2014-01-21 61 views
2

在gridview的edittemplate中,我有一个下拉列表,当点击每个gridview行的编辑按钮时,它将提供一个值列表。如何获取gridview的dropdownlist的值?

<EditItemTemplate> 
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack=false OnLoad="DropDownList1_onload" 
    onselectedindexchanged="DropDownList1_SelectedIndexChanged"> 
</EditItemTemplate> 

C#

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    DropDownList ddl = (DropDownList)sender; 
    GridViewRow row = (GridViewRow)ddl.Parent.Parent; 
    int idx = row.RowIndex; 

    DropDownList txtECustCode = (DropDownList)row.Cells[0].FindControl("DropDownList1"); 
    string _text1 = txtECustCode.selectedvalue(); 

} 
protected void DropDownList1_onload(object sender, EventArgs e) 
{ 

     SqlConnection cn = new System.Data.SqlClient.SqlConnection("Data Source=CHANGEME1;Initial Catalog=Reflection;Integrated Security=True"); 
     SqlDataAdapter da = new SqlDataAdapter("select salary from employee", cn); 
     DataSet ds = new DataSet(); 
     var ddl = (DropDownList)sender; 
     da.Fill(ds); 
     cn.Close(); 
     ddl.DataSource = ds; 
     ddl.DataTextField = "salary"; 
     ddl.DataValueField = "salary"; 
     ddl.DataBind(); 
     ddl.Items.Insert(0, new ListItem("--Select--", "0")); 


} 

所以,当我在编辑按钮点击onload事件将被解雇,并从数据库列表下的数据。当我选择下拉菜单项时,我需要访问下拉列表选定的值。

但每当我改变了下拉之前的SelectedIndexChanged再次调用在onload功能,inturn刷新内容并返回的selectedIndex为0

我如何避免这种情况?

+0

没关系,误解你的代码。 – JNYRanger

+0

在更新发生的同时是否触发了'SelectedIndexChanged'事件,就像在选择过程中一样? – JNYRanger

+0

当我选择项目并点击更新按钮时,此事件将被解雇。 –

回答

3

根据您的意见,我认为您需要在每次刷新之前保存当前值。让我们假设索引0始终是我们可以忽略的“空白”值。改变你的onload方法稍有提供保存和重新选择

protected void DropDownList1_onload(object sender, EventArgs e) 
{ 
    //SAVE SELECTED 
    string selected = ""; 
    if(DropDownList1.Items.Count > 0 && DropDownList1.SelectedIndex != 0) 
    { 
     selected = DropDownList1.SelectedValue; 
    } 
    //UPDATE 
    SqlConnection cn = new System.Data.SqlClient.SqlConnection("Data Source=CHANGEME1;Initial Catalog=Reflection;Integrated Security=True"); 
    SqlDataAdapter da = new SqlDataAdapter("select salary from employee", cn); 
    DataSet ds = new DataSet(); 
    var ddl = (DropDownList)sender; 
    da.Fill(ds); 
    cn.Close(); 
    ddl.DataSource = ds; 
    ddl.DataTextField = "salary"; 
    ddl.DataValueField = "salary"; 
    ddl.DataBind(); 
    ddl.Items.Insert(0, new ListItem("--Select--", "0")); 
    //RESELECT 
    if(!String.IsNullOrEmpty(selected)) 
    { 
     DropDownList1.SelectedValue = selected; 
    } 
} 

本质上讲,你需要保存你已经更新之前,如果选择一些选择。然后在更新后重新选择它。我的代码只是一个示例,您可能需要调整它以实际捕获并重新找到更新前实际选定的元素。

+2

伟大的逻辑..随着一个小的改变,你让我的代码工作。万分感谢。 –

+0

没问题,很高兴我能帮忙! – JNYRanger