Click here to Skip to main content
15,884,923 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a 10 rows in my DataTable. Now i want to insert records using foreach loop.
like this

C#
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

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:
C#
bool skip = true;
foreach (DataRow row in dt.Rows)
    {
    if (!skip)
        {
        ...
        }
    skip = false;
    }
 
Share this answer
 
use for loop which start from 1 to your dt.rows.count
 
Share this answer
 
Comments
Naveen.Sanagasetti 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 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900