问题
I build up my datagrid with bindnig source:
SqlDataAdapter adapter = new SqlDataAdapter(Datenbank.cmd);
dataSet1.Tables.Clear();
adapter.Fill(dataSet1, "Table");
bs = new BindingSource();
bs.DataSource = dataSet1.Tables["Table"];
dataGridView1.DataSource = bs;
Now I sort grid
bs.Sort = "customer DESC";
Now I want to remove row 0
dataSet1.Tables[0].Rows.RemoveAt(0);
However, the row which was at position 0 before sorting will be deleted, not the row which now is on position 0
//EDIT : is there similar for test.Tables[0].Rows.InsertAt(newRow, 0);
?
回答1:
why not just remove it using the binding source e.g.
bs.RemoveAt(0)
Regarding test.Tables[0].Rows.InsertAt(newRow, 0);
BindingSource.Insert(int, object)
or BindingSource.List.Insert(int, object)
looks good but it isn't supported when the source is a DataSet.
This is because BindingSource.Insert just calls the System.Collections.IList.Insert()
on the underlying list. The underlying list is a DataView. The implementation of Insert on Dataview is
private void System.Collections.IList.Insert(int index, object value)
{
throw ExceptionBuilder.InsertExternalObject();
}
You can show this by
System.Data.DataView dv = bs.List as DataView;
System.Collections.IList list = dv;
list.Insert(0,newRow); //BANG InsertExternalObject exception
回答2:
remove at binding source, not at dataset
来源:https://stackoverflow.com/questions/9335282/deleting-row-a-given-row-index-after-sorting-c-sharp