2013-05-22 104 views
1

我试图通过一系列查询来填充我的下拉菜单,我会在页面加载时自动进行查询。每当我选择在下拉列表中选择价值,我按下一个按钮,它可以追溯到第一指标,所以我想知道是否有无论如何要防止出现此问题:在页面加载中填充DropDown

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

一个很好的理解是,你可以通过使用IsPostBack property阻止它。你应该数据绑定您的DropDownList仅在初始加载:

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

状态通过ViewState默认维护,因此无需重新加载在每次回传的所有项目。如果再次加载数据源,您还可以防止触发事件。

+0

非常感谢你:) –

1

Page_Load检查它是否回发。要了解为什么需要的IsPostBack和处理可能出现的类似问题,你需要的ASP.NET Page Life Cycle

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)); 
    } 
} 
+0

非常感谢你:) –

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)); 
    } 
    } 
} 
1

使用IsPostBack方法:

if(!IsPostBack)  
{  
    //enter your dropdownlist items add code here  
} 
相关问题