我试图通过我所做的一系列查询来填充我的下拉菜单,每当页面加载时自动进行。每当我在下拉列表中选择一个值并按下一个按钮时,它都会返回到第一个索引,所以我想知道是否有任何方法可以防止这个问题:
protected void Page_Load(object sender, EventArgs e)
{
Functions.username = "1"; // This is just to get rid of my login screen for testing puposes
DropDownList1.Items.Clear();
Functions.moduledatelister();
for (int i = 0; i <= Functions.moduledatelist.Count-1; i++) {
DropDownList1.Items.Add(Functions.moduledatelist.ElementAt(i));
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = Functions.DATES.ElementAt(DropDownList1.SelectedIndex).ToString();
}
按下按钮后,索引返回到 0,标签显示第一项的值。
最佳答案
是的,您可以使用 IsPostBack
property 来阻止它.您应该仅在初始加载时对 DropDownList
进行数据绑定(bind):
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// DataBindDropDown();
}
}
默认情况下,状态通过 ViewState
维护,因此无需在每次回发时重新加载所有项目。如果再次加载数据源,您还可以防止触发事件。
关于c# - 在页面加载时填充下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16691460/