Thursday 2 January 2014

Populate Cascading DropDownList On Selection ASP.NET

Populate Cascading DropDownList On Selection ASP.NET
Populate Cascading DropDownList In Asp.Net C# VB.NET Based On Selection Of Other DropDown In SelectedIndexChanged Event. binding state DropDown based on selection of Country DropDownlist and then populating Cities on selection of State.

There are several situations where we need to populate second or third dropdownlist list based on selection of first or second dropdwonlist in asp.net.

populate dropdown based on selection in SelectedIndexChanged Event asp.net
For this we need to write code in code behind in the SelectedIndexChanged Event of respective Dropdownlist to implement the cascading of DropDowns.

HTML SOURCE OF PAGE
 
   1:  <form id="form1" runat="server">
   2:  <div>
   3:  <table><tr>
   4:  <td><strong>Country :</strong></td>
   5:  <td><asp:DropDownList ID="ddlCountry" runat="server"
   6:                        AutoPostBack="True" 
   7:                        onselectedindexchanged=
   8:                   "ddlCountry_SelectedIndexChanged">
   9:      </asp:DropDownList>
  10:  </td>
  11:   
  12:  <td><strong>State:</strong></td>
  13:  <td><asp:DropDownList ID="ddlState" runat="server" 
  14:                        AutoPostBack="True" 
  15:                        onselectedindexchanged=
  16:                   "ddlState_SelectedIndexChanged">
  17:      </asp:DropDownList></td>
  18:   
  19:  <td><strong>City:</strong></td>
  20:  <td><asp:DropDownList ID="ddlCity" runat="server" 
  21:                        AutoPostBack="True">
  22:      </asp:DropDownList></td>
  23:  </tr>
  24:  <tr><td><asp:Label ID="lblMsg" runat="server">
  25:         </asp:Label>
  26:      </td>
  27:  </tr>  
  28:  </table>
  29:   </div>
  30:   </form>

Write following code in respective events of page and dropdownlists.

C# CODE
001protected void Page_Load(object sender, EventArgs e)
002    {
003        if (!IsPostBack)
004        {
005            FillCountry();
006        }
007    }
008    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
009    {
010        int CountryID = Convert.ToInt32(ddlCountry.SelectedValue.ToString());
011        FillStates(CountryID);
012        ddlCity.SelectedIndex = 0;
013    }
014    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
015    {
016        int StateID = Convert.ToInt32(ddlState.SelectedValue.ToString());
017        FillCities(StateID);
018    }
019 
020    private void FillCountry()
021    {
022        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
023        SqlConnection con = new SqlConnection(strConn);
024        SqlCommand cmd = new SqlCommand();
025        cmd.Connection = con;
026        cmd.CommandType = CommandType.Text;
027        cmd.CommandText = "SELECT CountryID, CountryName FROM Country";
028        DataSet objDs = new DataSet();
029        SqlDataAdapter dAdapter = new SqlDataAdapter();
030        dAdapter.SelectCommand = cmd;
031        con.Open();
032        dAdapter.Fill(objDs);
033        con.Close();
034        if (objDs.Tables[0].Rows.Count > 0)
035        {
036            ddlCountry.DataSource = objDs.Tables[0];
037            ddlCountry.DataTextField = "CountryName";
038            ddlCountry.DataValueField = "CountryID";
039            ddlCountry.DataBind();
040            ddlCountry.Items.Insert(0, "--Select--");
041        }
042        else
043        {
044            lblMsg.Text = "No Countries found";
045        }
046    }
047 
048    private void FillStates(int countryID)
049    {
050        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
051        SqlConnection con = new SqlConnection(strConn);
052        SqlCommand cmd = new SqlCommand();
053        cmd.Connection = con;
054        cmd.CommandType = CommandType.Text;
055        cmd.CommandText = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID";
056        cmd.Parameters.AddWithValue("@CountryID", countryID);
057        DataSet objDs = new DataSet();
058        SqlDataAdapter dAdapter = new SqlDataAdapter();
059        dAdapter.SelectCommand = cmd;
060        con.Open();
061        dAdapter.Fill(objDs);
062        con.Close();
063        if (objDs.Tables[0].Rows.Count > 0)
064        {
065            ddlState.DataSource = objDs.Tables[0];
066            ddlState.DataTextField = "StateName";
067            ddlState.DataValueField = "StateID";
068            ddlState.DataBind();
069            ddlState.Items.Insert(0, "--Select--");
070        }
071        else
072        {
073            lblMsg.Text = "No states found";
074        }
075    }
076 
077    private void FillCities(int stateID)
078    {
079        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
080        SqlConnection con = new SqlConnection(strConn);
081        SqlCommand cmd = new SqlCommand();
082        cmd.Connection = con;
083        cmd.CommandType = CommandType.Text;
084        cmd.CommandText = "SELECT CityID, CityName FROM City WHERE StateID =@StateID";
085        cmd.Parameters.AddWithValue("@StateID", stateID);
086        DataSet objDs = new DataSet();
087        SqlDataAdapter dAdapter = new SqlDataAdapter();
088        dAdapter.SelectCommand = cmd;
089        con.Open();
090        dAdapter.Fill(objDs);
091        con.Close();
092        if (objDs.Tables[0].Rows.Count > 0)
093        {
094            ddlCity.DataSource = objDs.Tables[0];
095            ddlCity.DataTextField = "CityName";
096            ddlCity.DataValueField = "CItyID";
097            ddlCity.DataBind();
098            ddlCity.Items.Insert(0, "--Select--");
099        }
100        else
101        {
102            lblMsg.Text = "No Cities found";
103        }
104    }

VB.NET
01Protected Sub Page_Load(sender As Object, e As EventArgs)
02 If Not IsPostBack Then
03  FillCountry()
04 End If
05End Sub
06Protected Sub ddlCountry_SelectedIndexChanged(sender As Object, e As EventArgs)
07 Dim CountryID As Integer = Convert.ToInt32(ddlCountry.SelectedValue.ToString())
08 FillStates(CountryID)
09 ddlCity.SelectedIndex = 0
10End Sub
11Protected Sub ddlState_SelectedIndexChanged(sender As Object, e As EventArgs)
12 Dim StateID As Integer = Convert.ToInt32(ddlState.SelectedValue.ToString())
13 FillCities(StateID)
14End Sub
15 
16Private Sub FillCountry()
17 Dim strConn As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
18 Dim con As New SqlConnection(strConn)
19 Dim cmd As New SqlCommand()
20 cmd.Connection = con
21 cmd.CommandType = CommandType.Text
22 cmd.CommandText = "SELECT CountryID, CountryName FROM Country"
23 Dim objDs As New DataSet()
24 Dim dAdapter As New SqlDataAdapter()
25 dAdapter.SelectCommand = cmd
26 con.Open()
27 dAdapter.Fill(objDs)
28 con.Close()
29 If objDs.Tables(0).Rows.Count > 0 Then
30  ddlCountry.DataSource = objDs.Tables(0)
31  ddlCountry.DataTextField = "CountryName"
32  ddlCountry.DataValueField = "CountryID"
33  ddlCountry.DataBind()
34  ddlCountry.Items.Insert(0, "--Select--")
35 Else
36  lblMsg.Text = "No Countries found"
37 End If
38End Sub
39 
40Private Sub FillStates(countryID As Integer)
41 Dim strConn As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
42 Dim con As New SqlConnection(strConn)
43 Dim cmd As New SqlCommand()
44 cmd.Connection = con
45 cmd.CommandType = CommandType.Text
46 cmd.CommandText = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID"
47 cmd.Parameters.AddWithValue("@CountryID", countryID)
48 Dim objDs As New DataSet()
49 Dim dAdapter As New SqlDataAdapter()
50 dAdapter.SelectCommand = cmd
51 con.Open()
52 dAdapter.Fill(objDs)
53 con.Close()
54 If objDs.Tables(0).Rows.Count > 0 Then
55  ddlState.DataSource = objDs.Tables(0)
56  ddlState.DataTextField = "StateName"
57  ddlState.DataValueField = "StateID"
58  ddlState.DataBind()
59  ddlState.Items.Insert(0, "--Select--")
60 Else
61  lblMsg.Text = "No states found"
62 End If
63End Sub
64 
65Private Sub FillCities(stateID As Integer)
66 Dim strConn As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
67 Dim con As New SqlConnection(strConn)
68 Dim cmd As New SqlCommand()
69 cmd.Connection = con
70 cmd.CommandType = CommandType.Text
71 cmd.CommandText = "SELECT CityID, CityName FROM City WHERE StateID =@StateID"
72 cmd.Parameters.AddWithValue("@StateID", stateID)
73 Dim objDs As New DataSet()
74 Dim dAdapter As New SqlDataAdapter()
75 dAdapter.SelectCommand = cmd
76 con.Open()
77 dAdapter.Fill(objDs)
78 con.Close()
79 If objDs.Tables(0).Rows.Count > 0 Then
80  ddlCity.DataSource = objDs.Tables(0)
81  ddlCity.DataTextField = "CityName"
82  ddlCity.DataValueField = "CItyID"
83  ddlCity.DataBind()
84  ddlCity.Items.Insert(0, "--Select--")
85 Else
86  lblMsg.Text = "No Cities found"
87 End If
88End Sub

Build and run the code.

No comments:

Post a Comment