Željko Perić

Željko Perić

  • 902
  • 1.4k
  • 49.5k

How to change list of items inside DataGridViewComboBoxCell

Jun 21 2019 8:31 AM
I am writing simple application that uses DataGridView control with ComboBoxColumn.
I have used this method to change list of items inside one cell of ComboBoxColumn :
  1. void Fill_Location()  
  2. {  
  3.     DataGridViewComboBoxCell Location =
  4.          (DataGridViewComboBoxCell) DGV.Rows[0].Cells[1];  
  6.     Location.Items.Clear();  
  8.     string a ="hello";  
  10.     Location.Items.Add(a);  

When executed this method raises DataGridView Default Error Dialog with message:

The following exception occurred in the DataGridView
System.ArgumentException : DataGridViewComboBoxCell value is not valid.
To replace this default dialog please handle the DataError event.

So I have assigned to DGV this DataError event handler :
  1. void DGV_DataError(object sender, DataGridViewDataErrorEventArgs e)  
  2. {   
  3.         MessageBox.Show(e.Context.ToString());  

After that when executed method raises DataGridView DataError event handler with following message : Formatting, PreferredSize.

Since that I do not know how to resolve above error,
I have changed code for DataError event handler to :
  1. void DGV_DataError(object sender, DataGridViewDataErrorEventArgs e)  
  2. {  
  4.     if(e.Context== DataGridViewDataErrorContexts.Formatting)  
  5.         e.ThrowException = false;  

Now when executing method Fill_Location() list of items inside ComboBoxCell is changed as expected, and there is no any error message.

Is this correct use of DataError event handler for resolving this kind of problem,
or there can be some other hidden problems that currently are not evident ?

Program is written for .Net 4.0

All the best,
Željko Peric

Brought to you by:

Answers (2)