deleting row a given row index after sorting c#

自闭症网瘾萝莉.ら 提交于 2019-12-13 15:46:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!