2014-10-02 90 views
0

你好我试图删除列表中的一个值,当它在一个下拉列表中选择,但第一次我调用Button1_Click1它总是删除第一个索引(在此情况下)我不知道什么是对asp.net下拉列表第一次返回第一个值

List<String> Alph = new List<String>(); 

protected void Page_Load(object sender, EventArgs e) 
{ 
    if ((List<String>)Session["Alpha"] != null) 
    { 
     Alph = (List<String>)Session["Alpha"]; 
    } 
    else 
    { 
     fillAlpha(); 
    } 


} 
public void fillAlpha() 
{ 
    Alph = new List<String>() { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; 

    Alph.Sort(); 
    DropDownList1.DataSource = Alph; 
    DropDownList1.DataBind(); 

} 

protected void Button1_Click1(object sender, EventArgs e) 
{ 
    Label1.Text = DropDownList1.Text; 
    Alph.RemoveAt(DropDownList1.SelectedIndex); 
    DropDownList1.DataSource = Alph; 
    DropDownList1.DataBind(); 
    Session["Alpha"] = Alph; 
} 
+1

你缺少'如果' – Vivekh 2014-10-02 18:44:26

回答

0

Page_Load中去,是对每后回调用,并且它点击处理程序之前调用。所以,当你这样做:

DropDownList1.DataSource = Alph; 
DropDownList1.DataBind(); 

你重挫DropDownList1和重新填充它。然后,当你审视它:

Label1.Text = DropDownList1.Text; 
Alph.RemoveAt(DropDownList1.SelectedIndex); 

它要告诉你的默认值,这意味着无论是在数据源中的第一个值到它的约束。

可以防止这种通过使用条件,只填充它的初始页面加载,而不是后回:

if (!IsPostBack) 
{ 
    DropDownList1.DataSource = Alph; 
    DropDownList1.DataBind(); 
} 
+0

非常感谢你这工作(的IsPostBack!)完美,我看到我做错了! – Xaviex 2014-10-06 16:17:37

相关问题