Search code examples
c#winformsdatagridcomboboxcolumn

Extracting specific string from combobox select


I have a combobox for an item list that I populate using the following code:

List<string> comboboxItems = new List<string>();

foreach (var p in products)
{
   var x = p.Product;

   foreach (var pn in x)
   {
      comboboxItems.Add(pn.name + " :Qty " + pn.quantity_available
                         + " :Tax " + pn.default_tax_tier);                       
   }
}

cmbItems.DataSource = comboboxItems;

What should I do in order to get the value, pn.name only when the combobox item is selected?

Using WinForms.


Solution

  • You have to handle the event DataGridView.EditingControlShowing event, in there you can access the actual combobox and register the SelectedIndexChanged event handler like this:

    //EditingControlShowing event handler for your dataGridView1
    private void dataGridView1_EditingControlShowing(object sender,
                                       DataGridViewEditingControlShowingEventArgs e){
       if(dataGridView1.CurrentCell.OwningColumn == cmbItems){
         var combo = e.Control as ComboBox;
         combo.SelectedIndexChanged -= cmbItems_SelectedIndexChanged;
         combo.SelectedIndexChanged += cmbItems_SelectedIndexChanged;
       }   
    }
    private void cmbItems_SelectedIndexChanged(object sender, EventArgs e){
       var combo = sender as ComboBox;
       //Note that SelectedItem may be null
       var s = Convert.ToString(combo.SelectedItem);
       int i = s.IndexOf(" :Qty");
       var selectedName = i == -1 ? "" : s.Substring(0,i+1).TrimEnd();
       //other code ...
    }