0

I have two dropdownlists, ddlstates and ddlcitys.

The ddlstates has a list of Brazilian states that when clicked, loads the ddlcitys with the cities of that state. Until then, everything works correctly, but when clicking the save button which makes verification of completed fields or not, the ddlcitys back to the first option. How to store the information ddlcitys before the postback?

In code behind, have code that loads the ddlcitys:

protected void ddlstates_TextChanged(object sender, EventArgs e)
{
    if (ddlstates.Text != "")
    {
        List<ListItem> cidades = new List<ListItem>();               
        SqlConnection conn = new SqlConnection(mytools.stringconection);
        SqlDataReader dr = null;
        conn.Open();
        SqlCommand cmd = new SqlCommand("select ciddesc from cidades where cidestsigla = '" + ddlstates.SelectedValue.ToString() + "' order by 1 asc");
        cmd.Connection = conn;
        dr = cmd.ExecuteReader();
        ddlcitys.Items.Clear();
        while (dr.Read())
        {
            cidades.Add(new ListItem(dr[0].ToString()));
        }
        dr.Close();
        conn.Close();
        ddlcitys.DataTextField = "Text";
        ddlcitys.DataValueField = "Value";
        ddlcitys.DataSource = cidades;
        ddlcitys.DataBind();
    } 
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Just `bind` the results to the `DropDownLists` if the page is not returning from a `PostBack`. `if (ddlstates.Text != "" && !IsPostBack())` – emerson.marini May 27 '14 at 15:53
  • I hope this is just a sample of your code. Otherwise do not forget to use parameterized queries: http://stackoverflow.com/questions/5468425/how-do-parameterized-queries-help-against-sql-injection – aleafonso May 27 '14 at 16:04

1 Answers1

0

Asked long time ago, anyway may the answer help anyone.

On your page load event before bind any of your dropdownlists, make sure that not post back, then on your dropdown select change events , your dropdown values will not re bind so values will not changed.

hint : make sure that your aspx page enable view state (by default enabled) read more.

 protected void Page_Load(object sender, EventArgs e) {
 if (!IsPostBack) {
  //this will called when your page loaded at first time, so bind your drop down values here.
 } else {
  //this will called on select change, don't bind your dropdown again, then values will be same (asp.net web forms viewstates will handle read more about viewstate). 
 }
}
Mohammad Ghanem
  • 688
  • 6
  • 20