How to make Dynamic DropDownList in Asp.net

Step 1: Create a new Asp.net Empty Web Site


Step 2: Create new Web form then take 2 DropDownList and also take 2 label denoting the DropDownLinst eg like this:





Step 3: now give Different ID to both DropDownList Eg: StateDDL to state DropDownList and CityDDL to city DropDownList eg like this :




Step 4: Now Create new SQL Server Database then it will ask you to add App_Data click yes now go to server explorer and create two new tables named State and City

If u are using Visual Studio 2010 then after entering data just ctrl+s n it will ask u name for State table give name State and for City table give name City

And if you are using Visual Studio 2012 just enter a data and give name in its code section like this:
CREATE TABLE [dbo].[State]
and for saving table click on update button in upper left corner and then click on update database.

for State:
*** Note StateID is Primary Key ***




And for City:
*** Note CityID is Primary Key we need to make a Foregin Key for StateID I will specify it later on ***





Step 5: To give Foregin key in visual studio 2012 in Right side of City table Right Click on Foregin Key and create new Foregin Key now in code section of City table i.e.T-SQL instead of this code :

CONSTRAINT [FK_City_State] FOREIGN KEY ([Column]) REFERENCES [ToTable]([ToTableColumn])

write this code :

CONSTRAINT [FK_City_State] FOREIGN KEY ([StateID]) REFERENCES [State]([StateID])

and update city database

To give Foregin key in visual studio 2010 just create both table and give data and then go to server explorer inside your database create new Database Diagram and then select both City and State table and then click StateID from State table and drag it to StateID of City table and click ok on both foregin key creation tab just like this:





Save the diagram give the name location and foregin key is created in visual studio 2010

Step  6: Now again go to web form and go to .cs file of our web form and write this all code in start:

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.Configuration;
using System.Data;

now again go to design part for creatin connection string of our database simply take new SqlDataSource from toolbox and click on > button and click on configure data source select our database click next now in this section we will specify a new connection string for our database
*** Note: the check box of Yes save this Connection string as should be checked *** now give name to connection string and keep that name in mind for eg I have given this name:




click next and again next and click on finish now the connection string is created for our database

and now delete SqlDataSource

Step 7: Go to .cs file of our web form and write this code before PageLoader event

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DDLConStr"].ConnectionString);

give your connection string name instead of DDLConStr in above code

and write bind code below connection string code:

public void Bind_StateDDL()
    {
        con.Open();
        SqlCommand com = new SqlCommand("Select StateID,State from State", con);
        SqlDataReader dr = com.ExecuteReader();
        StateDDL.DataSource = dr;
        StateDDL.Items.Clear();
        StateDDL.Items.Add(".....Plese select State.....");
        StateDDL.DataTextField = "State";
        StateDDL.DataValueField = "StateID";
        StateDDL.DataBind();
        con.Close();
    }
    public void Bind_CityDDL()
    {
        con.Open();
        SqlCommand com = new SqlCommand("Select CityID,City from City where StateID='" + StateDDL.SelectedValue + "'", con);
        SqlDataReader dr = com.ExecuteReader();
        CityDDL.DataSource = dr;
        CityDDL.Items.Clear();
        CityDDL.Items.Add(".....Plese select City.....");
        CityDDL.DataTextField = "City";
        CityDDL.DataValueField = "CityID";
        CityDDL.DataBind();
        con.Close();
    }

*** Note: you should write City dropdownlist ID instead of CityDDL and State dropdownlist ID instead of  SateDDL if  you given same ID as I have given to both DropDownList so keep it as it is ***  

in PageLoader write this code:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind_StateDDL();
        }
    }

Step 8: Design part of our web form and double click on State DropDownList and create SelectedIndexChanged event on State DropDownList and write this code in side it:

protected void StateDDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        Bind_CityDDL();
    }

Step 9:
go to Design part and turn on AutoPostBack of State DropDownList

Step 10: Now go to server explorer and add data in State table by right click on state table and click on show table data
give data in State table just like this:



hear StateID is ID of States named in State column Save the table

and now give data in City table just like this:



 hear the logic is we have gave foregin key to City table in Row of StateID so which ever StateID data i.e. no. you will give in StateID Column it will relate to State table the logic is explained in bellow image properly :




Step 11:
and Save the changes on both .cs and .aspx and go to design and ctrl+F5 to run the web site

it will look like this:





as soon as you will select any state that states, city names will be displayed in city DropDownList
Video of how it will be displayed in end:







All Codes:

DDL1.aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DDL1.aspx.cs" Inherits="DDL1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <br />
&nbsp;&nbsp;&nbsp;
        <asp:Label ID="Label1" runat="server" Font-Bold="True" Text="State :"></asp:Label>
&nbsp;
        <asp:DropDownList ID="StateDDL" runat="server" AutoPostBack="True" OnSelectedIndexChanged="StateDDL_SelectedIndexChanged" Width="242px">
        </asp:DropDownList>
        <br />
        <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Label ID="Label2" runat="server" Font-Bold="True" Text="City :"></asp:Label>
&nbsp;
        <asp:DropDownList ID="CityDDL" runat="server" OnSelectedIndexChanged="CityDDL_SelectedIndexChanged" Width="242px">
        </asp:DropDownList>
   
    </div>
    </form>
</body>
</html>


DDL1.aspx.cs Code:



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.Configuration;
using System.Data;

public partial class DDL1 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DDLConStr"].ConnectionString);
    public void Bind_StateDDL()
    {
        con.Open();
        SqlCommand com = new SqlCommand("Select StateID,State from State", con);
        SqlDataReader dr = com.ExecuteReader();
        StateDDL.DataSource = dr;
        StateDDL.Items.Clear();
        StateDDL.Items.Add(".....Plese select State.....");
        StateDDL.DataTextField = "State";
        StateDDL.DataValueField = "StateID";
        StateDDL.DataBind();
        con.Close();
    }
    public void Bind_CityDDL()
    {
        con.Open();
        SqlCommand com = new SqlCommand("Select CityID,City from City where StateID='" + StateDDL.SelectedValue + "'", con);
        SqlDataReader dr = com.ExecuteReader();
        CityDDL.DataSource = dr;
        CityDDL.Items.Clear();
        CityDDL.Items.Add(".....Plese select City.....");
        CityDDL.DataTextField = "City";
        CityDDL.DataValueField = "CityID";
        CityDDL.DataBind();
        con.Close();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind_StateDDL();
        }
    }
    protected void StateDDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        Bind_CityDDL();
    }
}

Comments

Popular posts from this blog

Java Project of restaurant dish menu System with File handling java IO | With Code

Custom MenuItem with Notification on it

Encoded Password Save in database | asp.net with c#