Link to home
Start Free TrialLog in
Avatar of zintech
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(EventArgs e)
    {
                SqlConnection sqlConnectionString88 = new SqlConnection("Data Source=server;Initial Catalog=database;Persist Security Info=True;User ID=userid;Password=password");
        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.DataTextField = "VersionName";
        DropDownList2.DataBind();
        reader88.Close();
        sqlConnectionString88.Close();

        GridView1.DataBind();
    }
ASKER CERTIFIED SOLUTION
Avatar of Daniel Van Der Werken
Daniel Van Der Werken
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.