deleting row a given row index after sorting c#

2019-07-13 01:33发布

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); ?

2条回答
ら.Afraid
2楼-- · 2019-07-13 02:17

remove at binding source, not at dataset

查看更多
Explosion°爆炸
3楼-- · 2019-07-13 02:26

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
查看更多
登录 后发表回答