C#WinForms - 根据数据绑定datagridview中另一个组合框的值过滤一个组合框

Cla*_*Boy 2 c# combobox datagridview filter winforms

我有4张桌子 - 代理商,客户,县和城镇.代理商和客户都有Town字段和County字段.我为每个表都有一个DataGridView.这些都很有效.我将Town和County作为组合框使用Towns and Counties表作为数据源.

问题是它不会根据选定的县过滤城镇.我希望它能做到这一点,但没有选项根据另一个字段的值过滤组合框字段.

我已经搜索了一段时间,但无法找到任何有用的东西.

有谁能跟我说说怎么做,拜托?

提前致谢.

问候,

理查德

PS我使用的是Visual Studio 2010,主要是设计视图.

sta*_*ica 5

您可以将其DataView用作组合框的数据源,因为这允许您根据标准(通过RowFilter属性)过滤行.我将展示一个简单的例子,其中涉及两个用于选择该国家和乡镇的组合框.


首先,设置一些要使用的数据:

// set up DataTable with countries:
countriesTable = new DataTable("Countries");
countriesTable.Columns.Add("CountryID", typeof(int));
countriesTable.Columns.Add("CountryName", typeof(string));
countriesTable.Rows.Add(1, "England");
countriesTable.Rows.Add(2, "Spain");
...

// set up DataTable with towns:
townsTable = new DataTable("Towns");
townsTable.Columns.Add("TownID", typeof(int));
townsTable.Columns.Add("TownName", typeof(string));
townsTable.Columns.Add("CountryID", typeof(int));   // <-- this is a foreign key
townsTable.Rows.Add(1, "London", 1);
townsTable.Rows.Add(2, "Brighton", 1);
townsTable.Rows.Add(3, "Barcelona", 2);
...
Run Code Online (Sandbox Code Playgroud)

接下来,将组合框数据绑定到数据:

// bind countries to country combobox:
countryComboBox.DataSource = null;
countryComboBox.DisplayMember = "CountryName";
countryComboBox.ValueMember = "CountryID";
countryComboBox.DataSource = countriesTable;

// bind towns to town combobox:    
townsView = new DataView(townsTable, "CountryID = 1", ...);  // use foreign key
townComboBox.DataSource = null;                              // in a row filter
townComboBox.DisplayMember = "TownName";
townComboBox.ValueMember = "TownID";
townComboBox.DataSource = townsView;
Run Code Online (Sandbox Code Playgroud)

最后,每当在国家组合框中选择另一个国家/地区时,请更新行过滤器:

private void countryComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    ...
    townsView.RowFilter = string.Format("CountryID = {0}",
                                            countryComboBox.SelectedValue);
}
Run Code Online (Sandbox Code Playgroud)

我相信你可以使用数据绑定和自定义Format事件处理程序自动完成最后一步,但我不会详细介绍.