简体   繁体   中英

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.

I have a solution for a method that works if there are just strings in the 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).

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() :

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

You probably should check for null values:

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.

在C#6.0中:

return row[columnName]?.ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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