在 GridView 的编辑模板中,我有一个下拉列表,当单击每个 GridView 行的编辑按钮时,它将提供一个值列表。
<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 事件并列出数据库中的数据。当我选择下拉列表中的一项时,我需要访问下拉列表中选定的值。
但是每当我在 selectedindex 更改之前更改下拉列表时,就会再次调用 onload 函数,从而刷新内容并将 selectedindex 返回为 0。
如何防止这种情况发生?
最佳答案
根据您的评论,我认为您需要在每次刷新之前保存当前值。假设索引 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;
}
}
本质上,如果选择了某些内容,您需要在更新之前保存所选择的内容。然后更新后,重新选择它。我的代码只是一个示例,您可能需要对其进行调整以实际捕获并重新查找更新前实际选择的元素。
关于c# - 如何获取gridview的下拉列表的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21246861/