ca9163d9
ca9163d9

Reputation: 29199

Setting the CellStyle in the CellFormatting event raises an exception on mouse over

I have a form with the following event. However, when the mouse pointer hovers over the cells whose CellStyle has been set, the application raises an exception.

DataGridViewCellStyle AStyle = new DataGridViewCellStyle { BackColor = Color.Green };

private void DGV_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (string.IsNullOrEmpty(e.Value.ToString()))
    {
        e.CellStyle = AStyle;
    }

Exception:

base.OnMouseMove(e);

$exception {"Value cannot be null.\r\nParameter name: font"} System.ArgumentNullException

Upvotes: 1

Views: 222

Answers (1)

41686d6564
41686d6564

Reputation: 19651

The exception is basically telling you that the Font property of the DataGridViewCellStyle cannot be null when it's used to set the CellStyle. Change how you initialize your AStyle variable to something like this:

DataGridViewCellStyle AStyle;

public Form1()
{
    InitializeComponent();
    AStyle = new DataGridViewCellStyle { BackColor = Color.Green, Font = DGV.Font };
}

Alternatively, you can get rid of AStyle completely (if you're only using it to set the back color) and use something like this instead:

e.CellStyle.BackColor = Color.Green;

One more thing to note is that e.Value.ToString() may throw a NullReferenceException if e.Value is null. You may consider adding a null-conditioner to avoid this:

if (string.IsNullOrEmpty(e.Value?.ToString()))
{
    e.CellStyle = AStyle;
}

Upvotes: 1

Related Questions