2015-06-12 85 views
0

我在一个Dropdownlist中列出了员工姓名。通过选择任何员工,我将在数据库的gridview中显示员工详细信息。C#ASP.Net中的DropDownList清除选择

默认情况下,dropdownlist将第一项作为选定项目。因此当我选择另一项时,它仅返回第一个索引。 我的代码:

protected void FilterBtn_Click(object sender, EventArgs e) 
{ 
    if (EmployeeList.SelectedIndex > -1) 
    { 
     sInitQuery = sInitQuery + " WHERE (EmployeeName ='" + EmployeeList.SelectedItem.ToString() + "')"; 
    } 
    if (GlobalCS.OpenConnection() == true) 
    { 
      GridView1.DataSource = null; 
      GridView1.DataBind();  

      MySqlCommand cmd = new MySqlCommand(sInitQuery, GlobalCS.objMyCon); 
      MySqlDataReader reader = cmd.ExecuteReader(); 
      GridView1.DataSource = reader; 
      GridView1.DataBind(); 
      reader.Close(); 
    } 
    GlobalCS.CloseConnection(); 
    EmployeeList.ClearSelection(); 
} 
+0

你能不能展示你的页面载入,问题是在那里我想,你是否在下拉菜单中调用了'if(!Page.IsPostBack)''? –

+0

protected void Page_Load(object sender,EventArgs e) DisplayDatainGrid(); // GridView中的所有数据 AddDataDropList(); //在Dropdownlist中加载数据 } – Anu

+0

设计建议:您不需要按钮。您可以直接在DropDownList.SelectedIndexChanged()事件中编写此代码。 –

回答

1

把你的页面加载代码,如果条件所以它只是执行时加载页面时,其他明智的第一次,每当回传发生页面加载时调用和你的代码得到执行这是因为它每次都被设置为第一项:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if(!Page.IsPostBack) 
    { 
     DisplayDatainGrid(); //All data in GridView 
     AddDataDropList(); //Load data in Dropdownlist 
    } 
} 

当前每当您的页面加载代码正在执行时,都不应该发生。

0

将EmployeeList.SelectedIndex添加到ViewState中。

protected void EmployeeList_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    ViewState.Add("employeeListIndex", EmployeeList.SelectedIndex); 
} 

然后,在Page_Load中,读取ViewState并将值赋给EmployeeList.SelectedIndex。

void Page_Load(object sender, EventArgs e) 
{ 
    if(ViewState["employeeListIndex"] != null) 
    { 
    EmployeeList.SelectedIndex = ViewState["employeeListIndex"]; 
    { 
}