2

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

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

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

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

保存后,我调用:

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

问题是

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

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

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

4

2 回答 2

3

事实证明,这是.NET框架的“功能”。我之前曾在connect.microsoft.com上报告过,但该问题因“无法修复”而关闭。不过,有一个解决方法

我正在使用以下 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;
        }
    }
于 2009-03-26T18:38:53.017 回答
-1

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

于 2010-05-21T15:11:20.977 回答