Ashok Damani
Ashok Damani

Reputation: 127

dynamic cascade dropdown

I've got two dropdowns

  1. category
  2. subcategory

If a category is selected, then second dropdown should automatically update, so I've written this code below for 1st dropdown:

public void bindcategory()
{         
    DataTable dt = new BALCate().GetCate();        
    DropDownList dropdownlist = new DropDownList();
    foreach (DataRow dr in dt.Rows)
    {
        ListItem listitem = new ListItem();
        listitem.Text = dr["cate_name"].ToString();
        dropdownlist.Items.Add(listitem);            
    }
    cate_search.Controls.Add(dropdownlist);
}

but writing 2nd dropdown code getting some error and also confused that how could to get the 1st dropdown select value, because 1st dropdown declared inside of bindcategory() block, thats why it couldn't be accessed in other blocks. So what should I do for that?

public void bindsubcategory()
{
     //error (selected cate_id from 1st dropdown cant accessed due to scop problem)
     DataTable dt = new BALCate().GetSubCate(   //some cate_id   ); 

     // what should the code here?
}

Is there any other way to do this?

Upvotes: 0

Views: 990

Answers (1)

Tariqulazam
Tariqulazam

Reputation: 4585

You are missing few things. See the sample code below

public void bindcategory()
{         
    DataTable dt = new BALCate().GetCate();        
    DropDownList dropdownlist = new DropDownList();
    //SET AutoPostBack = true and attach an event handler for the SelectedIndexChanged event. This event will fire when you change any item in the category dropdown list.
    dropdownlist.AutoPostBack = true;
    dropdownlist.SelectedIndexChanged += new EventHandler(dropdownlist_SelectedIndexChanged);
    foreach (DataRow dr in dt.Rows)
    {
        ListItem listitem = new ListItem();
        listitem.Text = dr["cate_name"].ToString();
        listitem.Value= dr["cate_id"].ToString();
        dropdownlist.Items.Add(listitem);            
    }
    cate_search.Controls.Add(dropdownlist);
}

void dropdownlist_SelectedIndexChanged(object sender, EventArgs e){
    //Grab the selected category id here and pass it to the bindSubCategory function.
    bindSubCategory(Convert.ToInt32((sender as DropDownList).SelectedValue)); 
}

public void bindsubcategory(int categoryId)
{
     DataTable dt = new BALCate().GetSubCate(categoryId);
     //Bind this data to the subcategory dropdown list 
}

Upvotes: 1

Related Questions