简体   繁体   中英

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.

Notice:
I'm not creating ComboBox in GUI, I'm using code. It's looking like this: 在此处输入图像描述

Question:
I need to get value when the user chose something in my 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);

When I run my app: 在此处输入图像描述

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM