I am putting this up because it took far too long to find the answer on the web and this is probably a common problem - it is the second time i have experienced it on my app.
My solution: remove the column right after it is added (detailed reason at the end). The following code removes all potential image columns, you may want to customize this if your schema is not dynamic and you know what you want to leave out:
public Form1()
{
InitializeComponent();
dataGridView1.ColumnAdded += dataGrid_ColumnAdded;
}
void dataGrid_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
if (e.Column.CellType == typeof(DataGridViewImageCell))
dataGridView1.Columns.Remove(e.Column);
}
so when it comes to the actual binding
DataTable table = dataTableCombo.SelectedItem as DataTable;
dataGridView1.DataSource = table;
populating the cells will happen after adding (and the removing correction) of the columns. And the exception doesn't happen this way.
Also, in your dataGridView1_RowsAdded
event handler watch out: there's not only e.RowIndex
but there's e.RowCount
too, and it can be e.RowCount > 1
! So first I tried:
void dataGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
for (int i = e.RowIndex; i < e.RowIndex + e.RowCount; i++)
{
foreach (DataGridViewCell cell in dataGridView1.Rows[i].Cells)
{
if (cell.GetType() == typeof(DataGridViewImageCell))
{
cell.Value = DBNull.Value;
}
}
}
}
but I still got some exceptions. Plus if your binding is two-way, watch out because cell.Value = DBNull.Value;
causes a change in the business object! That's the reason I advise to just rather remove the column.