可以使用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 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;
最後,無論何時在國家組合框中選擇另一個國家/地區,請更新行過濾器ER:
private void countryComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
...
townsView.RowFilter = string.Format("CountryID = {0}",
countryComboBox.SelectedValue);
}
我相信你可以使用數據綁定和一個自定義Format
事件處理程序自動完成這最後一步,但我不會詳談。
您是否在使用像SqlDataSource或ObjectDataSource這樣的DataSource對象來獲取縣?如果你這樣做,那麼你應該通過一個選擇參數來過濾縣,具體取決於Town DropDown中選擇的值。 – 2010-10-30 11:00:43
我正在使用一個DataSet和一個mdf文件。我將表拖到DataSet上,然後我使用那裏顯示的表來可視化DataGridViews中的數據。對不起,如果我的措辭不正確 - 我只在2天前開始使用C#。 – ClarkeyBoy 2010-10-30 11:02:29
@ClarkeyBoy,提供相關代碼。 – mahesh 2010-10-30 11:16:09