This article will show you how you can set the default value
to dropdownlist control in asp.net using c#.net from database ms sql server.
So in this article first I will tell you how you can bind the drop down and then i will tell you how you can set the default value from code behind in your c# code.
So in this article first I will tell you how you can bind the drop down and then i will tell you how you can set the default value from code behind in your c# code.
So first we will create a database table
After creating the table we will add some data in it.
Now here is the dropdown on your page
<asp:DropDownList ID="ddlcountry" runat="server"></asp:DropDownList>
|
Now here is the code to bind the dropdown, and set the
default value to the drop down.
//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();
//------------Set the
default value-------------
ddlcountry.Items.Insert(0, new ListItem("--Select
Country--", "0"));
}
catch
{
}
finally
{
con.Close();
}
|
In above code please check the highlighted part of the code
rest code is for binding the dropdown list.
ddlcountry.Items.Insert(0,
new ListItem("--Select
Country--", "0"));
|
The above code is used for setting the default value of the
dropdown list in asp.net. Now run the page
and check the output.
0 comments:
Please let me know your view