DataGridView中选择行上下移动上下、DataGridView

2023-09-02 10:39:58 作者:谈情不说爱

我怎么能允许一个DataGridView(DGV)选定的行上移或下移。我以前有一个ListView已经这样做了。偏偏,对我来说,更换DGV不是一个选项(诅咒的)。顺便说一句,该DGV数据源是一个泛型集合。

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 option (curses). By the way, the DGV datasource is a Generic Collection.

该DGV对身边的两个按钮,是的,向上和向下。任何人都可以帮助在正确的方向指向我。我确实有code,我用为ListView,如果它会帮助(它并没有帮助我)。

The DGV has two buttons on the side, yes, UP & Down. Can anyone help point me in the right direction. I do have the code that I used for the ListView if it'll help (it did not help me).

推荐答案

如果你编程的方法修改在您的收藏项的顺序,在DGV会自动反映。

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

马虎,半工作的例子:

List<MyObj> 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.

嗯,最后一件事,如果你使用的是标准的列表或集合,这是不会为顺利。清单和收藏on't发出的DGV的数据绑定找到有用的事件。你可以'打嗝'的数据绑定每次更改收集时间,但更好的解决方案将是您使用System.ComponentModel.BindingList。当您更改的BindingList的顺序的DGV会自动反映这个变化。

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.