Net implementation of storing the current row index

I need to find out what the current Row index is from a loop foreach.

foreach (DataRow row in DataTable[0].Rows)
{
    // I do stuff in here with the row, and if it throws an exception
    // I need to pass out the row Index value to the catch statement
}

An exception can occur at any point in the block try/catch, but if I use an incremental counter in the loop foreach, and the exception occurs outside the loop, I get an invalid string, ve moved the pointer one by one.

I know that I can declare DataRowout of scope foreach, but foreachis in the block try/catch. I need to pass the Row index so that I can use it in the statement catch. I have to say mine DataTableis in the class level area.

Is this really the only way to get the current Row index? Or is there a cleaner implementation?

EDIT

So, reflecting on this, I could use intto store the current value of the string and increase this value as follows:

int i = 0;

try
{
    // Some code here - which could throw an exception
    foreach (DataRow row in DataTables[0].Rows)
    {
        // My stuff
        i++;
    }
    // Some code here - which could throw an exception
}
catch
{
    // Use the counter
    DataRow row = DataTables[0].Rows[i];
}

However, if it foreachdoes not throw an exception, then the value iwill be greater than the actual number of rows in the table. Obviously, I could do it i--;after the loop foreach, but that seems like a really dirty hack.

+5
source share
2 answers

the dirty way is to cut it in an extra trycatch block:

int i = 0;
try
{
    // Some code here - which could throw an exception

    try{
        foreach (DataRow row in DataTables[0].Rows)
        {
            // My stuff
            i++;
        }
        // Some code here - which could throw an exception
    }
    catch{
      i--;
      throw;
    }

}
catch
{
    // Use the counter
    DataRow row = DataTables[0].Rows[i];
}

this way, you probably know that the exception is thrown correctly, and then you get the right iterator.

0
source

Declare a counter variable outside of try and increment for each iteration of the loop:

int counter = 0;

try
{
    foreach (DataRow row in DataTable[0].Rows)
    {
        // Do stuff
        counter++
    }

    counter = -1;
    // Do other stuff
}
catch
{
    // Counter has index
    if (counter == -1)
    {
       // exception did not occur in loop
    }
    else
    {
       // exception did occur in loop
    }
}
0
source

All Articles