【问题标题】:dynamic cascade dropdown动态级联下拉菜单
【发布时间】:2012-10-30 19:57:59
【问题描述】:

我有两个下拉菜单

  1. 分类
  2. 子类别

如果选择了一个类别,那么第二个下拉菜单应该会自动更新,所以我在下面为第一个下拉菜单编写了以下代码:

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

还有其他方法吗?

【问题讨论】:

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


    【解决方案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 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-24
      • 2018-01-19
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 2013-09-14
      • 2015-11-30
      相关资源
      最近更新 更多