How to increment a variable if it is the first row of data table

Viewed 827

i have a data table having several rows. I want to increment a variable say i, only if it is the first row of the data table. How can I do that?

 foreach (DataRow row in dt.Rows)
 {  
     address = (row["address"].ToString());
     Counter += 1;
     int count = Convert.ToInt16(Dt.Rows[i]["limit"]);

     //for the first row
     if (Counter == count)
     {
         i += 1;
     }

     // also if it is the last row  
       exit;
3 Answers

You should work with a for loop - hat makes the index access easier

for (int i = 0; i < dt.Rows.Count; i++)
{
    string address = dt.Rows[i].Field<string>("address");
    if (i == 0)
    {
        //first row, increment here
    }
    if (i == dt.Rows.Count - 1)
    {
        //last row
    }
}

Why not a simple flag, say isFirstRow?

 bool isFirstRow = true;

 foreach (DataRow row in dt.Rows)
 {  
     if (isFirstRow) 
     {
         isFirstRow = false;

         //TODO: Increment here 
     } 
     ... 

Edit: In case of last row we can do postprocessing:

 DataRow lastRow = null;

 foreach (DataRow row in dt.Rows) {
   // Candidate for the last row
   lastRow = row;
   ... 
 }

 if (lastRow != null) {
   //TODO: Put relevant code for the last row     
 }

You can use code like below. Use IndexOf method of DataRowCollection class to determine if it's the first row. I have created a sample DataTable object before the loop. The main part of this answer is the if statement within the loop's body that checks for row index.

Keep in mind that the index of row in DataTable starts from 0 and not 1. So, first row has an index of 0, second row has an index of 1, third row row has index of 2 and so on.

    DataTable dt = new DataTable();
    dt.Columns.Add("EmployeeId", typeof(int));
    dt.Columns.Add("FirstName", typeof(string));
    dt.Columns.Add("LastName", typeof(string));
    dt.Columns.Add("Grade", typeof(int));

    // Here we add five DataRows.
    dt.Rows.Add(11, "John", "Smith", 9);
    dt.Rows.Add(92, "Sunita", "Mali", 7);
    dt.Rows.Add(2, "Anil", "Kumar", 4);
    dt.Rows.Add(5, "Mike", "Reb", 11);
    dt.Rows.Add(1, "Sunil", "Dev", 12);

   //your counter variable
    int i= 0;

    foreach(DataRow row in dt.Rows) {
      //use IndexOf method to check if it's the first row
      if( dt.Rows.IndexOf(row) == 0) {
        i++;//only first row causes increment of i
      }

      if(dt.Rows.IndexOf(row) == (dt.Rows.Count -1)) {
       //its the last row of datatable
      }

    }
Related