Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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>
share|improve this question
 
Is ddlistCity in an UpdatePanel? –  Kris Krause Oct 5 '11 at 14:21
 
no update panel –  Okan sar Oct 5 '11 at 14:30

2 Answers

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.

share|improve this answer
 
but I would like to receive the data. Is this impossible? –  Okan sar Oct 5 '11 at 14:28
 
Yes. You have to copy the selected item into a hidden field. However, you can NEVER access the value by using the SelectedValue property. –  Brian Mains Oct 5 '11 at 15:45
 
The reason is because you are doing everything on the client. The world works very different when you make that commitment. The main way most controls do this (ASP.NET AJAX and third party) to persist data back to the server is to put the value in a hidden field. Use a server-side hidden field, and that value posts back to the server. –  Brian Mains Oct 5 '11 at 15:46
 
Thank you. hidden field control when you use it right. Looking at the html tag, but it seems. Well static string? hidden field? is performance. And bought the data. When the page postback, the DropDownList is reset. Why? –  Okan sar Oct 5 '11 at 16:53
 
@Okan DropDownList does not persist values you add via javascript, which is what you are doing. It never will. You have to bind to the web service on every page load on the client. It's just the way Microsoft developed the control (the control was developed before they pushed the ASP.NET AJAX framework). You could see if a control here would suite your needs better: asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/Default.aspx –  Brian Mains Oct 5 '11 at 17:10
show 1 more comment

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;
share|improve this answer
 
null, but the DropDownList. I added the data does not exist within javasript. –  Okan sar Oct 5 '11 at 14:30
 
You want to get the SelectedValue in JavaScript? –  James Johnson Oct 5 '11 at 14:31
 
SelectedValue actually get the click event. then print the value of another database. –  Okan sar Oct 5 '11 at 14:38
 
Huh? That doesn't make any sense. SelectedValue is a property that returns a string... –  James Johnson Oct 5 '11 at 14:39
 
Do not take the value of the selected DropDownList id –  Okan sar Oct 5 '11 at 14:42
show 2 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.