【问题标题】:C# ResetBinding flip the DataGridView *Updated with example* [closed]C# ResetBinding 翻转 DataGridView *用示例更新* [关闭]
【发布时间】:2008-09-29 18:17:54
【问题描述】:

我有一个已部分解决的problem。快速解释一下:我有一个绑定到需要序列化的复杂对象的网格。从序列化中构建对象时,网格上的事件不会刷新表格显示。有人告诉我在反序列化后重建事件,它可以工作!但是刷新网格的事件似乎根本没有触发。

我必须从我的复杂对象构建一个事件,告诉我内部发生了变化。从这个事件中,我添加了这段代码:

this.bindingSource1.ResetBindings(false);

问题是网格在翻转,用户感觉不好(行上下移动,然后停止)。

如何在不发生这种翻转的情况下重置绑定? 我该如何解决original problem? (这将自动解决所有问题)。

更新

这是一个执行完全相同行为的示例:

创建一个类:

[Serializable()]
class BOClient : INotifyPropertyChanged, IDataErrorInfo
{
    private string name;
    private int len;
    public string Name
    {
        get { return name; }
        set { name = value;
        this.len = name.Length;
        if (this.PropertyChanged !=null)
            this.PropertyChanged(this, new PropertyChangedEventArgs("Name"));
        }
    }

    public int Len
    {
        get { return this.len; }
    }

    public BOClient(string name)
    {
        this.Name = name;
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    #region IDataErrorInfo Members

    public string Error
    {
        get { return ""; }
    }

    public string this[string columnName]
    {
        get { return ""; }
    }

    #endregion
}

现在,使用 BindingSource 调用“bindingSource1”创建一个表单,并使用该类作为数据源。创建一个网格并将该网格绑定到 bindingsource1。

在该表单中,在加载中使用此代码:

 private void Form1_Load(object sender, EventArgs e)
    {
        BindingList<BOClient> listClient = new BindingList<BOClient>();
        listClient.Add(new BOClient("P1"));
        listClient.Add(new BOClient("P2"));
        listClient.Add(new BOClient("P3"));

        //using (MemoryStream mem = new MemoryStream())
        //{
        //    BinaryFormatter b1 = new BinaryFormatter();

        //    try
        //    {
        //        b1.Serialize(mem, listClient);
        //    }
        //    catch (Exception ez)
        //    {
        //        MessageBox.Show(ez.Message);
        //    }




        //    BinaryFormatter b2 = new BinaryFormatter();

        //    try
        //    {
        //        mem.Position = 0;
        //        listClient = (BindingList<BOClient>)b2.Deserialize(mem);
        //    }
        //    catch (Exception ez)
        //    {
        //        MessageBox.Show(ez.Message);
        //    }

        //}


        this.bindingSource1.DataSource = listClient;
    }

我将序列化过程放在注释中,因为如果没有它,它似乎会出现同样奇怪的行为......现在启动应用程序。更改客户的名称。 “新名称”的示例“p1”,然后单击更改后的单元格下的单元格。您将看到“len”列没有改变。但是,如果您单击具有 len 的单元格,您会看到数字变为正确的值。

有人知道为什么吗?

【问题讨论】:

    标签: c# data-binding serialization datagridview


    【解决方案1】:

    我通过在 BindingList(通过继承)中添加一个方法 [OnDeserialization] 解决了这个问题,我在 OnListChange 上添加了添加事件的代码。这样当 1 个属性发生变化时,整行都会刷新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 2010-10-30
      • 2023-03-06
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多