在两个组合框之间创建关系

时间:2019-02-24 18:08:17

标签: c# winforms

我有两个相关的表(类别和子类别)。所以我在Windows窗体上有2个ComboBox控件。这两个ComboBox以父子(或category-sub_category)关系关联。例如,我有一个ComboBox,其中包含供用户选择的类别列表(父项),以及另一个ComboBox(子项),其中包含子类别列表。 现在,我需要:如果用户从第一个组合框中选择类别,则在第二个组合框中必须出现与该类别相关的子类别。 例如:

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

这是表中结构的两个相关部分。 我有这个C#代码:

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,则第二个组合框需要在子类别组合框中显示属于1st id的子类别。  如何在C#获胜表格中获得结果?

2 个答案:

答案 0 :(得分:1)

只需将第一个组合框上的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;
}

答案 1 :(得分:0)

  

...如果用户从第一个组合框中选择类别,则在第二个组合框中   组合框必须显示与该类别相关的子类别。

使用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
}
相关问题