Search code examples
c#datagridviewdatagridviewcolumn

Updating the existing DataGridViewComboBoxColumn Items collection


We have DataGridViewComboBoxColumn in which we have four values which are fixed. During run-time when the event dataGridView1_EditingControlShowing occurs we are trying to append new items to DataGridViewComboBoxColumn.

private void dataGridView1_EditingControlShowing(object sender, 
                                             DataGridViewEditingControlShowingEventArgs e)
{
   ComboBox combo = e.Control as ComboBox;
   if (combo != null)
   {
      combo.DropDown += new System.EventHandler(ComboBox1_DropDown);
   }
}

private void ComboBox1_DropDown(object sender, System.EventArgs e)
{
   ComboBox comboBox = (ComboBox)sender;
   if (comboBox.Items != null)
   {
      List<String> elementname = Elements();
      foreach (string s in elementname)
      {
         if (!comboBox.Items.Contains(s))
         {
            comboBox.Items.Add(s);
         }
      }
   }
}

I am getting this exception :

enter image description here

Can you please suggest how to add the values to the existing DataGridViewComboBoxColumn in Items collection.


Solution

  • You are adding into the Items of editing control but not into the Items of the ComboBoxColumn, which will eventually be used for validation.

    To get easy access to the hosting DGV we use the special type DataGridViewComboBoxEditingControl. Now we will add the new choices to both Items collections now in the ComboBox1_DropDown event: :

    DataGridViewComboBoxEditingControl comboBox = (DataGridViewComboBoxEditingControl)sender;
    DataGridView dgv = comboBox.EditingControlDataGridView; 
    if (comboBox.Items != null && dgv != null)
    {
        DataGridViewComboBoxColumn dcbc =
            (DataGridViewComboBoxColumn) dgv.Columns[dgv .CurrentCell.ColumnIndex];
    
        List<String> elementname = Elements.ToList();
        foreach (string s in elementname)
        {
            if (!comboBox.Items.Contains(s))
            {
              comboBox.Items.Add(s);
              dcbc.Items.Add(s);
            }
        }
    }
    

    Note:

    The new Items will not be persistet unless you code for it.

    So if you have set fields to new values and saved them, you must also save and reload those new values before re-loading the DGV or else the values will not be in the Column's list of values and throw the DataError again!

    The usual place to store them would be a DataTable in your DBMS, but any other external storage may also be used like an XML file or maybe dynamic resources etc.. But the DBMS is the most natural choice imo.