【问题标题】:How to ensure all changes in every controls applied to the DataSet before the data save to the database?在数据保存到数据库之前,如何确保应用于 DataSet 的每个控件的所有更改?
【发布时间】:2009-07-19 02:13:30
【问题描述】:

当我使用 Delphi 进行开发时,我总是调用 DataSet.CheckBrowseMode() 以允许绑定控件将其挂起的更改应用到 DataSet。我一直在.NET中寻找类似的方式

我试过了

// When the user press Ctrl-S 
// Apply any pending edit
this.TheDataBindingSource.CurrencyManager.EndCurrentEdit();
// then save the data
this.SaveData();

与 Delphi DataSet.CheckBrowseMode() 不同,此代码在 TextBox 内有未决更改时不起作用。在按 Ctrl-S 保存数据之前,我的用户必须通过 将焦点从文本框移开。

【问题讨论】:

标签: .net winforms data-binding


【解决方案1】:

根据MSDN,如果你验证表单,它会导致所有控件将它们当前的数据推回数据源。

// When the user press Ctrl-S 
// Apply any pending edit
this.Validate();  // assuming this is the Form...
// set the DataSource of the BindingSource to null,
// otherwise, the BindingSource immediately calls
// BeginEdit() automatically
this.TheDataBindingSource.DataSource = null;
this.TheDataBindingSource.EndEdit();
// then save the data
this.SaveData();

【讨论】:

    【解决方案2】:
    this.BindingContext[dataTableVariableHere].EndCurrentEdit();
    

    或者如果您使用 BindingSource 将数据绑定到您的控件:

    foreach(Component c in this.components.Components)
        if(c is BindingSource)
            (c as BindingSource).EndEdit();
    

    【讨论】:

    • 调用 EndEdit 将使 DataRowView(或其他 IEditableObjecT)将行推送到数据存储。但是,有时数据在控件本身上处于未决状态。在 BindingSource.EndEdit 之前调用 Form.Validate 是完美的解决方案。
    猜你喜欢
    • 2011-10-26
    • 2014-07-08
    • 2017-04-13
    • 2011-06-11
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    相关资源
    最近更新 更多