Home > ASP.Net > Bind Dependent DropdownList

Bind Dependent DropdownList


Hi

try this example:

protected void PopulateDropDownList1()

{
    string queryString = "SELECT * FROM Table1";
    SqlClient.SqlConnection connection = new SqlClient.SqlConnection("Data Source=HCISSQL2;Initial Catalog=...;User ID=apps;Password=...");
    SqlClient.SqlCommand command = new SqlClient.SqlCommand(queryString, connection);
       
    connection.Open();
  
    DataTable dt = new DataTable();
    SqlDataAdapter ad = new SqlDataAdapter(command);
    ad.Fill(dt);
    if (dt.Rows.Count > 0) {

    DropDownList1.DataSource = dt;
    DropDownList1.DataTextField = "CountryName";
    DropDownList1.DataValueField = "CountryID";
    DropDownList1.DataBind();
    }
   
    connection.Close();
  
}
protected void PopulateDropDownList2(int country)
{
   
    string queryString = "SELECT States FROM FROM Table2 WHERE CountryID = @countryId";
    SqlClient.SqlConnection connection = new SqlClient.SqlConnection("YOUR CONNECTION STRING HERE");
    SqlClient.SqlCommand command = new SqlClient.SqlCommand(queryString, connection);
    command.Parameters.AddWithValue("@countryId", country);
    connection.Open();
  
    DataTable dt = new DataTable();
    SqlDataAdapter ad = new SqlDataAdapter(command);
    ad.Fill(dt);

    DropDownList1.Items.Clear();
    if (dt.Rows.Count > 0) {

    DropDownList2.DataSource = dt;
    DropDownList2.DataTextField = "StatesName";
    DropDownList2.DataValueField = "StatesID";
    DropDownList2.DataBind();
    }
    connection.Close();
   
}

protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
   
 PopulateDropDownList2(int.Parse(DropDownList1.SelectedValue));
   
}
protected void Page_Load(object sender, System.EventArgs e)
{
   
    if (!Page.IsPostBack) {
       
        PopulateDropDownList1();
       
    }
}

NOTE: 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 DropDownList1 to fire up the SelectedIndexChanged event

Good Luck

Advertisements
Categories: ASP.Net
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: