【问题标题】:How to read column value generically from a datatable in .NET without explicitly specifying the data type and column name如何从 .NET 中的数据表中读取列值而不显式指定数据类型和列名
【发布时间】:2011-08-04 04:36:20
【问题描述】:

我想在不明确指定数据类型和列名的情况下从数据表中读取列值。

例如

int carId = CarTable.Rows[i].Field<int>("CarId");  //this requires the data type and column name.

string name= CarTable.Rows[i].Field<string>("Name"); 

我想在不明确指定数据类型和列名的情况下读取 carId。

如果我希望所有列的返回类型都是字符串类型会更容易吗?

【问题讨论】:

    标签: generics types datatable


    【解决方案1】:

    假设您正在考虑使用列的位置而不是其名称,您应该可以这样做:

    Object colvalue = CarTable.Rows[i].Items[colpos];
    

    【讨论】:

    • 谢谢,这适用于字符串和其他数据类型吗?如何从对象类型中获取价值?
    • 有没有办法检测数据类型并将其分配给其类型的变量?
    • 是的,您需要枚举 CarTable.Columns 集合,该集合将为您提供每列的数据类型信息。所以 CarTable.Columns[colpos] 将为您提供计算 CarTable.Rows[i].Items[colpos] 数据类型所需的信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 2013-12-10
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多