創建 DataTable

記錄一下 基礎知識

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

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

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

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

None.gif
None.gif將DataView保存到DataSet中:
void DataViewToDataSet(DataView dv)
ExpandedBlockStart.gif
{
InBlock.gif
// Clone the structure of the table behind the view
InBlock.gif
DataTable dtTemp = dv.Table.Clone();
InBlock.gif   dtTemp.TableName 
= "Row";  
InBlock.gif
InBlock.gif   
// Populate the table with rows in the view
InBlock.gif
   foreach(DataRowView drv in dv)
InBlock.gif      dtTemp.ImportRow(drv.Row);
InBlock.gif
InBlock.gifDataSet dsTemp 
= new DataSet(dv.Table.TableName);   
InBlock.gif
InBlock.gif   
// Add the new table to a DataSet
InBlock.gif
   dsTemp.Tables.Add(dtTemp);
ExpandedBlockEnd.gif}
發佈了40 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章