0

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..
}
}
MPelletier
  • 16,256
  • 15
  • 86
  • 137
dotnet-practitioner
  • 13,968
  • 36
  • 127
  • 200

5 Answers5

5

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
  • 182,639
  • 35
  • 285
  • 343
  • 1
    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 Mar 16 '10 at 17:30
  • 1
    @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 Mar 16 '10 at 17:34
3

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
  • 62,308
  • 19
  • 113
  • 113
2

Maybe something like this?

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.Index == 0)
        {
            //...
        }
        else
        {
            //...
        }
    }
Javier
  • 4,051
  • 2
  • 22
  • 20
  • 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 Mar 16 '10 at 17:35
0

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
    }
}
Roast
  • 1,715
  • 5
  • 24
  • 32
0

First convert the DataRow to DataRowView:

How Can Convert DataRow to DataRowView in c#

and after that:

    foreach (DataRowView rowview in DataView)
{
    if (DataRowView.Table.Rows.IndexOf(rowview.Row) == 0)
    {
        // bla, bla, bla... 
    }
}
Community
  • 1
  • 1