0

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 !!

3
  • Can you use Contains method? Commented May 12, 2014 at 9:24
  • 1
    iterate over it using Count of it Commented May 12, 2014 at 9:24
  • the loop has more than datatable wiz different counts Commented May 12, 2014 at 9:26

1 Answer 1

2

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.