Click here to Skip to main content
15,898,538 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
hi, does anyone know how do I loop through all datatable in dataset with a For Loop instead of foreach loop? I know foreach loop can do this but I want to use a For loop instead.

For example:

HTML
foreach (DataTable table in ds.Tables)
{
}


I would like to use a For Loop instead.

Appreciate if someone can help me on this. Thanks !

Regards,

Felicia
Posted
Updated 28-Sep-15 23:14pm
v2

You can do:

C#
DataSet ds = new DataSet();
for (int count = 0; count < ds.Tables.Count; count++)
{
    // Get individual datatables here...
    DataTable table = ds.Tables[count];
}
 
Share this answer
 
By simply using Dataset.Tables.Count property

C#
for (int i=0; i< ds.Tables.Count;i++)
{
   //your logic goes here
}


Why don't you want to use foreach, any specific reason?
I would like to recommend to use foreach over for loop unless there is any specific requirement.

Hope, it helps :)
 
Share this answer
 
v3
C#
for(int i=0; i < ds.Tables.Count; i++)
{
    // TODO:...
}


-KR
 
Share this answer
 
v2
Comments
Suvendu Shekhar Giri 29-Sep-15 5:13am    
If I am not wrong, it should be i < ds.Tables.Count if i is intialized to 0 else i need to be initialized to 1.
Krunal Rohit 29-Sep-15 5:21am    
Depends on your requirements.

-KR
Suvendu Shekhar Giri 29-Sep-15 5:29am    
In what kind of requirement you think it will be useful?
The loop will be executed for "no of tables in dataset"+1 times, isn't it?
Can you please share such a requirement for reference? Thanks !

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