views:

43

answers:

4

what is the best way to identify first row in the following code?

foreach(DataRow row in myrows)
{

if (first row )
{
...do this...
}
else
{
....process other than first rows..
}
}
+3  A: 

you could just use a for loop instead

for(int i = 0; i < myrows.Count; i++) 
{
    DataRow row = myrows[i];
    if (i == 0) { }
    else { }
{
hunter
+3  A: 

You can use a boolean flag for this:

bool isFirst = true;

foreach(DataRow row in myrows)
{
    if (isFirst)
    {
        isFirst = false;
        ...do this...
    }
    else
    {
        ....process other than first rows..
    }
}
Adam Robinson
Mmmm... @Adam, I´m sure that you answered this with a good reason. I'm curious to know why is better to use a boolean that check if the row index == 0. Is more eficient? thanks! :-)
Javier Morillo
@Javier: Do you mean calling `Array.IndexOf(myrows, row) == 0`? If so, then yes, this is absolutely more efficient. If you want to know the index, then Hunter's solution using a `for` loop would be more advisable. If you're referring to `row.Index`, then that's its index within its parent `DataTable`, *not* within the array that he describes.
Adam Robinson
aaaaaaaahmm... :-) ok! thanks very much! +1
Javier Morillo
+2  A: 

Maybe something like this?

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.Index == 0)
        {
            //...
        }
        else
        {
            //...
        }
    }
Javier Morillo
He indicates that he has a `DataRow[]`, not a `DataTable`. There's no necessary correlation between a row's index in a table and its index within an arbitrary array.
Adam Robinson
A: 

Use a int to loop through the collection.

for (int i =0; i < myDataTable.Rows.Count;i++)
{
    if (i ==0)
    {
       //first row code here
    }
    else
    {
       //other rows here
    }
}
Lily