【问题标题】:ADO.NET databinding bug - BindingSource.EndEdit() changes current positionADO.NET 数据绑定错误 - BindingSource.EndEdit() 更改当前位置
【发布时间】:2010-10-15 18:07:33
【问题描述】:

使用BindingSourceDataSetTableAdapter 处理来自数据绑定控件的插入的正确顺序是什么?这让我永远感到困惑。

我有一个用于添加新行的表单。

在显示表格之前,我调用:

bindingSource.AddNew();
bindingSource.MoveLast();

保存后,我调用:

bindingSource.EndEdit();
tableAdapter.Insert([the row given to me as bindingSource.Current]);

问题是

  • 如果不调用EndEdit(),当前焦点的TextBox的变化不会保存
  • 如果我调用 EndEdit(),BindingSource 的 Current 成员将不再指向我刚刚添加的行。

我当然可以使用表单中的值而不是由 BindingSource 更新的 DataTable 调用 Insert(),但这违背了使用数据绑定的目的。我需要做什么才能使其正常工作?

我知道我可以在整个数据集上调用TableAdapter.Update(),因为我使用的是强类型数据集。不过,我在表中有未绑定数据的外键,并且我在调用 Insert() 之前添加了这些外键。

【问题讨论】:

    标签: winforms data-binding dataset bindingsource tableadapter


    【解决方案1】:

    事实证明,这是.NET 框架的“功能”。我之前曾在connect.microsoft.com 上被报道过,但该问题已被关闭为“无法修复”。不过有一个workaround

    我正在使用以下 C# 代码来重置 ListChanged 事件处理程序中的位置:

        [...]
            bindingSource.ListChanged += 
                new ListChangedEventHandler(PreserveCurrentPosition);
        [...]
    
    
        private void PreserveCurrentPosition(object sender, ListChangedEventArgs e)
        {
            if (e.ListChangedType == System.ComponentModel.ListChangedType.ItemAdded &&
                ((BindingSource)sender).Count - e.NewIndex > 1)
            {
                ((BindingSource)sender).Position = e.NewIndex;
            }
        }
    

    【讨论】:

      【解决方案2】:

      您现在可能已经想通了,但是您不需要调用表格适配器的插入方法。只需调用 update 方法,它就会判断是否有新的或更改的记录并采取相应的行动。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-12
        • 1970-01-01
        • 2012-03-23
        • 1970-01-01
        • 2013-12-25
        相关资源
        最近更新 更多