Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get DataGridView row values and store in variables?

How can i loop through a DataGridView's rows at a time (I have 2 columns) then store those 2 columns in a variable which I will be using as a parameter for an sql query?

  foreach (DataGridViewRow Datarow in contentTable_grd.Rows)
            {
                contentValue1 = Datarow.Cells[0].Value.ToString();
                contentValue2 = Datarow.Cells[1].Value.ToString();

                SqlParameter param4 = new SqlParameter("@contentTableValue1", contentValue1);
                SqlParameter param5 = new SqlParameter("@contentTableValue2", contentValue2);

            }

I'm getting this error when using the above code -

Object reference not set to an instance of an object.

like image 920
kurupt_89 Avatar asked Aug 03 '11 23:08

kurupt_89


2 Answers

The most likely problem is that the one or both the Cell's you're referencing contains a null value and the exception is thrown when you attempt to call ToString() on such a cell.

One solution is to use the ?? operator to return a default value for your parameter if a Cell Value is null:

contentValue1 = Datarow.Cells[0].Value ?? string.Empty;
contentValue2 = Datarow.Cells[1].Value ?? string.Empty;

This code will return an empty string if a cell's Value is null; you might wish to use a different default.

like image 121
Jay Riggs Avatar answered Nov 03 '22 00:11

Jay Riggs


Found the problem I needed an if statement to prevent empty cells from going through

    foreach (DataGridViewRow Datarow in contentTable_grd.Rows)
    {
        if (Datarow.Cells[0].Value != null && Datarow.Cells[1].Value != null)
        {
            contentValue1 = Datarow.Cells[0].Value.ToString();
            contentValue2 = Datarow.Cells[1].Value.ToString();
            MessageBox.Show(contentValue1);
            MessageBox.Show(contentValue2);
        }

    }
like image 39
kurupt_89 Avatar answered Nov 03 '22 02:11

kurupt_89