Why does SelectedIndexChanged run again?!

I have 2 drop down boxes in the edit mode of my gridview. The first is used to populate the second (it is the second’s value that is saved back to the record) according to the selected value.

For some reason, when i save the changes, the SelectedIndexChanged method for the first dd runs again - resetting the second dd therefore losing the users selection!

Is there any reason why this would happen in a gridview? Code can be supplied if there is not an obvious reason for this :slight_smile:

cheers

monkey

Sounds like you do not have a if (!Page.IsPostBack) check on the page load, therefor, it is reloading the data on postback

Not sure what you mean - the method is not part of the page_load method so why would that make a difference?


protected void ddlParentValueListEdit_SelectedIndexChanged(object sender, EventArgs e)
	{
		DropDownList parentValueListEdit = (DropDownList)sender;
		//Get the Row from the DropDownList's parent DataControlFieldCell, who's parent is GridRowView.
		using (GridViewRow gvr1 = (GridViewRow)parentValueListEdit.Parent.Parent)
		{
			//Clear the list, add a None value and set this as the selected value - otherwise the bind tries to set to the original list
			//value which is no-longer in the list.
			((DropDownList)gvr1.FindControl("ddlParentValueEdit")).Items.Clear();
			((DropDownList)gvr1.FindControl("ddlParentValueEdit")).Items.Insert(0, new ListItem("None11", "0"));
			((DropDownList)gvr1.FindControl("ddlParentValueEdit")).SelectedValue = "0";
			
			if (parentValueListEdit.SelectedValue == "0")
			{
				((DropDownList)gvr1.FindControl("ddlParentValueEdit")).Items.Insert(0, new ListItem("None", "0"));
			}
			else
			{
				List<ListItems> list = ListItems.GetListValues(((DropDownList)sender).SelectedValue, "0", false);

				if (list.Count > 0)
				{
					((DropDownList)gvr1.FindControl("ddlParentValueEdit")).DataSource = list;
					((DropDownList)gvr1.FindControl("ddlParentValueEdit")).DataBind();
				}
			}
		}		
	}

Any ideas??? Anyone??? Please???

:injured:

Ignore everything i’ve just said SOMEONE had set enableviewstate to false on the gridview! I think they must have hacked into my system overnight and changed it :wink:

protected void Page_Load(object sender, EventArgs e)
{
bind();
}
protected void bind()
{
PlaceHolder1.Controls.Clear();
DropDownList ddl = new DropDownList() { AutoPostBack = true, ID=“ddl” };
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
ddl.Items.Add(“hi”);
ddl.Items.Add(“bye”);
PlaceHolder1.Controls.Add(ddl);
}
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
bind();
}

Thanks for that but the solution was far simpler! :slight_smile: