Hello i have simple problem
If no values in datagrid need to repair my code
Error is:
System.NullReferenceException: 'Object reference not set to an instance of an object.' System.Windows.Forms.DataGridViewCell.Value.get returned null.
My code
C#
private void ListDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
foreach (DataGridViewRow row in ListDataGridView.Rows)
{
if (String.IsNullOrWhiteSpace(row.Cells["R.b."].Value.ToString()))
{
row.DefaultCellStyle.ForeColor = System.Drawing.ColorTranslator.FromHtml("#51B3E8");
}
else
{
row.DefaultCellStyle.ForeColor = System.Drawing.ColorTranslator.FromHtml("#09ECA6");
}
}
}
Jignesh KumarRank #91 · 22.9K reputationPosted Mar 29, 2023, 6:46 AM EDT
please try to check null object before ToString(),
private void ListDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { foreach (DataGridViewRow row in ListDataGridView.Rows) { if (String.IsNullOrWhiteSpace(row.Cells["R.b."].Value?.ToString())) { row.DefaultCellStyle.ForeColor = System.Drawing.ColorTranslator.FromHtml("#51B3E8"); } else { row.DefaultCellStyle.ForeColor = System.Drawing.ColorTranslator.FromHtml("#09ECA6"); } } }Naimish MakwanaRank #324 · 7.7K reputationPosted Mar 29, 2023, 6:53 AM EDT
To avoid this error, you can add a null check before accessing the
Valueproperty of the cell, like this:if (row.Cells["R.b."].Value != null && String.IsNullOrWhiteSpace(row.Cells["R.b."].Value.ToString())) { row.DefaultCellStyle.ForeColor = System.Drawing.ColorTranslator.FromHtml("#51B3E8"); } else { row.DefaultCellStyle.ForeColor = System.Drawing.ColorTranslator.FromHtml("#09ECA6"); }Thanks