0

I am getting object reference not an instance of object which submitting the request.

      customer.CustomerNumber = Convert.ToInt32(HdnCustomerNo.Value);

How to set "0" if hidden field have no value.

  • 1
    Check to see whether `HdnCustomerNo` is `null` first? – canton7 May 06 '20 at 09:39
  • Try this: `customer.CustomerNumber = Convert.ToInt32(HdnCustomerNo?.Value ?? "");` – Zohar Peled May 06 '20 at 09:40
  • @ZoharPeled That will throw a ```System.FormatException```. – imsmn May 06 '20 at 09:42
  • @ZoharPeled That doesn't even compile: https://dotnetfiddle.net/jtgkpJ – canton7 May 06 '20 at 09:43
  • @canton7 You're assuming `HdnCustomerNo` is a nullable int. I was assuming it's was a type written by the OP (perhaps wrongly). For a nullable int, of course that wouldn't work - but then again, `Convert.ToInt32` is completely redundant for `int?` - if `HdnCustomerNo` is a nullable int all the OP needs is `HdnCustomerNo.GetValueOrDefault()`... – Zohar Peled May 06 '20 at 09:56
  • @ZoharPeled I did that based on the title of the question, and the fact that they're accessing `.Value`. Agreed though, the question doesn't make sense -- that's why step 0 is to find out what the question is. Regardless, `Convert.ToInt32("")` throws, as @Shawn said – canton7 May 06 '20 at 09:58
  • @Shawn correct. If my assumption that the `Value` property is actually a string is correct (see my comment to canton7), than the `?? ""` part is a problem. remove that, and `Convert.ToInt32` will return 0 for a null string. I almost never use `Convert.ToInt32` - I prefer `int.TryParse` – Zohar Peled May 06 '20 at 09:58
  • int.tryParse(HdnCustomerNo.Value,out int number); cutomer.CustomerNumber= number ; But still getting same object reference not an instance of object –  May 06 '20 at 12:22
  • @BParida You're getting a null reference exception beacuse `HdnCustomerNo` is null. canton7 and Shawn both talked about the conversion to int of `HdnCustomerNo.Value` - Naturally, that can only be done if `HdnCustomerNo` is not null. – Zohar Peled May 06 '20 at 12:58

0 Answers0