The easiest way to extract data from a DataTable when you have several types of data (not just rows) 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 , Field<T> Method:
Provides strongly typed access to each of the column values ββin the DataRow.
This means that when specifying the type, it will check and unpack 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 the extraction of data from the DataTable , since it eliminates the need to explicitly convert or parse the object into the correct types.
haldo Jan 24 '19 at 23:37 2019-01-24 23:37
source share