DataGridView Selected Row Move UP and DOWN

后端 未结 13 1485
盖世英雄少女心
盖世英雄少女心 2020-12-06 01:31

How can I allow selected rows in a DataGridView (DGV) to be moved up or down. I have done this before with a ListView. Unfortunetly, for me, replacing the DGV is not an opt

13条回答
  •  一整个雨季
    2020-12-06 02:19

    If you programatically change the ordering of the items in your collection, the DGV should reflect that automatically.

    Sloppy, half-working example:

    List foo = DGV.DataSource;
    int idx = DGV.SelectedRows[0].Index;
    int value = foo[idx];
    foo.Remove(value);
    foo.InsertAt(idx+1, value)
    

    Some of that logic may be wrong, and this may not be the most efficient approach either. Also, it doesn't take into account multiple row selections.

    Hmm, one last thing, if you're using a standard List or Collection this isn't going to go as smoothly. List and Collection on't emit events that the DGV finds useful for databinding. You could 'burp' the databinding every time you change the collection, but a better solution would be for you to use a System.ComponentModel.BindingList. When you change the ordering of the BindingList the DGV should reflect the change automatically.

提交回复
热议问题