2012-02-17 67 views
2

後給定的行索引我建立我與bindnig源數據網格:刪除行排序C#

SqlDataAdapter adapter = new SqlDataAdapter(Datenbank.cmd); 
    dataSet1.Tables.Clear(); 
    adapter.Fill(dataSet1, "Table"); 
    bs = new BindingSource(); 
    bs.DataSource = dataSet1.Tables["Table"]; 
    dataGridView1.DataSource = bs; 

現在我有點電網

bs.Sort = "customer DESC"; 

現在我想刪除行0

dataSet1.Tables[0].Rows.RemoveAt(0); 

然而,這是在位置0分選前的行會被刪除,而不是排它現在是在位置0

//編輯:是否有類似的test.Tables[0].Rows.InsertAt(newRow, 0);

+1

與綁定源排序證明這一點,不排序的原始數據表它將它的一個副本分類。你最好使用數據鍵而不是行索引來刪除。 – 2012-02-17 20:59:30

+0

@BrianDriscoll您能否詳細解釋如何使用數據鍵而不是行索引? – 2012-02-17 21:03:40

回答

2

爲什麼不使用綁定源 例如只是將其刪除

bs.RemoveAt(0) 

關於test.Tables[0].Rows.InsertAt(newRow, 0);

BindingSource.Insert(int, object)或​​看起來不錯,但在源是一個DataSet,不支持。

這是因爲BindingSource.Insert只是調用底層列表上的System.Collections.IList.Insert()。底層列表是一個DataView。插入對數據視圖的實現是

private void System.Collections.IList.Insert(int index, object value) 
{ 
    throw ExceptionBuilder.InsertExternalObject(); 
} 

您可以通過

System.Data.DataView dv = bs.List as DataView; 
System.Collections.IList list = dv; 
list.Insert(0,newRow); //BANG InsertExternalObject exception 
+0

是否有類似的'test.Tables [0] .Rows.InsertAt(newRow,0);'? – 2012-02-17 21:31:21

+0

[BindingSouce.Insert](http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.insert.aspx)接受一個整數和一個對象,以便肯定的,但是我沒有測試 – 2012-02-17 21:34:55

+0

它說外部對象不能添加到這個列表 – 2012-02-17 21:40:11

2

刪除在綁定源不在數據集