moe
moe

Reputation: 5249

Binding DropDownList using code behind in asp.net

The data binding works only when the page loads first time but it does not work otherwise. Somewhere in my page, i update and insert some new "Names" and i would like to show the newly added Names to be shown in the dropdownlist. But if i reload the page then the newly added Name will appear in the dropdownlist. How can i refresh the items in the dropdown? i thought my code should work. Pls help. thanks

 private void RefreshDropDown()
    {
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
        SqlConnection con2 = new SqlConnection(strConnString);
        SqlDataAdapter sda = new SqlDataAdapter();
        SqlCommand cmd1 = new SqlCommand("SELECT DISTINCT [Name] FROM [Main] order by Name asc");

        cmd1.Connection = con2;
        con2.Open();
        DropDownList1.DataSource = cmd1.ExecuteReader();
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "Name";
        DropDownList1.DataBind();
        con2.Close();

}

Upvotes: 2

Views: 5903

Answers (1)

user2483375
user2483375

Reputation: 26

I assume that you have some kind of button to do insert of new names. So on click of this button add call for RefreshDropDown() after you done inserting /updating your new names. That should do the trick.

Upvotes: 1

Related Questions