Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi.. This is Ibrahim,
How to write the code for dropdownlist if i select the country name in first ddl then it automatically states names loaded in 2nd ddl...?
Posted
Comments
[no name] 5-Jul-14 13:55pm    
In the SelectedIndexChanged event for the first drop down list, query your database for the states based on the country selected, fill the second drop down list with the result of your query.

It seems that you are trying to implement a Cascading DropDownList right?
Here's example using the ADO.NET way:
   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDropDownList1();
        }
    }

 private void BindDropDownList1()
    {
        DataTable dt = new DataTable();
        SqlConnection connection = new SqlConnection(GetConnectionString());
        try
        {
            connection.Open();
            string sqlStatement = "SELECT ColumnName * FROM TableName";
            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
            sqlDa.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                DropDownList1.DataSource =dt;
                DropDownList1.DataTextField = "ColumnName"; // the items to be displayed in the list items
                DropDownList1.DataValueField = "ColumnName"; // the id of the items displayed
                DropDownList1.DataBind();
            }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Fetch Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            connection.Close();
        }
    }

   protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
   { 
      BindDropDownList2(DropDownList1.SelectedItem.Text); 
   }

private string GetConnectionString()
    {
       //calling up the connection string that was set up from the web config file
        return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
    }


    private void BindDropDownList2(string field)
    {
        DataTable dt = new DataTable();
        SqlConnection connection = new SqlConnection(GetConnectionString());
        try
        {
            connection.Open();
            string sqlStatement = "SELECT * FROM Table WHERE ColumnName = @Value1";
            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
            sqlCmd .Parameters.AddWithValue("@Value1", field)
            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
            sqlDa.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                DropDownList2.DataSource =dt;
                DropDownList2.DataTextField = "ColumnName"; // the items to be displayed in the list items
                DropDownList2.DataValueField = "ColumnName; // the id of the items displayed
                DropDownList2.DataBind();
            }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Fetch Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            connection.Close();
        }
    }

Don't forget to add the following Namespaces below for you to make it work

Using System.Data;
Using System.Data.SqlClient;

Also don't forget to set AutoPostBack to TRUE in your first DropDownList to fire up the SelectedIndexChanged event
 
Share this answer
 
Try with :
Add a web page to the solution and copy and paste this into the .aspx page:
ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="cascading.aspx.cs" Inherits="counrtybasedropdown.cascading" %>

<!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 id="Head1" runat="server">
    <title></title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
        <center>
           <h3>
                Cascading DropDownList for Country/State/City in ASP.Net</h3>
            <table>
                <tr>
                   <td>
                        Select a Country :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged">
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>
                        Select a State :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlState" runat="server" Enabled="false" AutoPostBack="true"
                            OnSelectedIndexChanged="ddlState_SelectedIndexChanged">
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>
                        Select a City :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlCity" runat="server" Enabled="false">
                       </asp:DropDownList>
                   </td>
                </tr>
            </table>
        </center>
    </div>
 </form>
</body>
</html>


Your .aspx.cs should be as follows:
C#
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

namespace counrtybasedropdown

{
    public partial class cascading : System.Web.UI.Page
    {
        Database1Entities dbEntity = new Database1Entities();
        protected void Page_Load(object sender, EventArgs e)
        {
           if (!IsPostBack)
            {
                var country = from c in dbEntity.countries select new { c.countryID, c.countryName };
                ddlCountry.DataSource = country.ToList();
                ddlCountry.DataValueField = "countryID";
                ddlCountry.DataTextField = "countryName";
                ddlCountry.DataBind();
                ddlCountry.Items.Insert(0, "--Select--");
            }
        }
 
        protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            int countyID = Convert.ToInt16(ddlCountry.SelectedValue.ToString());
            var state = from s in dbEntity.states where s.countryID.Equals(countyID) select new { s.stateID, s.stateName };
            ddlState.DataSource = state.ToList();
            ddlState.Enabled = true;
            ddlState.DataValueField = "stateID";
            ddlState.DataTextField = "stateName";
            ddlState.DataBind();
            ddlState.Items.Insert(0, "--Select--");
        }
        protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
        {
            int stateID = Convert.ToInt16(ddlState.SelectedValue.ToString());
            var city = from c in dbEntity.cities where c.stateID.Equals(stateID) select new { c.cityID, c.cityName };
            ddlCity.DataSource = city.ToList();
            ddlCity.Enabled = true;
            ddlCity.DataValueField = "cityID";
            ddlCity.DataTextField = "cityName";
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, "--Select--");
        }
    }
}
 
Share this answer
 
v2
Comments
Agasimani 11-Jul-14 2:40am    
Can i above code used for filling textbox means if select any item from ddl then it display the price of the selected item in textbox.
ddl[--Select item--]
txtbox[--price of selected item--] like Bill generator.
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900