问题
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