How to Bind State Wise Citylist in DropDownList in ASP.NET

Here I am going to explain how to show state wise city list  in DropDownList in Asp.net like below Image.
 
untitled.JPG
I have two tables in database like :

untitled1.JPG
Now write the below code On the Page_Load in Asp.net

protected void Page_Load(object sender, EventArgs e)

{
    SqlConnection cn = new SqlConnection("Data Source=BCILGGN13\\SQLEXPRESS;Initial   catalog=Test; Uid=sa; Pwd=bcil;");

    DataTable dt;

    DataTable dt1;

    SqlDataAdapter adap;

    if (!IsPostBack)

    {

        ddlCity.AppendDataBoundItems = true;

        ddlCity.Items.Insert(0, "-select-");

        adap = new SqlDataAdapter("select * from State_List", cn);

        dt = new DataTable();

        adap.Fill(dt);

        int j = 0;

        if (dt.Rows.Count > 0)

        {

            j = 1;

            for (int i = 0; i < dt.Rows.Count; i++)

            {

                ddlCity.Items.Add(dt.Rows[i]["State"].ToString());

                ddlCity.Items[j].Attributes.Add("style", "color:red");

                adap = new SqlDataAdapter("select City from city_list where state= '" + dt.Rows[i]["State"] + "'", cn);

                dt1 = new DataTable();

                adap.Fill(dt1);

                for (int k = 0; k < dt1.Rows.Count; k++)

                {

                    ddlCity.Items.Add(dt1.Rows[k]["City"].ToString());

                }

              
j = dt1.Rows.Count +j+1;
            }

        }

    }

}

Ebook Download
View all
Learn
View all