1

I am trying to get data from form collection as:

foreach (string key in col.Keys)// where col is object of form collection
{
    if (col["ConstituntName[" + i + "]"].ToString() != null)
    { 
        UserRecordSubClass usr = new UserRecordSubClass();
        usr.Value = Convert.ToDecimal(col["ConstituntName[" + i + "]"]);
        usr.ConstituentNameId = Convert.ToInt32(col["ConstituntNameId[" + i + "]"]);
    }

    i++
}

but when the i is 2, ConstituntName["+i+"] does not exist so it throws:

System.NullReferenceException.

How can I prevent this exception in that case?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rupak
  • 409
  • 1
  • 3
  • 18

2 Answers2

2

Just check it for null before calling .ToString():

if ( col["ConstituntName[" + i + "]"] != null 
     && col["ConstituntName[" + i + "]"].ToString() != null)
StepUp
  • 36,391
  • 15
  • 88
  • 148
0

You could use the null conditional operator,

if (col["ConstituntName[" + i + "]"]?.ToString() != null)

The null conditional operator gets evaluated to null if col["ConstituntName[" + i + "]"] or col["ConstituntName[" + i + "]"].ToString() gets evaluated to null

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51