我的DataTable
1、新建DataTable:
DataTable dataTable = new DataTable();
DataTable dataTable = new DataTable("MyTable");
```
2、新建列:
```csharp
DataColumn dataColumn = new DataColumn("column" + i, typeof(string));
```
例:
~~~csharp
for (int i = 0; i < 10; i++)
{
DataColumn dataColumn = new DataColumn("Column" + i, typeof(string));
dataTable.Columns.Add(dataColumn);
}
3、在表中各列填充数据:
for(int i = 0; i < 20; i ++)
{
DataRow dataRow = dataTable.NewRow();
for(int j = 0; j < dataTable.Columns.Count; j ++)
{
dataRow[j] = new Random().Next(100, 200);
}
dataTable.Rows.Add(dataRow);
}
4、如何打印DataTable:
- 先打印列名:(除了Caption外,还有ColumnName也可以得到列名。)
for (int i = 0; i < dataTable.Columns.Count; i++)
{
Console.Write(dataTable.Columns[i].Caption + " ");
}
- 打印数据:
for (int i = 0; i < dataTable.Rows.Count; i++)
{
for (int j = 0; j < dataTable.Columns.Count; j++)
{
Console.Write(dataTable.Rows[i][j] + " ");
}
Console.Write("\n");
}