First learn about that particular error message.
What Is NullReferenceException? Object reference not set to an instance of an object – Stackify[
^]
And debug your code always to solve most of issues quickly.
Tutorial: Debug C# code - Visual Studio | Microsoft Docs[
^]
Set a breakpoint on exception thrown line, run your code & see the value.
cmd.Parameters.AddWithValue("@BodyM", row.Cells["BodyM"].Value.ToString());
Use
Quick Watch(Shift + F9) to see the value.
Here simple example to check your values while debugging. Ensure you're getting value for
row.Cells["BodyM"].Value
, if you're getting null, check value for
row.Cells["BodyM"]
. If you're getting null here, check value for
row.Cells
& just
row
Based on above observations, you need to handle things.
Here a simple code to handle not null.
string strBodyM = string.Empty;
if(row.Cells["BodyM"].Value != null)
{
strBodyM = row.Cells["BodyM"].Value.ToString();
}
cmd.Parameters.AddWithValue("@BodyM", strBodyM);
If you're getting
null
for
row.Cells["BodyM"]
itself, then you need to check things on other sides. Ensure name is
BodyM
. Sometime typos giving this error.
Now proceed further on making changes in your code.