一個DataTable賦值給另一個DataTable的常用方法

來源:互聯網
上載者:User
DataView view = new DataView();
view.Table = DataTableA;
view.RowFilter = "itemType = 'book'";//itemType是DataTableA中的一個欄位
DataTableB= view.ToTable();
或者:
DataRow[] rows = DataTableA.Select("itemType = 'book'");
DataTableB= DataTableA.Clone();
foreach (DataRow row in rows)
{
     DataTableB.ImportRow(row);
}

或者

/// 執行DataTable中的查詢返回新的DataTable
/// </summary>
/// <param name="dt">來源資料DataTable</param>
/// <param name="condition">查詢條件</param>
/// <returns></returns>
private DataTable GetNewDataTable(DataTable dt, string condition,string sortstr)
{
      DataTable newdt = new DataTable();
      newdt = dt.Clone();
      DataRow[] dr = dt.Select(condition,sortstr);
      for (int i = 0; i < dr.Length; i++)
      {
          newdt.ImportRow((DataRow)dr[i]);
      }
      return newdt;//返回的查詢結果

}

 

 

或者 逐列的形式

public static int TableDataExchange(DataSet ds, string tableName, DataTable sourceDT)
        {
             for(int i=0;i<sourceDT.Rows.Count;i++)
             {
                 DataRow drNew = ds.Tables[tableName].NewRow();
                 foreach (DataColumn dc in sourceDT.Columns)
                 {
                     drNew[dc.ColumnName] = sourceDT.Rows[i][dc.ColumnName];
                 }
                 ds.Tables[tableName].Rows.Add(drNew);
             }
             ds.Tables[tableName].AcceptChanges();
             DataTable dt = ds.Tables[tableName];
             return ds.Tables[tableName].Rows.Count;
            
        }

 

 

或者

 

DataSet 對象是支援 ADO.NET的斷開式、分布式資料方案的核心對象 ,用途非常廣泛.我們很多時候需要使用其中的資料,比如取得一個DataTable的資料或者複製另一個DataTabe中的資料或者是DataRow的資料,但是只有DataSet和DataTable的複製是支援深層複製的,就是說不僅能複製元素的結構,而且能複製元素的資料,而DatatDataRow沒有相關的複製的方法,下面將簡單介紹下這些資料元素的複製問題。

DataTable sourceTable;
DataTable objectTable;
DatatDataRow sourceRow;
DatatDataRow objectRow;
DataRow tempRow;
DataSet souceDataSet = new DataSet();

複製DataSet

  DataSet object = souceDataSet.Copy();//深複製
  DataSet object = souceDataSet.Clone();//淺複製,只複製架構

複製DataTable

  objectTable  = sourceTable .Copy();//深複製
  objectTable  = sourceTable .Clone();//淺複製,只複製架構

複製DataRow

    項目開發中經常遇到這種錯誤-“此行已屬於另一個表” 。導致這個錯誤的語句如下:

 

     objectTable .Rows.Add(SourceDataRow);
 

      分析了一下原因,因為DataRow DataTable 都是傳引用調用的。所以一個行在一個表中了,就不能再增加到另外一個表。

 

具體方法:

 

1  ImportRow方法:public void ImportRow( DataRow DataRow);

objectTable = sourceTable.clone();//必須先複製表的架構,使具有相同的的列或關係!
foreach (DataRow oRow in sourceTable)
{ 

       objectTable.ImportRow(oRow);//在objectTable中添加一個新行,並將sourceRow的值複製進去,要求表的結構一樣!

}

_____________________________________________________________________________________________________

2. 迴圈DataTable的每個列

DataRow aDataRow = objectTable.NewRow();

    foreach(DataColumn aDataColumn in sourceTable.Columns)

    {

        aDataRow [aDataColumn.ColumnName] = sourceTable[i][aDataColumn.ColumnName];

    }

    objectTable.Rows.Add(aDataRow);

3. 自訂複製

objectTable.Columns.Add ("id");//不需要有一樣的架構,只複製自己需要的列! 
Object [] myArry = new Object [1]; 
   foreach (DataRow oRow in sourceTable)
{ 

  tempRow = objectTable.NewRow();//此方法必須調用!
  myArry[0] = oRow["id"];//如果myArry中沒有源表中的id列的話就會報錯!
  tempRow.ItemArray = myArry;//ItemArray屬性為Object類型數組,根據程式的需要需要可自行複製多個列的資料!
  objectTable.Rows.Add(tempRow); //此方法必須調用,否則DataRow中的資料將不能顯示!

}
_____________________________________________________________________________________________________

4. LoadDataRow方法:public DataRow LoadDataRow(Object[] values,bool fAcceptChanges);

    Object[] newRow = new Object[3];
   // 設定對象數組的值
    newRow[0] = "Hello";
    newRow[1] = "World";
    newRow[2] = "two";
    DataRow myRow;
    ObjectTable.BeginLoadData();
    // 將新行添加到表中
    myRow = ObjectTable.LoadDataRow(newRow, true);//標誌要設定為true,表示添加新行
    ObjectTable.EndLoadData();

該方法比較複雜,如果只是簡單的複製現有行的資料來添加新行的話建議不要採用,具體用法請參看sdk文擋。

 

 

或者:

< type="text/JavaScript"> alimama_pid="mm_10249644_1605763_4929893"; alimama_titlecolor="0000FF"; alimama_descolor ="000000"; alimama_bgcolor="FFFFFF"; alimama_bordercolor="E6E6E6"; alimama_linkcolor="008000"; alimama_bottomcolor="FFFFFF"; alimama_anglesize="0"; alimama_bgpic="0"; alimama_icon="0"; alimama_sizecode="16"; alimama_width=658; alimama_height=60; alimama_type=2; < src="http://a.alimama.cn/inf.js" type=text/javascript>

我們經常需要向DataTable中添加一行資料,大多數的情況下都是把一些從UI的控制項和程式的變數中收集的資料添加到DataTable中。如以下的語句把供應商代碼和名稱添加到DataTable中:

DataTable dtProvider = new DataTable();
            DataRow drRow = dtProvider.NewRow();
            drRow[0] = txtProviderCode.Text.Trim();
            drRow[1] = txtProviderName.Text.Trim();
            dtProvider.Rows.Add(drRow);

 

大多數的情況下這幾行語句是完全可以滿足要求的。但是如果想把另一個同樣結構的DataTable的某一行添加到這個dtProvider中,就不能簡單的添加了。否則會提示一個錯誤“This row belongs to another table.”。這個時候我們必須定義另一個DataRow,把源DataRow的資料賦到目的DataRow中,再Add進DataTable中就可以了。如下所示:

DataTable dtProvider = new DataTable();
            DataRow drTarget = dtProvider.NewRow();
            drTarget.ItemArry = drSource.ItemArry;
            // 注意:這裡的drSource是另一個相同結構的DataTable中的一行。
            dtProvider.Rows.Add(drTarget);
            < type="text/JavaScript"> alimama_pid="mm_10249644_1605763_5027492"; alimama_type="f"; alimama_sizecode ="tl_1x5_8"; alimama_fontsize=12; alimama_bordercolor="FFFFFF"; alimama_bgcolor="FFFFFF"; alimama_titlecolor="0000FF"; alimama_underline=0; alimama_height=22; alimama_width=0; < src="http://a.alimama.cn/inf.js" type=text/javascript>

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.