0

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>
1
  • Is ddlistCity in an UpdatePanel? Commented Oct 5, 2011 at 14:21

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

but I would like to receive the data. Is this impossible?
Yes. You have to copy the selected item into a hidden field. However, you can NEVER access the value by using the SelectedValue property.
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.
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 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
0

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;

7 Comments

null, but the DropDownList. I added the data does not exist within javasript.
You want to get the SelectedValue in JavaScript?
SelectedValue actually get the click event. then print the value of another database.
Huh? That doesn't make any sense. SelectedValue is a property that returns a string...
Do not take the value of the selected DropDownList id
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.