1

我试图通过我所做的一系列查询来填充我的下拉菜单,每当页面加载时都会自动进行。每当我在下拉列表中选择一个值并按下一个按钮时,它都会返回到第一个索引,所以我想知道是否有任何方法可以防止这个问题:

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,标签显示第一项的值。

4

4 回答 4

4

是的,您可以通过使用IsPostBack属性来防止它。您应该DropDownList在初始加载时仅绑定数据:

protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack)
    {
        // DataBindDropDown();
    }
}

默认情况下,状态保持不变ViewState,因此无需在每次回发时重新加载所有项目。如果再次加载数据源,您还可以防止触发事件。

于 2013-05-22T12:16:19.167 回答
1

您必须处理页面类的 IsPostBack 属性:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
    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));
    }
    }
}
于 2013-05-22T12:16:21.237 回答
1

使用IsPostBack方法:

if(!IsPostBack)    
{    
  //enter your dropdownlist items add code here    
}
于 2013-05-22T12:16:55.210 回答
1

在 Page_Load 检查它是否是回发。要了解为什么需要 IsPostBack 并处理可能的类似问题,您需要很好地了解ASP.NET 页面生命周期

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack)
        return;

    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));
    }
}
于 2013-05-22T12:15:14.080 回答