Search code examples
c#winformsdatagridviewdatagridviewcomboboxdatagridviewcomboboxcell

How to display text in DataGridViewComboBoxColumn when the databound value is null


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?


Solution

  • 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;
            }
        }