Search code examples
c++datagridviewvisual-c++-2010datagridviewcombobox

Accessing a Combobox inside a dataGridView Column?


I'm working on a scheduling program, and inside the dataGridView, we have a few ComboBox Columns that are populated by 3 entries upon creation, but I wanted to be able to add more as the user creates them, but I have no idea how you would access the combobox data. Any help is appreciated!

// this is initialized in a separate part.
/* System::Windows::Forms::DataGridView^ dataGridView;*/

System::Windows::Forms::DataGridViewComboBoxColumn^ newCol = 
    (gcnew System::Windows::Forms::DataGridViewComboBoxColumn());

dataGridView->Columns->AddRange(gcnew cli::array< System::Windows::Forms::DataGridViewComboBoxColumn^  >(1) {newCol});  

// add the choices to the boxes.
newCol->Items->AddRange("User inputted stuff", "More stuff", "Add New..."); 

Solution

  • Solution

    If you have access to the data from the user entry and you know the column index for the DataGridViewComboBoxColumn, you should be able to just do the following wherever needed:

    DataGridViewComboBoxColumn^ comboboxColumn = dataGridView->Columns[the_combobox_column_index];
    
    if (comboboxColumn != nullptr)
    {
        comboboxColumn->Items->Add("the new user entry");
    }
    

    Comments Response

    how could you change the selected index of that combobox (the one that the edit was triggered on)? [...] we want it so that when the new item is added the selected index is set to that new item).

    Couple of ways come to mind.

    1. Add a single line within the if-statement of the above code. This will set the default displayed value for each DataGridViewComboBoxCell in the DataGridViewComboBoxColumn.

      if (comboboxColumn != nullptr)
      {
          comboboxColumn->Items->Add("the new user entry");
          comboboxColumn->DefaultCellStyle->NullValue = "the new user entry";
      }
      
      • Pros: Clean, efficient. Previous user-selected values are left intact. The cell's FormattedValue will display the new user value by default if no other selection has been made.
      • Cons: Doesn't actually set a cell's selected value, so Value will return null on cells not explicitly user-selected.
    2. Actually set the value of certain cells (based on your criteria) to the user-added value.

      if (comboboxColumn != nullptr)
      {
          comboboxColumn->Items->Add("the new user entry");
      
          for (int i = 0; i < dataGridView->Rows->Count; i++)
          {
              DataGridViewComboBoxCell^ cell = dataGridView->Rows[i]->Cells[the_combobox_column_index];
      
              if ( cell != nullptr /* and your conditions are met */ )
              {
                  cell->Value = "the new user entry";
              }
          }
      }
      
      • Pros: The Value of targeted cells is actually set to the new user value.
      • Cons: Logic deciding which cells should be affected is more complicated.