2

这是我的问题:我有一个绑定到自定义对象的 BindingList 的 DataGridView。后台线程不断更新这些对象的值。udpates 显示正确,一切都很好,除了一件事 - 如果您在更新背景更新字段时尝试编辑不同的字段,它会丢失输入的值。这是一个演示此行为的代码示例:(对于新表单,请在其上放置一个新的 DataGridView:)

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        private BindingList<foo> flist;
        private Thread thrd;
        private BindingSource b;
        public Form1()
        {
            InitializeComponent();
            flist = new  BindingList<foo>
                    {
                        new foo(){a =1,b = 1, c=1}, 
                        new foo(){a =1,b = 1, c=1}, 
                        new foo(){a =1,b = 1, c=1}, 
                        new foo(){a =1,b = 1, c=1}
                    };
            b = new BindingSource();
            b.DataSource = flist;
            dataGridView1.DataSource = b;
            thrd = new Thread(new ThreadStart(updPRoc));
            thrd.Start();

        }

        private void upd()
        {
            flist.ToList().ForEach(f=>f.c++);
        }  

        private void updPRoc()
        {
            while (true)
            {
                this.BeginInvoke(new MethodInvoker(upd));
                Thread.Sleep(1000);
            }
        }
    }


    public class foo:INotifyPropertyChanged
    {
       private int _c;
       public  int a { get; set; }
       public int b { get; set; }
       public int c 
       { 
           get {return _c;}
           set
           {
               _c = value;
               if (PropertyChanged!= null)
                   PropertyChanged(this,new PropertyChangedEventArgs("c"));
           }
       }

       #region INotifyPropertyChanged Members

       public event PropertyChangedEventHandler PropertyChanged;

       #endregion
    }
}

因此,您编辑列 a 或 b,您将看到列 c 更新导致您丢失条目。

任何想法表示赞赏。

4

2 回答 2

0

在将 datagridview 的 assign currentCell 属性保存为空之前,它会从正在编辑的单元格中失去焦点

于 2009-11-19T02:48:34.010 回答
0

我玩过你的代码。似乎正在发生的事情是,只要您添加了一个新行,就会BindingList通过“DataGridView 的添加行功能”自动将一个新的“foo”对象添加到该对象中。由于它与集合中的对象一样有效,因此它的“c”参数将由您实现的线程函数递增,并且您的输入更改将丢失,因为 PropertyChangedEvent 触发将导致“DataGridView”刷新。

我的建议是有一个不同的视图或表单,您可以在其中输入新对象的信息。然后在 OK 处,将新的 foo 对象添加到列表中。这违背了直接从 DataGridView 添加行的目的,如果您愿意,可以与我争论,但您可以在其他地方进行所有验证。您想为 UI 代码中的所有验证和正确性检查编写代码吗?您是否希望用户处理“您需要一个号码而不是那里的文字!” DataGridView 的其余部分正在更新时的消息?可能有点令人沮丧。

此外,如果数据要不断变化,那么从网格视图中对其进行编辑几乎没有意义。您希望数据源的连接方法范式在其中一些不断变化。您可能需要重新考虑如何显示此信息,并可能让用户查看数据并以不同的方式对其进行编辑。

反正我的5美分。

祝你好运,看到数字变得疯狂很有趣,我理解你的问题。

里奥·布鲁扎尼蒂

于 2009-08-04T12:15:31.187 回答