开发者

.ASP DropDownList not working properly on first postback with dyanamic DataSource

Here is the problem - there is DropDownList inside panel. DropDownList.DataSorce is prefilled in Load_Page method (C#). AutoPostBack is enabled. ViewState also is enabled. Problem does not appear on first dropdownlist in first panel. Problem is following - after choosing value value changed is raised, but dropdownlist has forgot all its parameters (value, datasource, etc.). Clicking one more time on dropdownlist and now it works fine.

Thus - dropdownlist starts to work correctly only after first time value is choosen.

1) Select value

2) One (selectedindex = 0)

3) Select value (value got lost)

4) One (selectedindex is correct)

I have found ugly workaround using Request.Form[dropdown.UniqueId] to manualy fetch selected value and restore it after setting DataSource for second time but this is bad solution and looks ugly.

I have spent 8+h on this issue and this is driving me craazy!

PS this error happens only on 2+ pannel. First pannel's controls work as expected!

Here some code -

Page_Load looks like this

if (ViewState["dropdownset"] == null) // tried many other thing here as well...
{
   dropdown.DataSource = new dictionary<string, string>();
   dropDown.EnableViewState = true;
   ... fill in some data in datasource
   dropdown.SelectedValue = "0"; //some key from dictionary (verified to work)
   dropdown.BindData();
   ViewState["dropdownset"] = true;
}

like 开发者_如何学Pythonthis. As i said - no magic at all! It just won't work. This ain't regular problem since I spent 8h on this one and I am top performer among programers! ;)


You still need to set DataSource on each page load, but not DataBind.

Regarding your comment on Jack Marchetti's answer - I don't understand how the code you posted fits in with "adding new panels." Are you dynamically creating a panel and/or the dropdown control?


I had the same issue. I have a DropDownListBox and set EnableViewState to false. On every postback, I need to repopulate the list box from a table in my database. However, the very first time an item in the list box is selected, the SelectedIndexChanged event is fired, but the SelectedItem.Value is “0”. However, the second time an item in the list box is selected, the SelectedItem.Value is correct. My solution was to use a SqlDataAdapter.


If you have ViewState enabled, then you don't need to manually reset it.

Your Page_Load should look something like this:

protected void Page_Load() {

 if(!Page.IsPostBack) {
      dropdown.DataSource = //whatever your datasource is
      dropdown.DataBind();
 }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜