-1

The following method is used by me to convert the cells in a datagrid view into a single string and print the string in the console when button is licked!

private void button3_Click(object sender, EventArgs e)
        {
            String file = "";
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    file = file + dataGridView1.Rows[i].Cells[j].Value.ToString();
                }
            }
            Console.WriteLine(file);
        }

But i get the following error "An unhandled exception of type 'System.NullReferenceException' occured' with the code line dataGridView1.Rows[i].Cells[j].Value.ToString(); highlighted! How can I correct this issue?

Kushan Peiris
  • 167
  • 3
  • 15

2 Answers2

0

You must check if value exists in cell like this ->

if (dataGridView1.Rows[i].Cells[j].Value!=null)
{    
file = file + dataGridView1.Rows[i].Cells[j].Value.ToString();
}
N1gthm4r3
  • 755
  • 1
  • 11
  • 23
0
  private void button3_Click(object sender, EventArgs e)
            {
                string file = "";
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    for (int j = 0; j < dataGridView1.Rows[i].Cells.Count; j++)
                    {
                       if(dataGridView1.Rows[i].Cells[j].Value!=null)
                         {
                      file+=dataGridView1.Rows[i].Cells[j].Value.ToString();
                         }
                       else
                         {
                           file+="";
                         }
                    }
                }
                Console.WriteLine(file);
            }

I think your loop for j is wrong. Let try this.