using System.Data;
namespace testDataTable
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("Role", typeof(string));
dt.PrimaryKey = new DataColumn[] { dt.Columns["id"] };//添加主键
dt.Rows.Add(new object[] { 1, "超级管理员" });
dt.Rows.Add(new object[] { 2, "管理员" });
dt.Rows.Add(new object[] { 3, "普通用户" });
DataRow[] currentRows = dt.Select(null, null, DataViewRowState.CurrentRows);
if (currentRows.Length < 1)
Console.WriteLine("No Current Rows Found");
else
{
foreach (DataColumn column in dt.Columns)
Console.Write("/t{0}", column.ColumnName);
//Console.WriteLine("/tRowState");
foreach (DataRow row in currentRows)
{
Console.WriteLine("/t");
foreach (DataColumn column in dt.Columns)
Console.Write("/t{0}", row[column]);
Console.WriteLine("/t");
//Console.WriteLine("/t" + row.RowState);
}
}
Console.ReadLine();
}
}
}
显示结果
using System.Data;
namespace baobiao
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("Role", typeof(string));
dt.Columns.Add("Remark", typeof(string));
dt.PrimaryKey = new DataColumn[] { dt.Columns["id"] };//添加主键
dt.Rows.Add(new object[] { 1, "超级管理员", "无" });
dt.Rows.Add(new object[] { 2, "管理员", "asa" });
dt.Rows.Add(new object[] { 3, "普通用户", "1212" });
dt.Rows.Add(new object[] { 4, "权限", "211s" });
DataRow[] currentRows = dt.Select(null, null, DataViewRowState.CurrentRows);
if (currentRows.Length < 1)
Console.WriteLine("No Current Rows Found");
else
{
int column1 = 0;
foreach (DataColumn column in dt.Columns)
{
Console.WriteLine("/t");
Console.Write("/t{0}", column.ColumnName);
foreach (DataRow row in dt.Rows)
{
//一个萝卜放一个坑
Console.Write("/t{0}", row[column1]);
}
column1++;
Console.WriteLine("/t");
}
}
//下面foreach 用法
//int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
//foreach (int i in fibarray)
//{
// System.Console.WriteLine(i);
//}
//
//int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
//foreach (int i in numbers2D)
//{
// System.Console.Write("{0} ", i);
//}
Console.ReadLine();
}
}
}
输出结果: