user3746002
user3746002

Reputation: 27

Bind a drop down list to SQL table in C#

How can i bind a DropDownList to SQL sever table in C#.

Here is the code i have so far:

string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sql = @"select Epic, Company from Company ";
SqlConnection conn = new SqlConnection(connString);
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet dataSet1 = new DataSet();
da.Fill(dataSet1, "Company");
DataTable dt = dataSet1.Tables["Company"];
DropDownList1.DataSource = dt;
DropDownList1.SelectedValue = "";

Upvotes: 0

Views: 2302

Answers (2)

Orlando Herrera
Orlando Herrera

Reputation: 3531

Well, when you don't know the name of your control (dropDown list) you can use something similar to this:

try
{
    //Add this couple of lines If you are adding controls dynamically and you need to find a specific control (by name)
    //--->DropDownList ddl = default(DropDownList);
    //--->ddl = (DropDownList)FindControl("DropDownList1");

    System.Data.DataTable subjects = new System.Data.DataTable();
    System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter("SELECT Id, Name FROM yourTable", "your connection");
    adapter.Fill(subjects);

    DropDownList1.DataSource = subjects;
    DropDownList1.DataTextField = "Name";
    DropDownList1.DataValueField = "id";
    DropDownList1.DataBind();
}
catch (Exception ex)
{
       // Handle the error
}

Upvotes: 0

optimus
optimus

Reputation: 856

First find the dropdown control.

DropDownList ddlStatus = default(DropDownList);
ddlStatus = (DropDownList)FindControl("DropDownList1");
//database connection, etc.
ddlStatus.DataSource = dt;
ddlStatus.SelectedValue = "";

Upvotes: 1

Related Questions