Reputation: 1415
In the edittemplate of a gridview i have a dropdownlist which will provide a list of values when click on the edit button of each gridview row.
<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"));
}
so when i click on edit button the onload event will get fired and list down data from database. when i select an item of the dropdown, i need to access the dropdownlist selected value.
But whenever i changed the dropdown before selectedindexchanged the onload function invoked again which inturn refresh the content and return the selectedindex as 0.
how can i prevent this?
Upvotes: 2
Views: 6988
Reputation: 7097
Based on your comments I think you need to save your current value before you refresh every time. Lets assume that index 0 is always the "blank" value that we can ignore. Change your onload method slightly to provide the save and re-select
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;
}
}
Essentially, you need to save what you have selected before the update IF something is selected. Then after the update, reselect it. My code is just an example you may need to tweak it to actually capture and re-find the element that was actually selected before the update.
Upvotes: 3