zintech
asked on
C# drop down list Databinding
I have a C# DropDownList that I set the DataSource for in the following way in the OnPreRender() method. What happens is that after the user changes the value in the drop down list, the page refreshes, and the data source re-fills the DropDownList correctly, but automatically goes back to the first value. I was just wondering how to make this so that it stays with the value the user selected.
protected override void OnPreRenderComplete(EventA rgs e)
{
SqlConnection sqlConnectionString88 = new SqlConnection("Data Source=server;Initial Catalog=database;Persist Security Info=True;User ID=userid;Password=passwor d");
sqlConnectionString88.Open ();
SqlCommand cmd88 = new SqlCommand();
SqlDataReader reader88;
cmd88.Parameters.Add(new SqlParameter("@Proj", SqlDbType.Int, 10));
cmd88.Parameters["@Proj"]. Value = projectselected;
cmd88.CommandText = "SELECT column1 FROM table1 WHERE column2 = @Proj AND column3 = 'False'";
cmd88.CommandType = CommandType.Text;
cmd88.Connection = sqlConnectionString88;
reader88 = cmd88.ExecuteReader();
DropDownList2.DataSource = reader88;
DropDownList2.DataTextFiel d = "VersionName";
DropDownList2.DataBind();
reader88.Close();
sqlConnectionString88.Clos e();
GridView1.DataBind();
}
protected override void OnPreRenderComplete(EventA
{
SqlConnection sqlConnectionString88 = new SqlConnection("Data Source=server;Initial Catalog=database;Persist Security Info=True;User ID=userid;Password=passwor
sqlConnectionString88.Open
SqlCommand cmd88 = new SqlCommand();
SqlDataReader reader88;
cmd88.Parameters.Add(new SqlParameter("@Proj", SqlDbType.Int, 10));
cmd88.Parameters["@Proj"].
cmd88.CommandText = "SELECT column1 FROM table1 WHERE column2 = @Proj AND column3 = 'False'";
cmd88.CommandType = CommandType.Text;
cmd88.Connection = sqlConnectionString88;
reader88 = cmd88.ExecuteReader();
DropDownList2.DataSource = reader88;
DropDownList2.DataTextFiel
DropDownList2.DataBind();
reader88.Close();
sqlConnectionString88.Clos
GridView1.DataBind();
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
No points just re-iterate what DanZel said. Usually you don't need to DataBind on every postback. If you only bind once the DropDownList items will automatically remain in ViewState (unless you have it turned off) and the SelectedItem will remain on subsequent postbacks as well.