DataGridView 选中的行上下移动 [英] DataGridView Selected Row Move UP and DOWN

查看:36
本文介绍了DataGridView 选中的行上下移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何允许 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 侧面有两个按钮,是的,UP &向下.任何人都可以帮助我指出正确的方向.如果有帮助的话,我确实有用于 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.

草率、半途而废的例子:

Sloppy, half-working example:

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.

嗯,最后一件事,如果您使用标准列表或集合,这不会那么顺利.列表和集合不会发出 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.

这篇关于DataGridView 选中的行上下移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆