Friday, September 9, 2011

Creating and Using Datatables in VB.net

DataTable is very useful in storing data in table format that can be use to display in DataGridView control or any data bound controls.

DataTable can be search/filtered using LINQ.

Here is how to create a datatable:
Dim dTable As New DataTable("TableName")

Add columns to the datatable
dTable.Columns.Add("Column1", GetType(Integer))
dTable.Columns.Add("Column2", GetType(String))
dTable.Columns.Add("Column3", GetType(Date))
dTable.Columns.Add("Column4", GetType(Double))

Add rows to the datatable
dTable.Rows.Add({1, "Hello", Now.Date, 5.6})
dTable.Rows.Add({2, "World", New Date(2011, 2, 1), Math.PI})

You can also add rows using the following code:
Dim dRow As DataRow
dRow = dTable.NewRow
dRow("Column1") = 3
dRow("Column1") = "Hello World"
dRow("Column1") = Now.Date
dRow("Column1") = 4.6
dTable.Rows.Add(dRow)

To bind the datatable to the DataGridView control:
'Change DataGridView1 to the name of your DataGridView control
DataGridView1.DataSource = dTable

To filter the datable, you can use any of the two codes.
'Filtering using DataTable.Select() method
'This method is very slow if you have a lot of rows.
Dim dResult1() As DataRow = dTable.Select("Column1 = 3")

'Filtering using LINQ.
'This is the recommended approach if you are working on large set of data.
Dim dResult2 = From dItem As DataRow In dTable.AsEnumerable
              Where dItem("Column1") = 3
              Select dItem

To convert DataTable to HTML you can read this article:
Convert DataTable to HTML Table

No comments:

Post a Comment