I'm using a datagridview in C#, bound to a bindingsource which selects data from SQL Server. So far, so standard. I set a lot of this up using the wizards, so a lot of the binding was done for me, which means that it knows, for example, when one of my columns does not allow nulls.
So, what happens at runtime, is I start entering a new record in the gridview, enter a bit of data so that I've got a partial record, then tab to the end of the row and tab off, which causes the grid to try to commit the record. It fails (because one of the fields contains null), and I trap the error in the DataError event of the gridview, like so:
private void dgvGasSafeDetails_DataError(object sender, DataGridViewDataErrorEventArgs e)
string colName = dgvGasSafeDetails.Columns[e.ColumnIndex].HeaderText;
MessageBox.Show(e.Exception.Message, colName + " Error");
e.Cancel = true;
My Problem is that 'e.Exception.Message' contains something like:
Column 'Asset ID' does not allow nulls.
but e.ColumnIndex does not refer to the 'Asset ID' column. It refers to the column I'm in when the error occurs (which is the last column, since I'm tabbing off the end of the record). So 'colName' in the above event handler is NOT the name of the column where the error is.
What I want to know is which column has raised the error. i.e. I want something that tells me 'Asset ID'. I could parse the text of the error, but this is too flaky - the error may not always be in this format.
How do I get the column where the error occurred?