Retain Selected Value of dynamically bound dropdownlist after postback

坚强是说给别人听的谎言 提交于 2020-01-15 12:06:30

问题


I have a dropdownlist which I declare on the aspx markup like so:

<asp:DropDownList ID="State" runat="server"></asp:DropDownList>

Then I bind it on page load like so :

protected void Page_Load(object sender, EventArgs e)
    {
       BindDropdowns();
    }
private void BindDropdowns()
    {
        State.DataSource = DataAccess.GetStates();
        State.DataValueField = "FieldId";
        State.DataTextField = "FieldName";
        State.DataBind();
    }

The selected value is not retained after postback, I also cannot fire the selectedindexchangedevent. What's wrong ?


回答1:


please change your code like this:

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostback)
       BindDropdowns();
}

This means that your dropdown control is only bound once on first pageload




回答2:


You have to use the AutoPostBack="true".

<asp:DropDownList ID="State" AutoPostBack="true" 
 runat="server"></asp:DropDownList>

And also state that the witch event handler like this:

<asp:DropDownList ID="State" AutoPostBack="true" 
OnSelectedIndexChanged="State_SelectedIndexChanged" 
runat="server"></asp:DropDownList>

Then in code. Bind just when not post back:

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostback)
       BindDropdowns();
}

protected void State_SelectedIndexChanged(object sender, System.EventArgs e)  
{  
    var somevalue= State.SelectedValue;  
} 


来源:https://stackoverflow.com/questions/10390465/retain-selected-value-of-dynamically-bound-dropdownlist-after-postback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!