winforms 如何在ComboBox中获取值?C#

busg9geu  于 2022-11-17  发布在  C#
关注(0)|答案(1)|浏览(178)

我有两个列表和两个组合框。所以,我想在它们之间建立一个关系。这意味着,当你从box1中选择某个东西时,你只能选择box2中的一些选项,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);

当我运行应用时:

2g32fytz

2g32fytz1#

我想你指的是这个逻辑。我希望它不会很难为你适应你的模板。

/** 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
}

相关问题