创建 DataTable

记录一下 基础知识

        DataTable dt = new DataTable();
        dt.Columns.Add(
"Name");
        dt.Columns.Add(
"Value");
        DataRow dr;
        dr 
= dt.NewRow();
        dr[
"Name"= "Ntext2";
        dr[
"Value"= "TesrNtext2";
        dt.Rows.Add(dr);

private void MakeDataTableAndDisplay()
{
    
// Create new DataTable.
    DataTable table = new DataTable("table");

    
// Declare DataColumn and DataRow variables.
    DataColumn column;
    DataRow row;
 
    
// Create new DataColumn, set DataType, 
    
// ColumnName and add to DataTable.    
    column = new DataColumn();
    column.DataType 
= System.Type.GetType("System.Int32");
    column.ColumnName 
= "id";
    table.Columns.Add(column);
 
    
// Create second column.
    column = new DataColumn();
    column.DataType 
= Type.GetType("System.String");
    column.ColumnName 
= "item";
    table.Columns.Add(column);
 
    
// Create new DataRow objects and add to DataTable.    
    for(int i = 0; i < 10; i++)
    
{
        row 
= table.NewRow();
        row[
"id"= i;
        row[
"item"= "item " + i;
        table.Rows.Add(row);
    }

    
// Set to DataGrid.DataSource property to the table.
    dataGrid1.DataSource = table;
}

将 DataTable 保存到 DataSet 中所需的 C# 代码:void DataTableToDataSet(DataTable dt)
{
   
// Duplicate the table and add it to a DataSet
   DataSet dsTmp = new DataSet();
   DataTable dtTmp 
= dt.Copy();
   dsTmp.Tables.Add(dtTmp);
  }


将DataView保存到DataSet中:
void DataViewToDataSet(DataView dv)
{
// Clone the structure of the table behind the view
DataTable dtTemp = dv.Table.Clone();
   dtTemp.TableName 
= "Row";  

   
// Populate the table with rows in the view
   foreach(DataRowView drv in dv)
      dtTemp.ImportRow(drv.Row);

DataSet dsTemp 
= new DataSet(dv.Table.TableName);   

   
// Add the new table to a DataSet
   dsTemp.Tables.Add(dtTemp);
}
posted @ 2007-08-18 01:11  小龟爬爬  阅读(513)  评论(0编辑  收藏  举报