ObjectDataSource in ASP.NET 2.0
Posted On June 4, 2007 by Ramdas S filed under
A new data bound control integrated in ASP.NET version 2.0 allows for a 3-layer architecture. Using ObjectDataSource control, you can separate the presentation layer, business layer and database layer. Presentation layer contains the web page (UI) while the business layer incorporates the classes that implement business rules, validations, etc. The third layer, i.e. database layer, contains the database.
Previous versions of ASP.NET could not support business layer customization. You can also use Typed Data-set with ObjectDataSource control.
ObjectDataSource gets its data through a data access class that handles the details of database access. Other data sources like SqlDataSource cannot go through user-defined classes.
Attributes of ObjectDataSource Control:
| Attribute | Description |
| ID | The ID of control. |
| Runat | “server” |
| TypeName | Name of data access class. |
| DataObjectType | Used to specify aggregate data type class name. |
| ConflictDetection | Concurrency checking purpose. |
| SelectMethod | To retrieve data. |
| InsertMethod | To insert data. |
| UpdateMethod | To update data. |
| DeleteMethod | To delete data. |
The following sample codes will provide more information on ObjectDataSource control.
Create a database table:
(Currently I am using ODBC to connect with database)
Table Name - Unit:
| Field Name | Data Type | Description |
| UID | Auto increment | Primary key |
| UnitName | Text | Name of unit |
| UnitDesc | Text | Description for unit. |
Let us now create a class that allows us to specify Get/Set properties for the above Unit table. Refer code 1.
Code 1
Class Name: Unit
Imports Microsoft.VisualBasic
Public Class Unit
Private lngUID As Long
Private strUnitName As String
Private strUnitDesc As String
Public Sub New()
End Sub
Public Property UID() As Long
Get
Return lngUID
End Get
Set(ByVal value As Long)
lngUID = value
End Set
End Property
Public Property UnitName() As String
Get
Return strUnitName
End Get
Set(ByVal value As String)
strUnitName = value
End Set
End Property
Public Property UnitDesc() As String
Get
Return strUnitDesc
End Get
Set(ByVal value As String)
strUnitDesc = value
End Set
End Property
End Class
Note: The property name must match the data field names of Bound Field elements that define each bound column. And, class should have a parameter-less constructor [New()].
To specify TypeName for ObjectDataSource control, one more class is required to deal with data. So, we have to create one more class. Check out code 2.
Code 2
Class Name: UnitTbl
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.Odbc
Imports System.ComponentModel
Imports System.Collections.Generic
<DataObject(True)> _
Public Class UnitTbl
<DataObjectMethod(DataObjectMethodType.Select)> _
Public Shared Function GetUnits() As List(Of Unit)
Dim sql As String = "SELECT UID, UnitName, UnitDesc " _
& "FROM Unit"
Dim cmd As OdbcCommand = _
New OdbcCommand(sql, New OdbcConnection(GetConnectionString))
cmd.Connection.Open()
Dim dr As OdbcDataReader = _
cmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim Units As New List(Of Unit)
Do While dr.Read
Dim objUnit As Unit = New Unit
objUnit.UID = CType(dr("UID"), Long)
objUnit.UnitName = dr("UnitName").ToString
objUnit.UnitDesc = dr("UnitDesc").ToString
Units.Add(objUnit)
Loop
dr.Close()
Return Units
End Function
<DataObjectMethod(DataObjectMethodType.Insert)> _
Public Shared Sub InsertUnit(ByVal Unit As Unit)
Dim sql As String = "INSERT INTO Unit " _
& "(UnitName, UnitDesc) " _
& "VALUES('" & Unit.UnitName & "','" & Unit.UnitDesc & "')"
Dim cmd As OdbcCommand = _
New OdbcCommand(sql, New OdbcConnection(GetConnectionString))
cmd.Connection.Open()
cmd.ExecuteNonQuery()
End Sub
<DataObjectMethod(DataObjectMethodType.Update)> _
Public Shared Function UpdateUnit(ByVal Unit As Unit, _
ByVal original_Unit As Unit) As Integer
Dim sql As String = "UPDATE Unit " _
& "SET UnitName ='" & Unit.UnitName & "'," _
& "UnitDesc ='" & Unit.UnitDesc & "' WHERE UID =" & Unit.UID
Dim cmd As OdbcCommand = _
New OdbcCommand(sql, New OdbcConnection(GetConnectionString))
cmd.Connection.Open()
Dim i As Integer = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Return i
End Function
<DataObjectMethod(DataObjectMethodType.Delete)> _
Public Shared Function DeleteUnit(ByVal Unit As Unit) _
As Integer
Dim sql As String = "DELETE FROM Unit " _
& "WHERE UID =" & Unit.UID
Dim cmd As OdbcCommand = _
New OdbcCommand(sql, New OdbcConnection(GetConnectionString))
cmd.Connection.Open()
Dim i As Integer = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Return i
End Function
Private Shared Function GetConnectionString() As String
Return ConfigurationManager.ConnectionStrings _
("UnitConnection").ConnectionString
End Function
End Class
Code 3 demonstrates how connection string value is set in “web.config” file.
Code 3
Web Configuration File: web.config
<connectionStrings>
<add name="UnitConnection" connectionString="Dsn=UnitDSN"
providerName="System.Data.Odbc" />
</connectionStrings>
Now, we will look at the user interface code included in our web page. See code4.
Code 4
UI Page Name: Default.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ObjectDataSource - Unit Table</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Unit
</h2>
<asp:GridView ID="GridView1" runat="server"
DataSourceID="ObjectDataSource1" DataKeyNames="UID"
AutoGenerateColumns="False" ForeColor="Black" >
<Columns>
<asp:BoundField DataField="UID" ReadOnly="True"
HeaderText="Unit ID" >
<ItemStyle Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="UnitName" HeaderText="Unit Name" >
<ItemStyle Width="150px" />
</asp:BoundField>
<asp:BoundField DataField="UnitDesc" HeaderText="Unit Description" >
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
<asp:CommandField ButtonType="Button" ShowDeleteButton="True" />
</Columns>
<RowStyle BackColor="White" ForeColor="Black" />
<HeaderStyle BackColor="Silver" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="Blue" ForeColor="White" />
<AlternatingRowStyle BackColor="WhiteSmoke" ForeColor="Black" />
</asp:GridView>
Here, we specify our class names to the ObjectDataSource control. ObjectDataSource control’s wizard is also useful. You need not do the code. Just answer the steps in the wizard.
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="UnitTbl" DataObjectTypeName="Unit"
ConflictDetection="CompareAllValues"
OldValuesParameterFormatString="original_{0}"
SelectMethod="GetUnits"
InsertMethod="InsertUnit"
DeleteMethod="DeleteUnit"
UpdateMethod="UpdateUnit" >
</asp:ObjectDataSource>
<br />
<asp:Label ID="lblError" runat="server" EnableViewState="False"
ForeColor="Red"></asp:Label><br />
Create a New Unit.<br /><br />
<asp:DetailsView ID="DetailsView1" runat="server"
AutoGenerateRows="False" DataSourceID="ObjectDataSource1"
DefaultMode="Insert" Height="50px" Width="300px"
GridLines="None" BorderStyle="None" CellSpacing="5" >
<Fields>
<asp:BoundField DataField="UnitName"
HeaderText="Unit Name:" />
<asp:BoundField DataField="UnitDesc"
HeaderText="Unit Description:" />
<asp:CommandField ButtonType="Button"
ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
</div>
</form>
</body>
</html>
The web page contains a GridView, DetailView and ObjectDataSource control. All the modules’ code language is VB. There are two class files and one UI web page.
In addition to the above code, you can also trap events like Update, Delete, Insert GridView, DetailView and ObjectDataSource control.
In this way, we can create CRUD (Create, Retrieve, Update and Delete) 3-layer applications using ObjectDataSource control.
The author is a Microsoft Certified Solution Developer working with Comtel Systems, Pune, as a Sr. Software Engineer. He can be reached at: Kuldeep.Deokule@gmail.com.
