Tuesday, 24 March 2015

Drop down Selection

Drop down Selection based one on other:

.cs file


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class home : System.Web.UI.Page
{
   public  String sqlc = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnection"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SqlConnection con = new SqlConnection(sqlc);
            SqlDataAdapter sd = new SqlDataAdapter("select * from Country1", con);
            DataTable dt=new DataTable();
            sd.Fill(dt);
            CountryDdl.DataSource = dt;
            CountryDdl.DataTextField = "Countryname";
            CountryDdl.DataValueField = "Countryid";
            CountryDdl.DataBind();
            CountryDdl.Items.Insert(0, new ListItem("select", "0"));
            StateDdl.Items.Insert(0, new ListItem("select", "0"));
            CityDdl.Items.Insert(0, new ListItem("select", "0"));
        }

        }
 
    protected void CountryDdl_SelectedIndexChanged(object sender, EventArgs e)
    {
        int Countryid = Convert.ToInt32(CountryDdl.SelectedValue);
        SqlConnection con = new SqlConnection(sqlc);
        SqlDataAdapter sd = new SqlDataAdapter("select * from State1 Where Countryid=" + Countryid, con);
        DataTable dt = new DataTable();
        sd.Fill(dt);
        StateDdl.DataSource = dt;
        StateDdl.DataTextField = "Statename";
        StateDdl.DataValueField = "Stateid";
        StateDdl.DataBind();
        StateDdl.Items.Insert(0, new ListItem("select", "0"));
        if (StateDdl.SelectedValue == "0")
        {
            CityDdl.Items.Clear();
            CityDdl.Items.Insert(0, new ListItem("Select", "0"));
        }
    }
    protected void StateDdl_SelectedIndexChanged(object sender, EventArgs e)
    {
        int Stateid = Convert.ToInt32(StateDdl.SelectedValue);
        SqlConnection con = new SqlConnection(sqlc);
        SqlDataAdapter sd = new SqlDataAdapter("select * from City1 Where Stateid=" + Stateid, con);
        DataTable dt = new DataTable();
        sd.Fill(dt);
        CityDdl.DataSource = dt;
        CityDdl.DataTextField = "Cityname";
        CityDdl.DataValueField = "Cityid";
        CityDdl.DataBind();
        CityDdl.Items.Insert(0, new ListItem("select", "0"));
    }
}

aspx file

<div>
     
        <asp:DropDownList ID="CountryDdl" runat="server" OnSelectedIndexChanged="CountryDdl_SelectedIndexChanged" AutoPostBack="true">
        </asp:DropDownList>
        <asp:DropDownList ID="StateDdl" runat="server" OnSelectedIndexChanged="StateDdl_SelectedIndexChanged" AutoPostBack="true">
        </asp:DropDownList>
        <asp:DropDownList ID="CityDdl" runat="server" AutoPostBack="true">
        </asp:DropDownList>
    </div>

output:


No comments:

Post a Comment