[Solved] C# How to read all the data in a datagridview and put it in a listbox?


I get the following error: “Object reference not set to an instance of an object”

The exception is throwing at the “string data” line.

I guess one of the values in your DataGridView has the value null. When you try to call the ToString() method on the property Value in:

string data = dgvOverzicht.Rows[getal - 1].Cells[i].Value.ToString();

it throws the exception.

One way to work around this is to check whether Value is null and if not then go ahead and call the ToString() method:

int getal = 0;

for (int i = 1; i < 10; i++)
{
    getal++;
    DataGridViewCell  c = dgvOverzicht.Rows[getal - 1].Cells[i];
    if (c.Value != null)
    {
        listBox1.Items.Add(c.Value.ToString());
    }
}

EDIT:

The for loop that you use will only visit the diagonal of your grid. If you want to get all Cells you need 2 for-loops:

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    for (int j = 0; j < dataGridView1.Columns.Count; j++)
    {
        DataGridViewCell c = dataGridView1.Rows[i].Cells[j];
        if (c.Value != null)
        {
            listBox1.Items.Add(c.Value.ToString());
        }
    }                
}

12

solved C# How to read all the data in a datagridview and put it in a listbox?