0

我有两个下拉菜单

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

有没有其他方法可以做到这一点?

4

1 回答 1

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 
}
于 2012-10-30T20:09:49.550 回答