你好我试图在下拉列表中选择它时从列表中删除一个值,但是第一次调用Button1_Click1它总是删除第一个索引(在这种情况下为a)我不知道发生了什么< / p>
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;
}
答案 0 :(得分:0)
Page_Load
在每个回发后调用,并且在点击处理程序之前调用。所以当你这样做时:
DropDownList1.DataSource = Alph;
DropDownList1.DataBind();
你正在破坏DropDownList1
并重新填充它。然后当你检查它时:
Label1.Text = DropDownList1.Text;
Alph.RemoveAt(DropDownList1.SelectedIndex);
它将向您显示默认值,这意味着它所绑定的数据源中的第一个值。
您可以通过使用条件仅在初始页面加载而不是回发时填充它来阻止这种情况:
if (!IsPostBack)
{
DropDownList1.DataSource = Alph;
DropDownList1.DataBind();
}