DataTable has a collection of Rows, and you can get each rows by index, or using the enumerator (in a foreach loop), for example:
for(var i=0; i<dt.Rows.Count; i++)
{
var row = dt.Rows[i];
}
or
foreach(DataRow row in dt.Rows)
{
}
You can get column values using either of the following options:
- Column Index: For example
dt.Rows[0][0]
- Column Name: For example
dt.Rows[0]["FirstName"]
-
Field<>
method: For exampledt.Field<string>(0)
, ordt.Field<string>("FirstName")
That said, you can show all the rows and their values like this:
using System.Data;
using System.Runtime.InteropServices;
namespace SampleConsoleApp
{
internal static class Program
{
[STAThread]
static unsafe void Main()
{
var dt = new DataTable();
dt.Columns.Add("Code", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "One");
dt.Rows.Add(2, "Two");
dt.Rows.Add(3, "Three");
foreach (DataRow row in dt.Rows)
{
Console.WriteLine($"Code:{row[0]}, Name:{row[1]}");
}
}
}
}
Or the following option, is a little different, returns a List<string> where each row is string representation of the row:
var list = dt.AsEnumerable().Select(
row => string.Join(",", row.ItemArray.Select(value => $"{value}")))
.ToList();