Skip to content

How to Bind Table to DropDown List using sql server 2008 ?

Gunti Dilip

Asked Mar 30, 2012, 4:03 AM EDT1 answer
Share
LinkedInX
Hi,

        I had given sql connection in web.config file i should have to bind a table to dropdown list  using web.config file only .Please tell the code for it.


Thanks.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Senthilkumar
    0
    Hi,

    Add the connection string in the web.config file.

    Place the drop down control in your web page.

    Then add this code in your web.config file to fill the drop down list.

                SqlConnection sqlConnection = new SqlConnection();
                sqlConnection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connectionStringName"].ToString();
                sqlConnection.Open();
                string sqlQuery = "SELECT * FROM Users";
                SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
                sqlCommand.CommandType = CommandType.Text;
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
                DataSet dataSet = new DataSet();
                sqlDataAdapter.Fill(dataSet);
                sqlConnection.Close();

                ddlUsers.DataSource = dataSet.Tables[0];
                ddlUsers.DataBind();
                ddlUsers.DataTextField = "FirstName";
                ddlUsers.DataValueField = "UserID";


    Note: Make sure you have included System.Data and System.Data.SqlClient namespace.

    0