Tuesday 30 April 2013

country values based state values(casecading dropdown function)




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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["masterConnectionString"].ToString());
            con.Open();
            SqlCommand com = new SqlCommand("select cname,cid from countryname", con);
            SqlDataReader dr = com.ExecuteReader();

            //TextBox1.Text = "";

            DropDownList1.Items.Clear();
            while (dr.Read())
            {
                //TextBox1.Text = dr.GetString(0);
                DropDownList1.Items.Add(new ListItem(dr[0].ToString()));
            }
        }
    }

    private void SearchText(string v)
    {
        //string v = DropDownList1.SelectedValue;

        SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["masterConnectionString"].ToString());
        con1.Open();

        SqlCommand com1 = new SqlCommand("select sname from statename1 where cname='" + v + "'", con1);
        SqlDataReader dr1 = com1.ExecuteReader();
        DropDownList2.Items.Clear();
        while (dr1.Read())
        {
            DropDownList2.Items.Add(new ListItem(dr1[0].ToString()));
        }
        con1.Close();
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string v = DropDownList1.SelectedValue.ToString().Trim();
        SearchText(v);
    }
}

Output:


No comments:

Post a Comment