Simple ? DataGridView combobox formatting

Simple ? DataGridView combobox formatting

Post by ldw » Tue, 21 Feb 2006 03:20:24

I need help with something that is probably simple.

The database table that my DataGridView is bound to has a column of
type Int16 that can contain 0 or 1. The DataGridView column type is a
combobox. But I don't want 0 and 1 in the combobox, I want "NO" and
"YES" (combobox list of values is not itself bound to a datasource).

So I handled the CellFormatting and CellParsing events for the
DataGridView, and if it is a cell in that column, for the
CellFormatting event I have
if ((short)e.Value == 0)
e.Value = "NO";
e.Value = "YES";
e.FormattingApplied = true;
and for the CellParsing event I have
if ((string)e.Value == "NO")
e.Value = (short)0;
e.Value = (short)1;
e.ParsingApplied = true;
The problem is that before the CellFormatting event ever happens, I get
the DataError event telling me that the "DataGridViewComboBoxCell value
is not valid". If, in the DataError handler, I add the value in
datagridview[e.RowIndex, e.ColumnIndex].Value to the combobox's list,
then the table displays, updates, etc. just fine, displaying "NO" and
"YES" for the column's cells, but with the unacceptable drawback that
my combobox for that column now contains "NO", "YES", 0, and 1 instead
of just "NO" and "YES". The context for the DataError events is
Formatting | Display, even though CellFormatting event has NOT happened
yet. If I just ignore the DataError event then the cells wrongly all
display "NO", never "YES".

What do I do to make it work? Thanks for your help.

Simple ? DataGridView combobox formatting

Post by ldw » Tue, 21 Feb 2006 04:03:48

>From looking at some other posts here, it seems to me that perhaps what
I need to do is forget about CellFormatting and CellParsing, stop
loading the combobox through its Items property, but to create an array
of class objects that I bind to the combobox, where the class has a
property for the numeric value in the database and another property for
the corresponding string value for the datagrid, assigning the names of
those properties to the combobox's ValueMember and DataMember

Is that correct?