通用的.列表:如何设置/获取位置/当前项为DataGridView

本文关键字:位置 获取 DataGridView 设置 列表 何设置 | 更新日期: 2023-09-27 18:07:07

我目前正在开发一个带有自定义数据源处理的datagridview扩展。如果我将一个列表绑定到两个正常的System.Windows.Forms.DataGridView,并在dataGridView1中选择一个项目,dataGridView2也会自动设置该项目的位置。

如果我分配一个BindingSource,我可以处理PositionChanged事件,但一个泛型。列表没有CurrencyManager,那么dataGridView2如何知道新的位置?

通用的.列表:如何设置/获取位置/当前项为DataGridView

你想从列表中获得一些DataGridView(具有作为数据源的列表)的当前位置?那么答案是:你不能。列表不知道所连接的视图所显示的元素(当然)

从DataGridView获取信息的替代方法:订阅DataGridView的SelectionChanged事件,并相应地设置第二个的索引——对于这两个你都应该能够使用currentcell属性

如果不了解DataGridView的一些知识,你就不能做你在下面评论中描述的事情。这是一个不同的设计-你可以实现自己的"ShowableList"或其他东西,并尝试创建自己的DataGridView,从你的ShowableList中显示指定的项目,并在那里设置ShownIndex -但你必须自己做这个

最后我找到了答案:BindingContext!

一个简单的例子:

public class ModifiedCollection : BindingSource {
    BindingSource Source {get;set;}
    BindingManagerBase bmb;
    Control Parent;
    public ModifiedCollection(object Source, Control Parent) {
        if ((this.Source = Source as BindingSource) == null) {
            this.Source = new BindingSource();
            this.Source.DataSource = Source;
        }
        this.Source.ListChanged += new ListChangedEventHandler(Source_ListChanged);

        this.Parent = Parent;
        this.Parent.BindingContextChanged += new EventHandler(Parent_BindingContextChanged);
    }
    void Parent_BindingContextChanged(object sender, EventArgs e) {
        if (bmb != null) {
            bmb.PositionChanged -= bmb_PositionChanged;
        }
        if (Parent.FindForm().BindingContext.Contains(this.Source.DataSource)) {
            bmb = Parent.BindingContext[this.Source.DataSource];
            if (bmb != null) {
                bmb.PositionChanged += new EventHandler(bmb_PositionChanged);
            }
        }
    }
}