简体   繁体   English

C#-从数据表以字符串形式返回单个值(任何数据类型)

[英]C# - Returning a single value (any datatype) from a DataTable as a string

I've loaded a table from excel in C# using the ExcelDataReader package, however I'm struggling to write a method which returns the value of a cell as a string, based on the row number and column name. 我已经使用ExcelDataReader包从C#中的excel中加载了一张表格,但是我正在努力编写一种基于行号和列名将单元格的值作为字符串返回的方法。

I have a solution for a method that works if there are just strings in the DataTable... 我有一种方法的解决方案,该方法可以在DataTable中只有字符串的情况下使用...

public string ReadData(int rowNum, string columnName)
{
    DataRow row = table.Rows[rowNum];
    string value = row.Field<string>(columnName);
    return value;
}

(the DataTable variable 'table' is loaded elsewhere) ..however I would like also like to be able to return numbers and dates (as strings). (DataTable变量“表”已加载到其他位置)..但是我也希望能够返回数字和日期(作为字符串)。

I feel I might need to edit this part somehow... 我觉得我可能需要以某种方式编辑此部分...

string value = row.Field<string>(columnName);

But I don't know how to make it so it pulls back whatever value and type is in that field and returns a string. 但是我不知道怎么做,所以它会拉回该字段中的任何值和类型并返回一个字符串。

Many thanks! 非常感谢!

您可以使用DataRow name-indexer返回一个object在该object上我们可以调用.ToString()将其转换为string

return row[columnname].ToString();

You can simply use the by-name-indexer and call ToString() : 您可以简单地使用by-name-indexer并调用ToString()

string value = row[columnName].ToString();

You probably should check for null values: 您可能应该检查null值:

string value = (row[columnName] ?? string.Empty).ToString();

Use 采用

string value = Convert.ToString(row[columnName]);

Using Convert.ToString() is preferrable because it does not only check for null but also for DBNull , which is the value of the column when accessing a real database where the column has no content. 最好使用Convert.ToString() ,因为它不仅会检查null而且还会检查DBNullDBNull是在访问不包含任何列的真实数据库时的列值。

在C#6.0中:

return row[columnName]?.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM