Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: ASP.NET C#4.0
I have a 10 rows in my DataTable. Now i want to insert records using foreach loop.
like this
 
foreach(DataRow dr dt.Rows)
{
 
}
 
But i don't want to insert row 0.
 
I want to insert from row 1 onwords.
 
I know the logic using for loop but i want using foreach.
 
Can any one give me suggestion to fix the possition using foreach only...
Posted 14-Feb-13 1:19am
N@veen.S1.6K
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

A foreach loop always works on all the elements on the Collection you feed it, so there is no mechanism to "skip" the first (or any other element) other than using break to exit the loop completely.
 
There are two ways to miss out the first element:
1) Copy the list into a new collection and remove the first element.
2) Add a bool outside the foreach:
bool skip = true;
foreach (DataRow row in dt.Rows)
    {
    if (!skip)
        {
        ...
        }
    skip = false;
    }
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

use for loop which start from 1 to your dt.rows.count
  Permalink  
Comments
naveensenagasetti at 14-Feb-13 7:03am
   
I already mentioned in my question i know how to do using for loop but i'm asking using foreach loop
vishal.shimpi at 14-Feb-13 7:58am
   
bool isfirst = true;
foreach (DataRow row in dt.Rows)
{
if(isfirst)
{
first = false;
continue;
}
//do your operation here
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 George Jonsson 215
1 Kornfeld Eliyahu Peter 169
2 OriginalGriff 120
3 PIEBALDconsult 110
4 BillWoodruff 85
0 OriginalGriff 6,165
1 DamithSL 4,658
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,649
4 Sergey Alexandrovich Kryukov 3,294


Advertise | Privacy | Mobile
Web01 | 2.8.141220.1 | Last Updated 14 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100