【问题标题】:How to set fields in DataRow object如何在 DataRow 对象中设置字段
【发布时间】:2021-04-19 12:53:31
【问题描述】:

我已将旧代码从 vb 迁移到 c#。以下迁移的代码行引发错误:

using System.Data;
..
..
DataRow targetDataRow = targetDataTable.NewRow();
targetDataRow.SetField("DateValue", calendarRow.DateValue.ToShortDateString);

错误:

=Error  CS1061  'DataRow' does not contain a definition for 'SetField' and no accessible extension method 'SetField' accepting a first argument of type 'DataRow' could be found (are you missing a using directive or an assembly reference?)

我知道我可以像这样使用它:

targetDataRow["DateValue"] = calendarRow.DateValue.ToShortDateString);

但是,这是将值设置为 DataRow 对象中的字段的最佳做法吗?

【问题讨论】:

  • targetDataTable 重构为类型化的DataTable 会更好。然后你可以像这样设置字段值:targetDataRow.DateValue = ...。如果您正在迁移 VB 代码,那么同时完成这项工作可能并不是一项很大的额外工作。

标签: c# datatable .net-5 datarow


【解决方案1】:

以下迁移的代码行引发错误:

 Error  CS1061  'DataRow' does not contain a definition for 'SetField' and no accessible extension method 'SetField' accepting a first argument of type 'DataRow' could be found (are you missing a using directive or an assembly reference?)

此错误是因为您尝试使用项目中未引用的DataRowExtension.SetField Method

要添加它,您可以使用 PM 控制台进行添加:

 Install-Package System.Data.DataSetExtensions -Version 4.5.0-preview1-26216-02

这是将值设置为 DataRow 对象中的字段的最佳做法吗

在这种情况下,设置或调用方法都没有关系。在幕后SetField 正在做同样的事情,仅此而已。

【讨论】:

    猜你喜欢
    • 2020-02-27
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多