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
  • 704,970
  • 168
  • 1,303
  • 1,425
Rupak
  • 339
  • 2
  • 15

2 Answers2

2

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

if ( col["ConstituntName[" + i + "]"] != null 
     && col["ConstituntName[" + i + "]"].ToString() != null)
StepUp
  • 30,747
  • 12
  • 76
  • 133
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
  • 16,800
  • 2
  • 18
  • 44