Understanding DataSet, DataTable, DataRow and DataColumn in VB.NET


VB.NET allows the users to use a very convenient way to store data that is, to store into virtual tables. I will briefly explains how all these objects (dataset, datatable, datarow, datacolumn) interconnects. A virtual table is also known as a datatable, which is stored into a dataset. So, it can be said that a dataset is a collection of datatables. In other words, a dataset can hold many datatables. So what makes up a datatable? Well, a datatable is make up of many datarows, which of course depends on how many records a datatable might have. Datacolumn then, represents the columns of a datarow.

Below is a simple example to show you how to program with these objects and to show you how they worked. It is a simple code to store the number of hours an employee is doing overtime and how much the employee is paid for the duration. Assuming the hourly rate is set to 20 dollars per hour.



Public Sub OverTime(ByVal No_Of_Hours As Integer)

'declare dataset
Dim ds As New DataSet

'declare datatable as dt
Dim dt As New DataTable("dt")

'declare datarow
Dim dr As DataRow

'declare the datacolumns
Dim dct1 As New DataColumn("dcHour")
Dim dct2 As New DataColumn("dcTime")

'hourly rate of overtime pay
Dim HourlyRate As Double = 20


'declare the datatype of the datacolumns
dct1.DataType = GetType(Integer)
dct2.DataType = GetType(Double)

'add the datacolumn, column1 and column2 into the datatable
dt.Columns.Add(dct1)
dt.Columns.Add(dct2)

'create a new row for the datatable
dr = ds.Tables("dt").NewRow

'insert the data into the datarows (column1 and column2)
dr("drHour") = No_Of_Hours
dr("drAmount") = No_Of_Hours * HourlyRate

'add newly created row into the datatable
ds.Tables("dt").Rows.Add(dr)

'add the datatable into the dataset
ds.Tables.Add(dt)

End Sub



And, now we have successfully inserted the data (number of hours & overtime pay amount) into the datatable in the dataset.


Back to VB Egg

0 comments