在gridview的edittemplate中,我有一个下拉列表,当点击每个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事件将被触发并从数据库中列出数据。当我选择下拉列表的项目时,我需要访问下拉列表选择的值。
但每当我在selectedindexchanged之前更改下拉列表时,再次调用onload函数,这会刷新内容并将selectedindex返回为0.
我该如何防止这种情况?
答案 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;
}
}
基本上,您需要在更新之前保存您选择的内容。然后在更新后重新选择它。我的代码只是一个示例,您可能需要调整它以实际捕获并重新找到在更新之前实际选择的元素。