MR.G
MR.G

Reputation: 37

How to create dynamic dropdownlist with datasource from database

I trying to create dynamic dropdownlist with datasource from my access database. I want to add the dropdownlist into a table. Tried to do like this but it didn't work. How can I do it, and get the value if a item selected in dropdownlist? Thank you.

DropDownList mylist = new DropDownList();
            mylist.DataSource = DBConnectivity.getMovieSchedule(c.Movie_ID);
            mylist.DataTextField = "date";
            mylist.DataValueField = "id";
            mylist.DataBind();
            c6.Controls.Add(mylist);

Upvotes: 0

Views: 91

Answers (1)

ASH
ASH

Reputation: 20302

This should do it for you.

using (SqlConnection sqlConnection = new SqlConnection("connstring"))
{
    SqlCommand sqlCmd = new SqlCommand("SELECT * FROM YourTable", sqlConnection);
    sqlConnection.Open();
    SqlDataReader sqlReader = sqlCmd.ExecuteReader();

    while (sqlReader.Read())
    {
        ComboBox1.Items.Add(sqlReader["name"].ToString());
    }

    sqlReader.Close();
}

Upvotes: 1

Related Questions