0

So I have a method called on the DataGridViewCellFormattingEvent that inspects the first column of my datagridview. If a row is found to have a value in the first column set to either an H or an F, it colors all the cells in that row one way or another, but then also sets the row to ReadOnly, Selected = false, and font to Bold. This is my workaround to including additonal Headers and Footers...it works great, except for this one problem.

If I set the datagridview AllowUserToAddRow property to true (Which ultimately we need to do), this method throws an invalid reference exception when it tries to get the cell value. The value is returning null, and I tried various methods to pass out of the method if that value is null, but it just keeps throwing the error no matter what I do. I would appreciate it if someone could offer some advice. Here is my method (note the only way I can get it to work is by setting the AllowUserToAddRows to false...I didn't normally have it in this method but included it for reference):

    private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs args)
    {
        var dgv = (DataGridView)sender;
        dgv.AllowUserToAddRows = false;

        if (!dgv.Rows[args.RowIndex].Cells[0].Value.Equals(null))
        {
            string cellValue = dgv.Rows[args.RowIndex].Cells[0].Value.ToString();

            bool regF = Regex.Match(cellValue, "F.*").Success;
            bool regH = Regex.Match(cellValue, "H.*").Success;

            if (regH == true)
                args.CellStyle.BackColor = System.Drawing.Color.LightBlue;

            if (regF == true)
                args.CellStyle.BackColor = System.Drawing.Color.LightGray;

            if (regH == true || regF == true)
            {
                args.CellStyle.Font = new System.Drawing.Font(args.CellStyle.Font, FontStyle.Bold);
                dgv.Rows[args.RowIndex].Cells[args.ColumnIndex].Selected = false;
                dgv.Rows[args.RowIndex].ReadOnly = true;
            }
        }
    }

This is the line that breaks:

    if (!dgv.Rows[args.RowIndex].Cells[0].Value.Equals(null))

I tried using IsNullOrEmpty, doing a direct ... == null, all with the same result

svenGUTT
  • 399
  • 4
  • 11

1 Answers1

0

Sorry if I wasted anyone's time with this, but I found a resolution. Instead of directly comparing null to my referenced value, I set the value as a DataGridViewCell object first, then I was able to properly compare its value to null. Here is the update I made:

DataGridViewCell c = dgv.Rows[args.RowIndex].Cells[0]; 
if (c.Value != null) 
svenGUTT
  • 399
  • 4
  • 11