我有一个在页面加载时填充的下拉列表,默认情况下,所选索引为0,并将其设置为一个emty字符串。在页面加载时,如果我们更改所选值,则所选索引方法不会触发。
if(!page.isPostback)
{
this.ddl.DataSource = list;
this.ddl.DataValueField = "Id";
this.ddl.DataTextField = "Name";
this.ddl.DataBind();
this.ddl.Items.Insert(0, String.Empty);
if (Request.QueryString != null)
{
string name = Request.QueryString["name"];
long Id = list.Where(item => item.Name == name).Select(item =>item.Id).SingleOrDefault();
this.selectedIndex = 1;
this.ddl.SelectedValue = Id.ToString();
}
}
答案 0 :(得分:1)
应该如此。如果要从事件和/或页面加载执行某些逻辑,请将该逻辑放在单独的方法中,以便您可以从页面加载中轻松调用它。
答案 1 :(得分:0)
private void BindList()
{
this.ddl.Items.Clear();
this.ddl.DataSource = list;
this.ddl.DataValueField = "Id";
this.ddl.DataTextField = "Name";
this.ddl.DataBind();
this.ddl.Items.Insert(0, String.Empty);
this.ddl.Items.SelectedIndex = 0;
}
if(!page.isPostback)
{
BindList();
if (Request.QueryString != null)
{
string name = Request.QueryString["name"];
long Id = list.Where(item => item.Name == name).Select(item =>item.Id).SingleOrDefault();
this.ddl.Items.ClearSelection();
this.ddl.Items.FindByValue(Id.ToString()).Selected = true;
}
}