This article will show you how you can bind the value
collection to dropdown list and add the “Select” value to the the dropdown in
asp.net using c#.net. In this article I have use sql server to retrieve the data
from the database.
Some of my previous articles are as follows: Bind
DropdownList Using Sql Server and Datatable in Asp.Net and C#, Validation
of Duplicate Email Id Of Registration Form Using C# in Asp.Net, Bind
Asp.net DropdownList Control by XML File Data Using DataSet in C#.Net,
DropdownList
Item With Custom Icon Image In Asp.net Using C#.Net, Bind
DropDownList In MVC WebGrid and Retrive Value Using Asp.net MVC, C#.Net,
Display
DropdownList Item By Group in Asp.Net MVC Using C#.Net, DropDownList
Bind By Using XmlDataSource in Asp.Net, Bind
DropDownList Using Entity Framework in ASP.Net MVC Using C#.
Here is the sql table which we will bind with dropdownlist
So for this article first we will create a new asp.net
application and add the below code into the .asp page.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2"
%>
<!DOCTYPE html
PUBLIC "-//W3C//DTD
XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Add
Select text in Dropdownlist in Asp.Net OR Adding Default Select Option in the
DropDownList Using C#.Net in Asp.Net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Country Name :<asp:DropDownList ID="DropDownList1"
runat="server"
Width="150px">
</asp:DropDownList>
</div>
</form>
</body>
</html>
|
Now add the below code into the .cs page for binding the dropdown
list and assigning the default value.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace WebApplication1
{
public partial class WebForm2 : System.Web.UI.Page
{
protected
void Page_Load(object
sender, EventArgs e)
{
if
(!IsPostBack)
{
BindDdl();
}
}
private
void BindDdl()
{
SqlConnection
con = new SqlConnection("Data Source=SQLEXPRESS;Initial
Catalog=Demo;Integrated Security=True");
string
queryValidate = "Select * from
CountryName";
DataTable
objdt = new DataTable();
SqlDataAdapter
da = new SqlDataAdapter(queryValidate,
con);
da.Fill(objdt);
if
(objdt.Rows.Count > 0)
{
DropDownList1.DataSource =
objdt;
DropDownList1.DataTextField =
"CountryName";
DropDownList1.DataValueField
= "Id";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0,
"Select Country");
}
}
}
}
|
In above code I have shown how you can bind the dropdown
list control using c#.net in asp.net. Just check the below code.
DropDownList1.Items.Insert(0,
"Select Country");
|
This piece of code is used for assigning the default value
to the dropdown list control. Now we have done run the code and check the output.
0 comments:
Please let me know your view