possible null reference argument for parameter 's' parse in 'double double.Parse(string s)'
dr = cm.ExecuteReader();
while (dr.Read())
{
i = 1;
_total = double.Parse(s: dr["total"].ToString()); // warning message
dataGridView1.Rows.Add(i, dr["id"].ToString(), dr["transno"].ToString(), dr["pcode"].ToString(), dr["pdesc"].ToString(), dr["price"].ToString(), dr["qty"].ToString(), dr["disc"].ToString(), dr["total"].ToString());
}
CodePudding user response:
C# does not know value of your column. That's why you are getting this warning. When the value of your column is null, calling .ToString()
on null results in a NullReferenceException
at runtime.
When you know that this column exists 100%, you can do it like this to get rid off the warning:
dr["total"]!.ToString()
Or even better: use an object-mapping framework like Dapper. It will save you tons of hours.
CodePudding user response:
The reason of the warning is that dr["total"]
can return null
(in case there's no field "total"
in the cursor) and .ToString()
will throw exception.
If you are sure that the field does exist rain or shine you can switch this warning off with the null forgiving operator !
:
// using: do not forget to Dispose IDisposable (dr)
using var dr = cm.ExecuteReader();
while (dr.Read()) {
i = 1;
_total = Convert.ToDouble(dr["total"]!);
dataGridView1.Rows.Add(i,
dr["id"]!.ToString(),
dr["transno"]!.ToString(),
dr["pcode"]!.ToString(),
dr["pdesc"]!.ToString(),
dr["price"]!.ToString(),
dr["qty"]!.ToString(),
dr["disc"]!.ToString(),
dr["total"]!.ToString());
}
Note, that we can get rid of to and from string
conversion and let .net convert the value with Convert