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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With