private void MakeDataTableAndDisplay(){
// Create new DataTable.
DataTable myDataTable = new DataTable("MyDataTable");
// Declare DataColumn and DataRow variables.
DataColumn myDataColumn;
DataRow myDataRow;
// Create new DataColumn, set DataType, ColumnName and add to DataTable.
myDataColumn = new DataColumn();
myDataColumn.DataType = System.Type.GetType("System.Int32");
myDataColumn.ColumnName = "id";
myDataTable.Columns.Add(myDataColumn);
// Create second column.
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "item";
myDataTable.Columns.Add(myDataColumn);
// Create new DataRow objects and add to DataTable.
for(int i = 0; i < 10; i++){
myDataRow = myDataTable.NewRow();
myDataRow["id"] = i;
myDataRow["item"] = "item " + i;
myDataTable.Rows.Add(myDataRow);
}
// Set to DataGrid.DataSource property to the table.
dataGrid1.DataSource = myDataTable;
}
--------------------
C# 在代码中创建 DataTable 和从数据库取出的数据 DataTable 合并
myDataRow = myDataTable.NewRow();
myDataRow["id"] = i;
myDataRow["item"] = "item " + i;
myDataTable.Rows.Add(myDataRow);