1

I have a column fields with different names. For example I load the files from ABC. and the Name column fields will be ABC.

I have to show a button only when I select the ABC row object.

I wrote a code below, but its throwing an exception. It would be great helpful if someone suggest me on this.

FormViewButton fvb = FormViewButton.getInstance();

        foreach (DataGridViewRow row in this.dataGridView1.Rows)
        {
            row.DefaultCellStyle.SelectionBackColor = this.dataGridView1.DefaultCellStyle.SelectionBackColor;


            bool selectedRow = row.Cells["Name"].Selected;

            if (row.Cells["Name"].Value.ToString().Equals("ABC") && selectedRow == true) // A Nullreferenceexception was unhandled by user code is thrown here. 
            {
                fmv.showButton.Visible = true;
            }
            else if (!row.Cells["Name"].Value.ToString().Equals("ABC") && selectedRow != true)
            { 
                fmv.showButton.Visible = false;
            }

        }
Sunny
  • 61
  • 8
  • 3
    Related: [What is a `NullReferenceException` and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül Apr 24 '15 at 06:13

2 Answers2

1

It happens because either row.Cells["Name"] or row.Cells["Name"].Value doesn't exist.

Solution: When you iterate through Rows of your DataGridView, check indexes:

  • if RowIndex == -1 then it's a header row
  • if RowIndex == dataGridView1.NewRowIndex then its a new row, and the cell's Value will be null

... and check if row.Cells["Name"] != null && row.Cells["Name"].Value != null, just in case

Arie
  • 5,251
  • 2
  • 33
  • 54
0

if a cell or string variable is null and you try to attach some string method to it, such as something.ToString() or something.indexof etc., C# will always throw a null exception error.

SteveFerg
  • 3,466
  • 7
  • 19
  • 31