Creating a Custom ObjectDataSource Control - Demo
If you are using the ObjectDataSource control with the same properties on multiple pages, then it's useful to derive a new
control from the ObjectDataSource control that has these properties by default. For example, if you are displaying a list of movies
un multiple pages, then it would be helpful to create a specialized MovieDataSource control. In this example, the MovieDataSource
control derives from the base ObjectDataSource control class.
<%@ Page Language="VB" %>
<%@ Register TagPrefix="custom" Namespace="StonecoastWebDesign.Samples" %>
<!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 id="Head1" runat="server">
<title>Show Movie DataSource</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView
id="grdMovies"
DataSourceID="srcMovies"
Runat="server" />
<custom:MovieDataSource
id="srcMovies"
Runat="server" />
</div>
</form>
</body>
</html>
** MovieDataSource.vb **
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Configuration
Imports System.Web.UI.WebControls
'Namespace AspNetUnleashed.Samples
Namespace StonecoastWebDesign.Samples
Public Class MovieDataSource
Inherits ObjectDataSource
Public Sub New()
Me.TypeName = "StonecoastWebDesign.Samples.MoviesComponent"
Me.SelectMethod = "GetMovies"
End Sub
End Class
Public Class MoviesComponent
Private ReadOnly _conString As String
Public Function GetMovies() As SqlDataReader
' Initialize connection
Dim con As New SqlConnection(_conString)
' Initialize command
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandText = "SELECT Title,Director,DateReleased FROM Movies"
' Execute command
con.Open()
Return cmd.ExecuteReader(CommandBehavior.CloseConnection)
End Function
Sub New()
_conString = WebConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString
End Sub
End Class
End Namespace