views:

67

answers:

4

I don't know whether this is possible or not. What I want to do is to reference a DataTable (and other objects, but getting it working for one will make the rest easy) and use it as a paramater, but I want to do this in a loop, so that I can perform the function with each DataTable dt1, dt2, dt3 etc. Something like this (although this obviously doesn't work):

for (int i = 0; i <= max; i++)
{
    Load("dt"+i);
}

Is this actually possible to do?

+5  A: 

Stick all your DataTables into an array:

var dataTables = new[] { dt1, dt2, dt3 };
foreach(var dt in dataTables)
    // ...
Anton Gogolev
jeez, its so obvious now. Thanks.
Sir Graystar
A: 

Yes, it's possible to do. If you can reference them at compile time you can stick them in an array like Anton said. Otherwise you have to use Reflection to work with them. Either way, the DataTable instances have to be stored in some variable somewhere. Can you give a bit more context? Where are the DataTables coming from?

Nelson
+1  A: 

I recommend using the method sugested by Anton Gogolev. However you can do it how you want using the 'System.Reflection' namespace. Here is an example. Notice that the DataTable members must be public for the GetField to work.

public DataTable dt0 = new DataTable();
public DataTable dt1 = new DataTable();
public DataTable dt2 = new DataTable();

public void findall()
{
    DataTable temp;
    for (int i = 0; i < 3; i++)
        temp = (DataTable)this.GetType().GetField("dt" + i.ToString()).GetValue(this);
}
Jason Webb
A: 
foreach( var dt in new List<int>() { dt1,dt2,dt3,dt4,dt5 })
{
 // do something   
}
Andrew Lewis