[英]How to get value in ComboBox Windows Forms? C#
I have two lists and two ComboBoxes.我有两个列表和两个组合框。 So, I would like to make a relation between them.所以,我想建立他们之间的关系。 That means, when you choose from box1 something, then you can choose only some options in box2, which is related to box1.也就是说,当你从box1中选择一些东西时,你只能选择box2中的一些选项,这与box1有关。
Notice:注意:
I'm not creating ComboBox in GUI, I'm using code.我不是在 GUI 中创建 ComboBox,而是使用代码。 It's looking like this:它看起来像这样:
Question:问题:
I need to get value when the user chose something in my ComboBox.当用户在我的 ComboBox 中选择某些东西时,我需要获得价值。 How can I get the user's choice?我怎样才能得到用户的选择?
Code:代码:
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);
I assume you mean this logic.我假设你的意思是这个逻辑。 I hope it won't be difficult for you to adapt it for your template.我希望你不难适应你的模板。
/** 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.