I have the following code below. Which works great expect I want to allow MaxDemand to be a null value. But since i’m parsing a string it seems to error if I don’t put in some value.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Whats the best solution to implement an error handling solution? I tried float.TryParse but can’t get that to work.
Thank you for looking over my issue.
protected void GridView3_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
float Cost = 0.0F;
float Consumption = 0.0F;
int InvoiceID = 0;
float MaxDemand = 0.0F;
DateTime ServiceFrom = new DateTime();
DateTime ServiceTo = new DateTime();
foreach (string key in e.NewValues.Keys)
switch (key)
{
case "TotalInvoice": Cost = float.Parse(e.NewValues[key].ToString());
break;
case "EnergyInvoiceID": InvoiceID = int.Parse(e.NewValues[key].ToString());
break;
case "Consumption": Consumption = float.Parse(e.NewValues[key].ToString());
break;
case "ServiceFrom": ServiceFrom = DateTime.Parse(e.NewValues[key].ToString());
break;
case "ServiceTo": ServiceTo = DateTime.Parse(e.NewValues[key].ToString());
break;
case "MaxDemand": MaxDemand = float.Parse(e.NewValues[key].ToString());
break;
}
UpdateInvoice(InvoiceID, Cost, Consumption, ServiceFrom, ServiceTo, MaxDemand);
GridView3.EditIndex = -1;
PopulateAccountHistory();
}
The problem here isn’t in the actual parsing of the
floatordoublevalue. If that failed it would return a more specific exception. It appears that the problem is one of the returns ofe.NewValues[key]is returningnulland you are throwing on the call toToStringIt would be best to centralize the
nullchecks at the start of the loop. It would also allow you to remove the repeated calls toe.NewValues[key].