代码之家  ›  专栏  ›  技术社区  ›  Oktam Yaqubov

创建两个ComboBox | C之间的关系#

  •  0
  • Oktam Yaqubov  · 技术社区  · 7 年前

    现在我需要:如果用户从第一个组合框中选择类别,那么在第二个组合框中必须出现与该类别相关的子类别。 例如:

    | Category
    | cat_id   | cat_name |
    | 1        | Car      |
    | 2        | Car1     |
    | 3        | Car2     |
    | 4        | Car3     |
    

    | SubCategory
    | scat_id   | scat_name  | cat_id |
    | 1         | sCar       | 1      |
    | 2         | sCar1      | 1      |
    | 3         | sCar2      | 3      |
    | 4         | sCar3      | 1      |
    

    这是表中两个相关的结构。 我有个密码:

    private void SInfo_Load(object sender, EventArgs e)
    {
        using (var context = new StBaseSQLEntities())
        {
            metroComboBox1.DataSource = context.Category.ToList();
            metroComboBox1.DisplayMember = "cat_name";
            metroComboBox1.ValueMember = "cat_id";
    
            //SubCategory
            metroComboBox2.DataSource = context.SubCategory.ToList();
            metroComboBox2.DisplayMember = "scat_name";
            metroComboBox2.ValueMember = "scat_id";
        }
    }
    

    我是新来的C#Windows窗体,所以我不知道如何执行此操作。如果我从类别组合框中选择1,那么第二个组合框需要显示属于子类别组合框中第一个id的子类别。 我怎样才能在C#win表格中得到结果?

    1 回复  |  直到 7 年前
        1
  •  1
  •   radbyx Matt    7 年前

    只要使用 SelectedValue 属性作为子类别的筛选器:

    private void MetroComboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        ComboBox cmb = (ComboBox) sender;
        MetroComboBox2.DataSource = 
                          context.Subcategory.Where(x => x.cat_id == cmb.SelectedValue).ToList();
        MetroComboBox2.enabled = true;
    }
    
        2
  •  0
  •   Fabio    7 年前

    用户选择类别

    使用 ComboBox.SelectionChangeCommitted Event
    来自文档:

    当用户更改所选项目且更改为

    将所有子目录保存为私有成员,这样就可以在不读取数据库的情况下过滤它。

    private List<SubCategory> _allSubCategories;
    
    private void SInfo_Load(object sender, EventArgs e)
    {
        using (var context = new StBaseSQLEntities())
        {
            metroComboBox1.DataSource = context.Category.ToList();
            metroComboBox1.DisplayMember = "cat_name";
            metroComboBox1.ValueMember = "cat_id";
    
            //SubCategory
            _allSubCategories = context.SubCategory.ToList();
            metroComboBox2.DataSource = _allSubCategories;
            metroComboBox2.DisplayMember = "scat_name";
            metroComboBox2.ValueMember = "scat_id";
        }
    }
    

    然后进来 SelectionChangeCommitted

    private void metroComboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        var combobox = (ComboBox)sender;
        var selectedCategory = (short)combobox.SelectedValue;
        metroComboBox.DataSource = 
            _allSubCategories.Where(sub => sub.cat_id == selectedCategory).ToList();
        // display/enable item
    }
    
    推荐文章