1

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?

1
  • Where are your DataTables stored? Do you have a separate variable for each named, dt1, dt2, etc or are they stored in something like a hastable where the stirngs dt1, dt2, etc are the keys? Commented Jun 9, 2010 at 15:28

4 Answers 4

5

Stick all your DataTables into an array:

var dataTables = new[] { dt1, dt2, dt3 };
foreach(var dt in dataTables)
    // ...
Sign up to request clarification or add additional context in comments.

1 Comment

jeez, its so obvious now. Thanks.
1

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);
}

Comments

0

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?

Comments

0
foreach( var dt in new List<int>() { dt1,dt2,dt3,dt4,dt5 })
{
 // do something   
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.