动态级联下拉列表

时间:2012-10-30 19:58:00

标签: c# asp.net drop-down-menu

我有两个下拉菜单

  1. 类别
  2. 子类
  3. 如果选择了一个类别,那么第二个下拉列表应该会自动更新,所以我在下面编写了这个代码用于第一个下拉列表:

    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);
    }
    

    但写第二个下拉代码得到一些错误并且还混淆了如何获得第一个下拉选择值,因为在bindcategory()块中声明了第一个下拉列表,这就是为什么它无法在其他块中访问那我该怎么做呢?

    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?
    }
    

    还有其他办法吗?

1 个答案:

答案 0 :(得分:1)

你缺少一些东西。请参阅下面的示例代码

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 
}