如何在回发之前存储值

时间:2014-05-27 15:51:31

标签: c# asp.net

我有两个下拉列表,ddlstates和ddlcitys。

ddlstates有一个巴西状态列表,点击后,将ddlcity加载到该状态的城市。在此之前,一切都正常,但是当点击保存按钮来验证已完成的字段时,ddlcity会返回第一个选项。如何在回发之前存储信息ddlcity?

在代码后面,有代码加载ddlcity:

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();
    } 
}

1 个答案:

答案 0 :(得分:0)

很久以前问过,无论如何答案都可以帮助任何人。

在绑定任何下拉列表之前的页面加载事件中,请确保不要回发,然后在下拉列表中选择change events,下拉列表值将不会重新绑定,因此值不会更改。

提示:确保您的aspx页面启用了视图状态(默认情况下处于启用状态)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). 
 }
}