开发者

asp.net javascript Object reference not set to an instance of an object

开发者 https://www.devze.com 2023-04-10 16:25 出处:网络
I do not speak very good English language. Telling problem. . net page, the javascript code to get data from the database. I add them into the DropDownList. When I run this I want to retrieve data fro

I do not speak very good English language. Telling problem. . net page, the javascript code to get data from the database. I add them into the DropDownList. When I run this I want to retrieve data from a selected DropDownList selection when I press the button. asp.net, but I see it as part of the DropDownList is empty. What can I do. Waiting for help. thanks.

codes

aspx.cs----------------

using Ajax;

public partial class Ajax_CSharp : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Ajax.Utility.RegisterTypeForAjax(typeof(Ajax_CSharp));
    }


    [Ajax.AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
    public string GetDataCity()
    {
        try
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["conn"]);
            SqlCommand cmd = new SqlCommand("SELECT * FROM Sehir", con);
            cmd.Connection.Open();

            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet("DataSet");
            adapter.Fill(ds, "Table");

            if ((ds.Tables[0].Rows.Count <= 0))
            {
                return "Empty";
            }
            else
            {
                string cityID = "";
                string cityName = "";
                for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                {
                    cityID += ds.Tables[0].Rows[i]["SehirID"].ToString() + ",";
                    cityName += ds.Tables[0].Rows[i]["SehirAdi"].ToString() + ",";
                }
                cityID = cityID.Substring(0, cityID.Length - 1);
                cityName = cityName.Substring(0, cityName.Length - 1);

                return cityID + "~" + cityName;
            }
        }
        catch
        {
            return "Error";
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string c;
        c = ddlistCity.SelectedItem.Value; **(error here. DropDownList is null.)**
    }

aspx page ----------------------

<script language="javascript" type="text/javascript">

    function GetDataCity() {
        var response;
        Ajax_CSharp.GetDataCity(GetData_CallBackCity);
    }

    function GetData_CallBackCity(response) {
        var response = response.value;

        if (response == "Empty") {
            alert("no record");
        }
        else if (response == 'Error') {
            alert("database not connection");
        }
        else {
            var arr = response.split("~");
            var cityID = arr[0].split(",");
            var cityName = arr[1].split(",");

            document.getElementById('ddlistCity').length = 0;
            var o = document.createElement("option");
            o.value = "select";
            o.text = "select"开发者_开发技巧;
            document.getElementById('ddlistCity').add(o);
            for (var i = 0; i < cityID.length; i++) {
                var o = document.createElement("option");
                o.value = cityID[i];
                o.text = cityName[i];
                document.getElementById('ddlistCity').add(o);
            }
        }
    }




    </script>
</head>
<body onload="GetDataCity();">
    <form id="form1" runat="server"  >
    <div>
        <asp:DropDownList ID="ddlistCity" runat="server" >
        </asp:DropDownList>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="ddlistCity" ErrorMessage="no select.." 
            InitialValue="seciniz" SetFocusOnError="True" ValidationGroup="genel">*</asp:RequiredFieldValidator>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" ValidationGroup="genel"/>
    </div>
    </form>
</body>


Change this:

protected void Button1_Click(object sender, EventArgs e)
{
     string c;
     c = ddlistCity.SelectedItem.Value; **(error here. DropDownList is null.)**
 }

To:

protected void Button1_Click(object sender, EventArgs e)
{
     string c;
     if (ddllistCity.SelectedItem != null)
        c = ddlistCity.SelectedItem.Value; **(error here. DropDownList is null.)**
 }

To prevent the error.

However, the error is that values are not persisted back to the server when they are created on the client. This means that you have to store the selected value of the drop down list in a hidden field in order to process it on the server. You also have to bind the drop down list on every page load, because again the server does not persist items created on the client.

HTH.


As Brian mentioned, using SelectedItem requires some logic to validate the the item is not null. You might have an easier time just using SelectedValue instead:

string selectedValue = DropDownList1.SelectedValue;
0

精彩评论

暂无评论...
验证码 换一张
取 消