C# 动态级联下拉

C# 动态级联下拉,c#,asp.net,drop-down-menu,C#,Asp.net,Drop Down Menu,我有两个下拉列表 类别 子类别 如果选择了一个类别,则第二个下拉列表将自动更新,因此我为第一个下拉列表编写了以下代码: public void bindcategory() { DataTable dt = new BALCate().GetCate(); DropDownList dropdownlist = new DropDownList(); foreach (DataRow dr in dt.Rows) {

我有两个下拉列表

  • 类别
  • 子类别
  • 如果选择了一个类别,则第二个下拉列表将自动更新,因此我为第一个下拉列表编写了以下代码:

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

    还有其他方法吗?

    您遗漏了一些东西。请参见下面的示例代码

    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 
    }