How can I get DataGridView row values ​​and store them 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.

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.