DataTable、DataColumn、DataRow C# 应用示例代码

作者:MSDN 来源:MSDN 日期:2008-7-30
DataTable tbl = new DataTable("示例表");

DataColumn codeColumn = new DataColumn();
codeColumn.ColumnName = "代码";
codeColumn.DataType = System.Type.GetType("System.String");
codeColumn.AllowDBNull = true;
tbl.Columns.Add(codeColumn);
 
DataColumn districtColumn = new DataColumn(); //一列对应一个 DataColumn 对象。
districtColumn.ColumnName = "地区";
districtColumn.DataType = System.Type.GetType("System.String");
districtColumn.AllowDBNull = true;
tbl.Columns.Add(districtColumn);
 
DataRow row = tbl.Rows.Add();
row["地区"] = "重庆";

上面是我写的示例,下面是 MSDN 上的示例:

private void CreateNewDataRow()
{
    // Use the MakeTable function below to create a new table.
    DataTable table;
    table = MakeNamesTable();

// Once a table has been created, use the // NewRow to create a DataRow. DataRow row; row = table.NewRow();

// Then add the new row to the collection. row["fName"] = "John"; row["lName"] = "Smith"; table.Rows.Add(row);

foreach(DataColumn column in table.Columns) Console.WriteLine(column.ColumnName); dataGrid1.DataSource=table; }

private DataTable MakeNamesTable() { // Create a new DataTable titled 'Names.' DataTable namesTable = new DataTable("Names");

// Add three column objects to the table. DataColumn idColumn = new DataColumn(); idColumn.DataType = System.Type.GetType("System.Int32"); idColumn.ColumnName = "id"; idColumn.AutoIncrement = true; namesTable.Columns.Add(idColumn);

DataColumn fNameColumn = new DataColumn(); fNameColumn.DataType = System.Type.GetType("System.String"); fNameColumn.ColumnName = "Fname"; fNameColumn.DefaultValue = "Fname"; namesTable.Columns.Add(fNameColumn);

DataColumn lNameColumn = new DataColumn(); lNameColumn.DataType = System.Type.GetType("System.String"); lNameColumn.ColumnName = "LName"; namesTable.Columns.Add(lNameColumn);

// Create an array for DataColumn objects. DataColumn [] keys = new DataColumn [1]; keys[0] = idColumn; namesTable.PrimaryKey = keys;

// Return the new DataTable. return namesTable; }

你前面那位网友看了:HTTP 错误 500.19 - Internal Server Error

▲▲▲嘿,欢迎转载传播本站原创文章,尽量保留来源噢。▲▲▲

文章评论
标题:必填
内容: