是否可以在SelectedIndexChanged事件触发的回发时重新DataBind DropDownList?

Ape*_*ure 2 c# vb.net asp.net concurrency

假设我有一个产品类别的DropDownList和一个基于DropDownList中类别选择的产品ListView.当用户访问该页面时,存在可能出现一致性问题,因为属于新类别的新产品可能在用户浏览时被添加到库存中.

当用户选择要查看的其他类别(SelectedIndexChanged事件)并导致回发时,我希望DropDownList更新类别列表以包括同时添加的新类别,同时仍然可以更改所选指数.回发时,DropDownList似乎不支持此更新.那么我该如何处理这个并发问题呢?

Waq*_*aja 7

无论在Page_Init事件中检查回发下拉列表,您都需要绑定和重新绑定.它不会导致下拉列表的选定索引发生任何变化,您可以继续正常工作,在加载视图状态之前调用页面init方法.表示在此方法之后将选择您的下拉列表索引,您可以使用dropdown_selectedIndexChanged方法访问它.

有关ASP.Net页面生命周期的更多信息

编辑1:查看示例代码

protected void Page_Init(object sender, EventArgs e)
{
    // here you bind your dropdown
    // don't check IsPostBack
    DropdownList1.DataSource = db.GetCategories();
    DropdownList1.DataTextField = "TextField";
    DropdownList1.DataValueField = "ValueField";
    DropdownList1.DataBind();
}
Run Code Online (Sandbox Code Playgroud)

ASP.Net在Page_Init之后和Page_Load事件之前加载控件viewstate ,因此DropDownList1的selectedIndex不会受到影响,并且您得到了所需的结果.