I have 5 DataTables that needs to be converted to TXT files. Instead of creating them separately, I thought I use a for
loop. Here's my code:
StringBuilder sb = new StringBuilder();
for (int i = 1; i < 5; i++)
{
DataTable dtFile1 = file1BLO.SelectFile1ForCSV()
foreach (DataRow dr in dtFile1.Rows)
{
string[] fields = dr.ItemArray.Select(field => field.ToString()).ToArray();
sb.AppendLine(string.Join("|", fields) + "|");
}
Response.ContentType = "application/text";
Response.AddHeader("content-disposition", "attachment;filename=CAPRES-FILE1-"
+ DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".txt");
Response.Output.Write(sb);
Response.Flush();
Response.End();
sb.Clear();
}
I would want the iterator to be appended to the variable names and methods. Like this DataTable dtFile + i = file + i + BLO.SelectFile + i + ForCSV();
Thanks!
Requested Code for SelectFile1ForCSV()
public DataTable SelectFile1ForCSV()
{
return file1DAO.SelectFile1ForCSV();
}
EDIT: I am sorry, it seems that I haven't provided enough details, and my question has caused confusion. Edited now.
You cannot just append a number to a variable name at runtime to magically reference a new variable. What you should do instead is:
Define an an interface:
Have
File1BLO
,File2BLO
etc all implementIFileBLO
and fix the method names so that they are allSelectFileForCSV
rather thanSelectFile1ForCSV
etc.Add a lookup for reference these objects:
Finally, change your loop to: