Hi,
I have a datatable that I extracted from my dataset.
I want to enumerate through the datatable, and output all the rows.
Each row has to display all the column information, comma or tab seperated.
How can I do this?
for (int x = 0; x < dt.Rows.Count; x++)
{
DataRow dr = dt.Rows[x];
// ?? how to list all the column information?
}

1 answers
Here's some example code for enumerating and outputting a DataTable's rows as comma separated strings.
Although you're getting the DataTable from a DataSet, I've created one individually and added some sample data in order to test the code:
using System;
using System.Data;
class Program
{
static void Main()
{
DataTable dt = CreateTable();
string[] columnData = new string[dt.Columns.Count];
string columnString = null;
foreach (DataRow dr in dt.Rows)
{
for(int i = 0; i < columnData.Length; i++)
{
columnData[i] = dr[i].ToString();
}
columnString = String.Join(",",columnData);
Console.WriteLine(columnString);
}
Console.ReadKey();
}
static DataTable CreateTable()
{
DataTable table = new DataTable("Persons");
DataColumn column;
DataRow row;
column = new DataColumn();
column.DataType = Type.GetType("System.Int32");
column.ColumnName = "Id";
table.Columns.Add(column);
column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "Name";
table.Columns.Add(column);
column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "Sex";
table.Columns.Add(column);
column = new DataColumn();
column.DataType = Type.GetType("System.Int32");
column.ColumnName = "Age";
table.Columns.Add(column);
string[] names = new string[]{"John", "Fred", "Louise", "David"};
string[] genders = new string[]{ "M","M","F","M"};
int[] ages = new int[]{25,35,45,55};
for (int i = 0; i < 4; i++)
{
row = table.NewRow();
row["Id"] = i + 1;
row["Name"] = names[i];
row["Sex"] = genders[i];
row["Age"] = ages[i];
table.Rows.Add(row);
}
return table;
}
}
answered 2 years ago by:
17279
This post was imported from csharpfriends, if you have a similiar question please ask it again.
All previous members have been migrated, hope you enjoy the new platform!