I have a DataTable
that is filled in from an SQL query to a local database, but I don\'t know how to extract data from it.
Main method (in test program):
The simplest way to extract data from a DataTable
when you have multiple data types (not just strings) is to use the Field<T>
extension method available in the System.Data.DataSetExtensions
assembly.
var id = row.Field<int>("ID"); // extract and parse int
var name = row.Field<string>("Name"); // extract string
From MSDN, the Field<T>
method:
Provides strongly-typed access to each of the column values in the DataRow.
This means that when you specify the type it will validate and unbox the object.
For example:
// iterate over the rows of the datatable
foreach (var row in table.AsEnumerable()) // AsEnumerable() returns IEnumerable<DataRow>
{
var id = row.Field<int>("ID"); // int
var name = row.Field<string>("Name"); // string
var orderValue = row.Field<decimal>("OrderValue"); // decimal
var interestRate = row.Field<double>("InterestRate"); // double
var isActive = row.Field<bool>("Active"); // bool
var orderDate = row.Field<DateTime>("OrderDate"); // DateTime
}
It also supports nullable types:
DateTime? date = row.Field<DateTime?>("DateColumn");
This can simplify extracting data from DataTable
as it removes the need to explicitly convert or parse the object into the correct types.