Menus

Showing posts with label DropdownList. Show all posts
Showing posts with label DropdownList. Show all posts

Sunday, February 3, 2013

Bind Dropdownlist from Database - ASP.NET

Before implement this example first design one table UserInformation in your database as shown below
Column Name
Data Type
Allow Nulls
UserId
Int (set Identity=true)
No
UserName
varchar(50)
Yes
Location
Varchar(50)
Yes
Once table designed in database write the following code in your aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>how to show data in dropdownlist from database in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<b>Selected UserName:</b>
<asp:DropDownList ID="ddlCountry" runat="server" />
</div>
</form>
</body>
</html>
Now add the following namespaces in code behind

C# Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
After add namespaces write the following code in code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindContrydropdown();
}
}
/// <summary>
/// Bind COuntrydropdown
/// </summary>
protected void BindContrydropdown()
{
//conenction path for database
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserId,UserName FROM UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlCountry.DataSource = ds;
ddlCountry.DataTextField = "UserName";
ddlCountry.DataValueField = "UserId";
ddlCountry.DataBind();
ddlCountry.Items.Insert(0, new ListItem("--Select--", "0"));
con.Close();
}
}
VB.NET Code
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Partial Class VBSample
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindContrydropdown()
End If
End Sub
''' <summary>
''' Bind COuntrydropdown
''' </summary>
Protected Sub BindContrydropdown()
'conenction path for database
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("Select UserId,UserName FROM UserInformation", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
ddlCountry.DataSource = ds
ddlCountry.DataTextField = "UserName"
ddlCountry.DataValueField = "UserId"
ddlCountry.DataBind()
ddlCountry.Items.Insert(0, New ListItem("--Select--", "0"))
con.Close()
End Using
End Sub
End Class
Demo

Friday, December 14, 2012

Country State City DropDownList using AJAX in ASP.Net

In this article I will explain how to build Country State City Cascading DropDownList in ASP.Net i.e. Country State City Cascading DropDownList populated from Database and dependent on each other.
Database
For this example I have created a SQL Server database named Cascading_ddl, the script of which is attached along with the sample code.
In this database I have created tables for storing Country, State and City named as Countries, States and Cities respectively with schema shown below
Countries Table
country state city drop down list using ajax in asp.net

States Table
country state city drop down list in asp.net with c#

Cities Table
cascading dropdownlist for country/state/city in asp.net

Creating the Database
You will have to simply execute the script named CreateCascadingDatabase.sql stored in the SQL Folder of the attached sample and it will create the complete database with data.
HTML Markup
Below is the HTML Markup which contains three ASP.Net DropDownList controls each for Country, State and City. I have placed all the three DropDownLists inside ASP.Net UpdatePanel control to avoid full PostBack and make use of AJAX.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <table>
            <tr>
                <td>Country:</td>
                <td><asp:DropDownList ID="ddlCountries" runat="server" AutoPostBack = "true" OnSelectedIndexChanged = "Country_Changed">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>State:</td>
                <td>
                    <asp:DropDownList ID="ddlStates" runat="server" AutoPostBack = "true" OnSelectedIndexChanged = "State_Changed">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>City:</td>
                <td>
                    <asp:DropDownList ID="ddlCities" runat="server">
                    </asp:DropDownList>
                </td>
            </tr>
        </table>
    </ContentTemplate>
</asp:UpdatePanel>
 
Generic function to Bind and populate the ASP.Net DropDownList
Below is the generic function that will be used to populate and bind the ASP.Net DropDownList with data from the SQL Server Database
C#
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
    string conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    SqlCommand cmd = new SqlCommand(query);
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            con.Open();
            ddl.DataSource = cmd.ExecuteReader();
            ddl.DataTextField = text;
            ddl.DataValueField = value;
            ddl.DataBind();
            con.Close();
        }
    }
    ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
 
VB.Net
Private Sub BindDropDownList(ddl As DropDownList, query As String, text As String, value As String, defaultText As String)
    Dim conString As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
    Dim cmd As New SqlCommand(query)
    Using con As New SqlConnection(conString)
        Using sda As New SqlDataAdapter()
            cmd.Connection = con
            con.Open()
            ddl.DataSource = cmd.ExecuteReader()
            ddl.DataTextField = text
            ddl.DataValueField = value
            ddl.DataBind()
            con.Close()
        End Using
    End Using
    ddl.Items.Insert(0, New ListItem(defaultText, "0"))
End Sub
 
 
Populating the Country DropDownList
The Country DropDownList is populated on Page_Load event of the page as shown below
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string query = "select CountryId, CountryName from Countries";
        BindDropDownList(ddlCountries, query, "CountryName", "CountryId", "Select Country");
        ddlStates.Enabled = false;
        ddlCities.Enabled = false;
        ddlStates.Items.Insert(0, new ListItem("Select State", "0"));
        ddlCities.Items.Insert(0, new ListItem("Select City", "0"));
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim query As String = "select CountryId, CountryName from Countries"
        BindDropDownList(ddlCountries, query, "CountryName", "CountryId", "Select Country")
        ddlStates.Enabled = False
        ddlCities.Enabled = False
        ddlStates.Items.Insert(0, New ListItem("Select State", "0"))
        ddlCities.Items.Insert(0, New ListItem("Select City", "0"))
    End If
End Sub
 
 
Populating the State DropDownList
The State DropDownList is populated on OnSelectedIndexChanged event of the Country DropDownList as shown below
C#
protected void Country_Changed(object sender, EventArgs e)
{
    ddlStates.Enabled = false;
    ddlCities.Enabled = false;
    ddlStates.Items.Clear();
    ddlCities.Items.Clear();
    ddlStates.Items.Insert(0, new ListItem("Select State", "0"));
    ddlCities.Items.Insert(0, new ListItem("Select City", "0"));
    int countryId = int.Parse(ddlCountries.SelectedItem.Value);
    if (countryId > 0)
    {
        string query = string.Format("select StateId, StateName from States where CountryId = {0}", countryId);
        BindDropDownList(ddlStates, query, "StateName", "StateId", "Select State");
        ddlStates.Enabled = true;
    }
}
 
VB.Net
Protected Sub Country_Changed(sender As Object, e As EventArgs)
    ddlStates.Enabled = False
    ddlCities.Enabled = False
    ddlStates.Items.Clear()
    ddlCities.Items.Clear()
    ddlStates.Items.Insert(0, New ListItem("Select State", "0"))
    ddlCities.Items.Insert(0, New ListItem("Select City", "0"))
    Dim countryId As Integer = Integer.Parse(ddlCountries.SelectedItem.Value)
    If countryId > 0 Then
        Dim query As String = String.Format("select StateId, StateName from States where CountryId = {0}", countryId)
        BindDropDownList(ddlStates, query, "StateName", "StateId", "Select State")
        ddlStates.Enabled = True
    End If
End Sub
 
 
Populating the City DropDownList
The City DropDownList is populated on OnSelectedIndexChanged event of the State DropDownList as shown below
C#
protected void State_Changed(object sender, EventArgs e)
{
    ddlCities.Enabled = false;
    ddlCities.Items.Clear();
    ddlCities.Items.Insert(0, new ListItem("Select City", "0"));
    int stateId = int.Parse(ddlStates.SelectedItem.Value);
    if (stateId > 0)
    {
        string query = string.Format("select CityId, CityName from Cities where StateId = {0}", stateId);
        BindDropDownList(ddlCities, query, "CityName", "CityId", "Select City");
        ddlCities.Enabled = true;
    }
}
 
VB.Net
 
Protected Sub State_Changed(sender As Object, e As EventArgs)
    ddlCities.Enabled = False
    ddlCities.Items.Clear()
    ddlCities.Items.Insert(0, New ListItem("Select City", "0"))
    Dim stateId As Integer = Integer.Parse(ddlStates.SelectedItem.Value)
    If stateId > 0 Then
        Dim query As String = String.Format("select CityId, CityName from Cities where StateId = {0}", stateId)
        BindDropDownList(ddlCities, query, "CityName", "CityId", "Select City")
        ddlCities.Enabled = True
    End If
End Sub