Reputation: 11393
I want to to know how to check there is a row in specific index to avoid the following exception :
System.IndexOutOfRangeException
for example :
if (dtNew != null && dtNew.Rows.Count > 0 )
{
if (dtNew.Rows[i][0] != null)
{
row["newEmp"] = dtNew.Rows[i][0];
}
else
{
row["newEmp"] = 0;
}
}
What if dtNew
has just a one row
and the i = 3
!!
Upvotes: 0
Views: 426
Reputation: 1500515
Well if you want to get to row i
, you need to change your check from
&& dtNew.Rows.Count > 0
to
&& dtNew.Rows.Count > i
Currently you're only checking whether there are any rows - i.e. whether dtNew.Rows[0]
is valid.
(Do you definitely need to check for dtNew
being null
? Is that a valid program state? Likewise is it valid for the row to exist but column 0 to not be populated? You may be able to make your code much simpler.)
Upvotes: 2