user3452010
user3452010

Reputation: 25

How to populate listbox with SQL Database dynamically

I have a database with following structure. now I want to populate a listbox with this table in c#. how can I do this?

Column      | Type
------------------------------
ID          | Unique Identifier;
txtname     | nvarchar(50);
txtcitycode | nchar(5);

Upvotes: 0

Views: 141

Answers (1)

Hadi Barak
Hadi Barak

Reputation: 478

You can use this code:

using (SqlConnection con = new SqlConnection(YOUR_CONNECTION_STRING))
        {
            using (SqlCommand cmd = new SqlCommand("Select ID, txtname, txtcitycode from YOUR_TABLE", con))
            {
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                DropDownList1.DataTextField = "txtname";
                DropDownList1.DataValueField = "txtcitycode";
                DropDownList1.DataSource = dt;
                DropDownList1.DataBind();
            }
        }

Replace "YOUR_CONNECTION_STRING" with connection string and "YOUR_TABLE" with your table name

if you dont know connection string, you can find some useful information in this website: http://www.connectionstrings.com/

Upvotes: 1

Related Questions