Part 3

Using Dataset

In this article we will see how to use Dataset to retrieve and update the data in a database.

What is a Dataset?

OLEDBDataProvider class

Modifying DataSet

Setting relationship between data tables

What is Dataset?

A dataset represents a mini database in memory. It is a collection of DataTables. Each DataTable contains data retrieved from one or more tables of the database.

The following is the heirarchy of the DataSet.

DataSet
 |-- DataTable
       |--  DataRow
                |-- DataColumn
DataSet contains the data in the form DataTables that is retreived from Database. Then the data in DataTables can be modified and then the changes can be made back to the Database from where the data was retrieved.

An important feature of Dataset is its disconnected nature. It connects to database to retrieve data and once data is retrieved then the connection is closed. So DataSet doesn't keep the connection opened throughout and instead it connects when it is required. You are allowed to make changes to Dataset once the data is loaded into it. It is possible to add rows, delete rows and update rows of data tables of Dataset. When the changes to DataSet are to be updated then it connects to data source and makes changes based on the status of the rows in data tables.

The entire interaction to database is actually handled through OLEDBDataAdapter.

OLEDBDataProvider class

OLEDBDataProvide sits between Database and Dataset. It is responsible for retriving the data from Database and placing in DataSet in the form DataTables. It is also responsible to obtain changes made to data in Dataset and make those changes to Database.

OLEDBDataProvider contains a set of data commands and a connect to the database and uses the connection and command objects to retrieve the data and make changes to the data.

The following code creates a Dataset with one DataTable.


' import required namespaces

Imports system
Imports System.data
Imports system.data.oledb


Module DataSetExample1
    
    Public Sub Main()
        
        Dim con As New OLEDBConnection("provider=Microsoft.jet.oledb.4.0;Data Source=c:\srikanth\phones.mdb")
        Dim da As New OLEDBDataAdapter("select * from cities", con)
        Dim ds As New dataset()

            ' create a datatable with the name CITIES
            da.Fill(ds, "cities")

           'display number of rows in the table
            console.writeline(ds.Tables(0).Rows.Count())
            
           ' load another table into dataset
      
           da.selectcommand = new OLEDBCommand("select * from phones",con)
           da.fill(ds,"phones")

           'display number of rows in the table
            console.writeline(ds.Tables("phones").Rows.Count())
        
    End Sub
    
End Module


The above program first establishes a connection to PHONES.MDB. Then it creates an object of OLEDBDataAdapter class by passing the command to be executed and the connection to be used. Remember the connection is not yet open. The connection will be automatically opened and closed DataAdapter.

Then we used Fill method of the DataAdapter class to retrieve the data from the database and create a DataTable in Dataset with the name CITIES.

Rows collection of DataTable provides access to rows of the table and Count method returns the number of rows in rows collection.

The second DataTable - PHONES is created in a different way. We assigned an OLEDBCommand object to SelectCommand property of DataAdapter and then executed Fill method to create a new DataTable with the name PHONES.

Modifying DataSet

In the previous section we have seen how to retrieve data from data source into DataTable of DataSet. Now, let us see how we can make changes to the data loaded into DataTables and make those changes to Data source.

The following are the important steps related to Dataset.

The following program illustrates how to change the staring digit of phone number to 7 if it is 5.


' import required namespaces

Imports system
Imports System.data
Imports system.data.oledb


Module UpdateSetExample
    
    Public Sub Main()
        
        Dim con As New OLEDBConnection("provider=Microsoft.jet.oledb.4.0;Data Source=c:\srikanth\phones.mdb")
        Dim da as new OLEDBDataAdapter()
        dim ds as new dataset

           ' load another table into dataset
      
           da.selectcommand = new OLEDBCommand("select * from phones",con)
           da.fill(ds,"phones")

          ' update rows 
          dim  r as datarow
          dim phno as string

          for  each  r in  ds.tables(0).rows
               ' change starting digit of phone number from 5 to 7
                phno =  r.item("phoneno") 
                if  phno.substring(0,1) = "5" then
                       phno = "7" & phno.substring(1)
                       ' update current row
                       r.BeginEdit()
                       r.item("Phoneno") = phno
                       r.EndEdit() 

               end if
         next

        '  OLEDBCommandBuilder will automatically create required commands 
        dim  cmdbuilder  as new OLEDBCommandBuilder(da)
        da.update(ds,"phones") 
        Console.writeline("Change is successful")
        
    End Sub
    
End Module


The above program does the following:
Note: The table that is being modified using DataSet must have a primary key defined.

Setting relationship between data tables

It is possible to establish relationship between tables of Dataset. Once relationship is set between two tables based on a column then we can retrieve all child rows of a parent row by using the relation object.

Relationship is set using DataRelation object.

The following example shows how to set relation ship between CITITES and PHONES table using DataRelation object.


' import required namespaces

Imports system
Imports System.data
Imports system.data.oledb


Module RelationExample
    
    Public Sub Main()
        
        Dim con As New OLEDBConnection("provider=Microsoft.jet.oledb.4.0;Data Source=c:\srikanth\phones.mdb")
        Dim da as new OLEDBDataAdapter()
        dim ds as new dataset

           ' load data into tables from data source
      
           da.selectcommand = new OLEDBCommand("select * from cities",con)
           da.fill(ds,"cities")

           da.selectcommand = new OLEDBCommand("select * from phones",con)
           da.fill(ds,"phones")


          Dim pcol As DataColumn
          Dim ccol As DataColumn

         pcol = ds.Tables("cities").columns("citycode")
         ccol = ds.Tables("phones").Columns("citycode")

        ' Create DataRelation.
         Dim rel As DataRelation
         rel = New DataRelation("CityPhones", pcol, ccol) 

        ' Add the relation to the DataSet.
         ds.Relations.Add(rel) 

         ' use relation object to retrieve child rows for each parent row
         dim parentrow,childrow as datarow
   
         for each  parentrow in  ds.tables(0).rows
               Console.writeline("City : " &  parentrow("cityname") )
                for each childrow  in  parentrow.getchildrows("cityphones") 
                         Console.writeline( childrow.item("person") & " - " &  childrow.item("phoneno"))
                 next
        next

    
    End Sub
    
End Module

DataRelation object is used to establish relationship between two tables of DataSet. The above example we created two data tables - Cities and Phones in Dataset. Then we created a DataRelation object to establish relationship between tables Cities and Phones based on common column CityCode.

The method GetChildRows takes the name of the data relation object and return all child rows of the given parent row.

The program take one parent row at a time using For Each loop. And then it takes all child rows of each parent row using the relation object.

In this article I have concentrated on major features of DataSet. However, there are some other applications of Dataset. For example, datasets are very widely used to display data using server side controls in ASP.NET and even in windows based controls.

For more information about DataSet, DataAdapter and other related object, please go through documentation as it contains several examples and details of each property and method.

P.Srikanth

I request you to tell me how you found this article. Please click here to send your feedback. Your feedback is very valuable and enables me to serve you better.