2013-05-16 53 views
1

是否可以使用c#在現有數據集的中間添加一行?我做了很多搜索,並且一直沒有找到關於如何做到這一點的任何事情。我試過了什麼?我嘗試了很多搜索,並沒有發現像數據集的'insertAt'方法。 感謝 邁克我可以使用c#向數據集的中間添加一行嗎?

+0

定義_middle_。可能你在DataSet中引用了一個'DataTable'。 –

+0

是dataset.Tables [0]一個DataTable?我可能會感到困惑。 – dmikester1

+0

即便如此,爲「DataTable」定義了「中間」。 –

回答

3

DataSet由DataTable對象的集合組成,因此我假定您正在討論Datatable,對嗎?如果是這樣,它有一個InsertAt方法:

DataTable dt = dataset.Tables[0]; //Get first datatable from dataset 
DataRow row = dt.NewRow(); 
//fill row 
dt.Rows.InsertAt(row,3); //Insert at index 3 
+0

這是正確的,我只是標記mallan的答案,因爲他回答第一個 – dmikester1

+0

@ dmikester1他沒有,但沒關係;) – nmat

+0

你是對的,我讀了錯誤的時間,對不起 – dmikester1

0

在我看來(雖然這可能需要花費大量的時間),你可以創建一個數組或數組列表然後從你的數據集,通過對循環或循環轉移存在的所有數據...那麼把一個好像裏面的語句來檢查,你想要把你額外的數據是這樣的:

List<string> arrayList = dataset;// i know this is not possible just showing you that you have to put all your data from dataset to array:) 
List <string> newList = new List<string>();//its up to you if you want to put another temporary array or you could simply output your data from the loop. 
//THE LOOP 
for(int i = 0; i<=arrayList.Count(); i++){ 
    if(i == x)//x is the index or you may change this statement its up to you 
    { 
    //do the print or pass the data to newList 
     newList.add(arraList[i]);//not sure about this. its been a while since the last time i use this array list.. 
    } 
} 

另一種方式是自定義查詢(如果你從數據庫中提取出來的一些數據)

編碼快樂:)

1

DataSet中沒有一個行集合,所以你不能將行添加到它。

您可以使用DataTable.Rows.InsertAt(row, i)通過索引將一行插入到DataTable對象中。如果表是在DataSet,你的語法爲DataSet.Tables[i].Rows.InsertAt(row, 0)

+0

正是我在找什麼爲,謝謝。 – dmikester1

0

這裏做的一個簡短的樣本:

class Program 
{ 
    static void Main(string[] args) 
    { 
     DataSet ds = new DataSet(); 

     DataTable dt = ds.Tables.Add("Table"); 
     dt.Columns.Add("Id"); 
     for (int i = 0; i < 10; i++) 
     { 
      dt.Rows.Add(new object[]{i}); 
     } 

     var newRow=dt.NewRow(); 
     newRow.ItemArray=new string[]{(dt.Rows.Count/2).ToString()+".middle"}; 
     dt.Rows.InsertAt(newRow, dt.Rows.Count/2); 
    } 
} 
相關問題