This article will show you how you can bind a dropdown list
in asp.net using c#.net. In this I have bind the country table list from the
database.
First we will create a new table.
Now add some value into it.
First we will create a new table.
Now add some value into it.
So first we will create a new asp.net application and add a
dropdown list control. And rename it.
<asp:DropDownList ID="ddlcountry" runat="server"></asp:DropDownList>
|
Use the below code. If you want to bind the control on some
other event like button click the put it on that.
//Data base connection string
string connection = @"Server=LAPTOP-EVJEKV38\SQLEXPRESS;
Database=TestDB; Integrated Security=True";
SqlConnection
con = new SqlConnection(connection);
try
{
DataTable
dt = new DataTable();
//Sql query
string query = "Select * from
CountryMaster;";
//Execute the query
SqlDataAdapter da = new SqlDataAdapter(query, con);
con.Open();
da.Fill(dt);
//Bind the dropdown
ddlcountry.DataSource = dt;
ddlcountry.DataTextField = "CountryName";
ddlcountry.DataValueField = "Id";
ddlcountry.DataBind(); ddlcountry.Items.Insert(0, new ListItem("--Select Country--", "0"));
}
catch
{
}
finally
{
con.Close();
}
|
In above code I have made the connection. Then execute the query using SqlDataAdapter. And finally I have bind the datatable to the dropdown list control. Here is the piece of code which bind the dropdown.
ddlcountry.DataSource = dt;
ddlcountry.DataTextField = "CountryName";
ddlcountry.DataValueField = "Id"; ddlcountry.DataBind();
|
Now run the application and check the output.
0 comments:
Please let me know your view