我有兩個串列和兩個組合框。所以,我想建立他們之間的關系。也就是說,當你從box1中選擇一些東西時,你只能選擇box2中的一些選項,這與box1有關。
注意:
我不是在 GUI 中創建 ComboBox,而是使用代碼。它看起來像這樣:

問題:
當用戶在我的 ComboBox 中選擇某些內容時,我需要獲得價值。我怎樣才能得到用戶的選擇?
代碼:
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.Name = "Accounts";
List<string> data = new List<string>();
foreach (var item in contactNames)
{
data.Add(item);
}
cmb.DataSource = data;
dataGridView1.Columns.Add(cmb);
//dataGridView1.Rows.Add(data);
DataGridViewComboBoxColumn cmb2 = new DataGridViewComboBoxColumn();
List<String> contacts2 = new List<String>();
cmb2.Name = "Contacts";
cmb2.DataSource = data;
dataGridView1.Columns.Add(cmb2);
當我運行我的應用程式時:

uj5u.com熱心網友回復:
我假設你的意思是這個邏輯。我希望你不難適應你的模板。

/** required */
using System.Linq;
public Form1()
{
InitializeComponent();
var source = new Dictionary<string, string>()
{
{ "Red", "Colors" },
{ "Yellow", "Colors" },
{ "hasOne", "Relationships" },
{ "belongsTo", "Relationships" },
{ "hasMany", "Relationships" }
};
#region DataGridViewComboBoxCell
var dgcb1 = (DataGridViewComboBoxCell)dataGridView.Rows[0].Cells[0];
var dgcb2 = (DataGridViewComboBoxCell)dataGridView.Rows[0].Cells[1];
dgcb1.Items.Clear();
dgcb1.Items.AddRange(source
.Select(x => x.Value)
.Distinct()
.ToArray());
dataGridView.CellValueChanged = (s, e) =>
{
dgcb2.Items.Clear();
dgcb2.Items.AddRange(source
.Where(x => x.Value == dgcb1.Value.ToString())
.Select(x => x.Key)
.ToArray());
};
#endregion
#region Combobox
cb1.Items.Clear();
cb1.Items.AddRange(source
.Select(x => x.Value)
.Distinct()
.ToArray());
cb1.SelectedIndexChanged = (s, e) =>
{
cb2.Items.Clear();
cb2.Items.AddRange(source
.Where(x => x.Value == cb1.SelectedItem.ToString())
.Select(x => x.Key)
.ToArray());
};
#endregion
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/510007.html
上一篇:TreeView檔案夾結構例外
下一篇:旋轉影像的矩形邊界
