【问题标题】:Generic.List: How to set/get position/currentitem for DataGridView?Generic.List:如何设置/获取 DataGridView 的位置/当前项?
【发布时间】:2011-08-30 12:39:45
【问题描述】:

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

如果我分配一个 BindingSource 我可以处理 PositionChanged 事件,但 Generic.List 没有 CurrencyManager,那么 dataGridView2 如何知道新位置?

【问题讨论】:

  • CurrencyManager 在这一切中的作用是什么?
  • @Tigran,see MSDN。它与货币货币无关;)
  • @Thomas Levesque:好点 :)

标签: c# winforms list bindingsource


【解决方案1】:

您想从 List 中获取某些 DataGridView(将 as 列表作为 DataSource)的当前位置吗? 那么答案是:你不能。该列表对连接视图一无所知 - 包括显示的元素(当然)

从 DataGridView 获取信息的替代方法: 订阅 DataGridView 的 SelectionChanged 事件并相应地设置第二个事件的索引 - 你应该能够使用 CurrentCell-property

在不了解 DataGridView 的情况下,您无法执行以下 cmets 中所述的操作。 这是一个不同的设计 - 您可以实现自己的“ShowableList”或其他东西,并尝试创建自己的 DataGridView 来显示 ShowableList 中的指示项目并在那里设置 ShownIndex - 但您必须自己做。

【讨论】:

  • 我不相信标准的datagridview会这样做。这背后一定有什么诡计。使用您的解决方案,我必须监听所有容器控件 Control.Added 事件并监听所有 datagridviews SelectionChanged 和 DataSourceChanged 事件。一定有别的办法。
  • 如果我收到您的问题,您想将两个数据网格视图绑定在一起 - 标准视图根本不会这样。而且您的 List 肯定不知道显示了什么元素,因此如果您想将它与一般 List(或集合)一起使用,则必须使用 datagridviews-abilities。也许我错了,或者我没有让你的问题正确,所以请解释一下。
  • 我只用datagridview做了一个例子。另一个例子是:将 listX 分配给 dataGridView1 和 textbox1。如果我在 dataGridView1 中选择另一个项目,则文本框也会跳转到所选项目。它不仅在datagridview之间,而且在具有列表作为数据源的所有组件之间。必须有任何方法可以获取类列表的当前项。
【解决方案2】:

我终于找到了答案: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);
            }
        }
    }
}

【讨论】:

  • 但是现在你绑定到这个源而不是列表是吗? - 但我告诉你什么:很高兴你找到它 - 给你一个赞成票,你可以关闭它;)
  • 不,我仍在绑定列表。上半部分只知道它是否已经是一个绑定源。示例: var m = new ModifiedCollection(list1 /*Generic List*/, this /*Datagridview 或 Form 或任何其他组件*/);
猜你喜欢
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
  • 2011-07-15
  • 2017-04-01
  • 1970-01-01
相关资源
最近更新 更多