Tuesday 1 April 2014

How to bind data to dropdown list from Database in ASP.NET

In this article I will explain how to bind data to dropdown list from Database in ASP.NET.
I have one table in DataBase.

1.      City Table (tblCity)

First we need to establish a connection in Web.config file.

<connectionStrings>
<add name="connectionString" connectionString="Data Source=LocalHost;uid=sa1;password=Con@123;Initial Catalog=practice"/>
</connectionStrings>

Below is the page design.




<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Populate dropdown List</title>
</head>
<body>
<form id="form1" runat="server">
<table align="center">
<tr>
<td colspan="2" style="color: maroon; font-size:large;">
<b><u>Populate dropdown list</u></b>
</td>
</tr>
<tr>
<td colspan="2" height="20px"></td>
</tr>
<tr>
<td>Select City:
</td>
<td>
<asp:DropDownList ID="ddlCity" runat="server" Width="150px"></asp:DropDownList>
</td>
</tr>
</table>
</form>
</body>
</html>

Below is the total code for Dropdowns list code.

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

public partial class Dropdown : System.Web.UI.Page
{
SqlConnection conCascading = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindCitydropdown();
}
}
protected void BindCitydropdown()
{
conCascading.Open();
SqlCommand cmdCountry = new SqlCommand("select * from tblCity", conCascading);
SqlDataAdapter daCountry = new SqlDataAdapter(cmdCountry);
DataSet dsCountry = new DataSet();
daCountry.Fill(dsCountry);
conCascading.Close();
ddlCity.DataSource = dsCountry;
ddlCity.DataTextField = "CityName";
ddlCity.DataValueField = "CityID";
ddlCity.DataBind();
ddlCity.Items.Insert(0, new ListItem("--Select City--", "0"));

}
}

Output:



No comments:

Post a Comment