Search code examples
c#winformsdatagridviewcomboboxdatagridviewcombobox

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: enter image description here

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: enter image description here


Solution

  • I assume you mean this logic. I hope it won't be difficult for you to adapt it for your template. enter image description here enter image description here

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