I have a databound DataGridView with a DataGridViewComboBoxColumn. If the combobox value is null I want to display a text. I do not want to add a null item to the databound list as I need to display different text in each datagridview line. How would I achieve this using the default datagridview control?
Asked
Active
Viewed 2,433 times
1 Answers
2
You can use the CellFormatting event to alter any displayed value:
//attach in code or via designer:
dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);
//example implementation:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == Column1.Index && e.Value==null)//where Column1 is your combobox column
{
e.Value = "Empty";
e.FormattingApplied = true;
}
}

Me.Name
- 12,259
- 3
- 31
- 48
-
If I change the value to something that is not in the databound list then I get an error. – Daniel Jul 02 '12 at 14:24
-
Any other ideas? The problem is that the DataGridViewComboBoxCell has no text property. The value is databound, so there's no way to assign a text to it. – Daniel Jul 02 '12 at 14:42
-
Could you try if it works if e.FormattingApplied = true; is set? (also edited the original post to add it) – Me.Name Jul 02 '12 at 14:53
-
Aaaaaaaahhhh, my bad. I was trying to assign a value directly to the cell and not via the EventArgs. Doing exactly what you wrote works like a charm! Thanks a lot. – Daniel Jul 02 '12 at 15:15