DataRow
FieldDataRow
in VB.NET has a Field Function. This provides support for getting a field with no casting required. The field value is returned in the object type specified.
Field is a generic Function—we use it with special syntax. We must specify a type parameter like (Of String
) in the function call.
This program first creates a DataTable
. The table has 4 columns (Weight, Name, Code and Date
). With For Each
, we loop over the rows in the table.
Field()
extension four times. In this way we get typed fields from the row.string
argument ("Name", "Date
").Module Module1 Sub Main() ' Create new table. Dim table As DataTable = New DataTable table.Columns.Add("Weight", GetType(Integer)) table.Columns.Add("Name", GetType(String)) table.Columns.Add("Code", GetType(String)) table.Columns.Add("Date", GetType(DateTime)) table.Rows.Add(57, "Koko", "A", DateTime.Now) table.Rows.Add(130, "Fido", "B", DateTime.Now) table.Rows.Add(92, "Alex", "C", DateTime.Now) table.Rows.Add(25, "Charles", "D", DateTime.Now) table.Rows.Add(7, "Candy", "E", DateTime.Now) ' Loop over rows. For Each row As DataRow In table.Rows ' Get fields. Dim weight As Integer = row.Field(Of Integer)(0) Dim name As String = row.Field(Of String)("Name") Dim code As String = row.Field(Of String)(2) Dim date1 As DateTime = row.Field(Of DateTime)("Date") ' Display fields. Console.WriteLine("{0} {1} {2} {3}", weight, name, code, date1) Next End Sub End Module57 Koko A 6/10/2013 5:00:47 PM 130 Fido B 6/10/2013 5:00:47 PM 92 Alex C 6/10/2013 5:00:47 PM 25 Charles D 6/10/2013 5:00:47 PM 7 Candy E 6/10/2013 5:00:47 PM
Casting often leads to problems because of its confusing syntax and the extra steps needed. With Field, objects are returned strongly-typed—no casting is needed.
With DataRow
, cells can be retried with the Items array. But the Field generic Function can also be used. It can lead to clearer code when using DataTable
.