Cascading dropdownlist

Ankitsrist
Posted by Ankitsrist under ASP.NET category on | Points: 40 | Views : 1692
in this code i will show u how to cascade two dropdownlist, for gxample if u have two dropdownlist state and city, when u select state its corresponding cities should be display in another dropdown...
firstly create the table "country" add some sample data

CREATE TABLE [dbo].[country]

(

[id] [int] IDENTITY(1,1) NOT NULL,

[state] [varchar](50) NULL,

[city] [varchar](50) NULL,

}




and then in design page add two dropdowns with button

<strong>state<asp:DropDownList ID="ddlstate" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlstate_SelectedIndexChanged">

</asp:DropDownList></strong>



<strong>city<asp:DropDownList ID="ddllcity" runat="server"

AutoPostBack="True">

</asp:DropDownList></strong>

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="submit" />


then write the following coding in code separation page

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
fillddlstate();

}

}
public void fillddlstate()
{
db.myconnection();
SqlCommand cmd = new SqlCommand("select ID, state from country", db.sqlcon );
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds );
ddlstate.DataSource = ds;
ddlstate.DataTextField = "state";
ddlstate.DataValueField = "ID";
ddlstate.DataBind();
ddlstate.Items.Insert(0, new ListItem ("--select--","0"));


}

protected void ddlstate_SelectedIndexChanged(object sender, EventArgs e)
{
db.myconnection();
SqlCommand cmd = new SqlCommand("select * from country where state='"+ddlstate.SelectedValue+"'",db.sqlcon );
SqlDataAdapter adp = new SqlDataAdapter(cmd );
DataSet ds = new DataSet();
adp.Fill(ds);
ddlcity.DataSource = ds;
ddlcity.DataTextField = "city";
ddlcity.DataValueField = "ID";
ddlcity.DataBind();

}

and u have done
njoy

Comments or Responses

Login to post response