gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:22:07 27 4
gpt4 key购买 nike

我有 4 个表 - 代理商、客户、县和城镇。代理和客户都有一个城镇字段和一个县字段。我为每个表都有一个 DataGridView。这些效果很好。我将城镇和县作为组合框,使用城镇和县表作为数据源。

问题是它没有根据所选县过滤城镇。我希望它这样做,但没有选项可以根据另一个字段的值过滤组合框字段。

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

有人可以告诉我如何做到这一点吗?

提前致谢。

问候,

理查德

PS 我正在使用 Visual Studio 2010,主要使用设计 View 。

最佳答案

您可以使用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);
...

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

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

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

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

我相信您可以使用数据绑定(bind)和自定义 Format 事件处理程序自动执行最后一步,但我不会详细介绍。

关于C# WinForms - 根据数据绑定(bind) datagridview 中另一个组合框的值过滤一个组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4058350/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com