Navigation

Search

Categories

On this page

Using Explicit Parameters with the ObjectDataSource control

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 112
This Year: 50
This Month: 0
This Week: 0
Comments: 0

Sign In

 Wednesday, July 25, 2007
Wednesday, July 25, 2007 2:02:49 PM (Eastern Standard Time, UTC-05:00) ( )

The order of the parameters does not matter - just the names of the parameters.  You can specify the type of a parameter using the Type property - Int32, Decimal and DateTime.

Here is a demo of this code.

*** Movies.vb ***

Imports System.Web.Configuration

Public Class Movies

Private ReadOnly _conString As String

Public Sub UpdateMovie(ByVal id As Integer, ByVal title As String, &_
ByVal director As String, ByVal dateReleased As DateTime)
' Create Command
Dim con As New SqlConnection(_conString)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandText = "UPDATE Movies SET Title=@Title,Director=@Director,DateReleased=@DateReleased WHERE Id=@Id"

' Add parameters
cmd.Parameters.AddWithValue("@Title", title)
cmd.Parameters.AddWithValue("@Director", director)
cmd.Parameters.AddWithValue("@DateReleased", dateReleased)
cmd.Parameters.AddWithValue("@Id", id)

' Execute command
Using con
con.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

Public Function GetMovies() As SqlDataReader
' Create Connection
Dim con As New SqlConnection(_conString)

' Create Command
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = con
cmd.CommandText = "SELECT Id,Title,Director,DateReleased FROM Movies"

' Return DataReader
con.Open()
Return cmd.ExecuteReader(CommandBehavior.CloseConnection)
End Function

Public Sub New()
_conString = WebConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString
End Sub

End Class


*** ExplicitShowMovies.aspx ***

<%@ Page Language="VB" %>
<!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 Movies</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:GridView
id="grdMovies"
DataSourceID="srcMovies"
DataKeyNames="Id"
AutoGenerateEditButton="true"
Runat="server" />

<asp:ObjectDataSource
id="srcMovies"
TypeName="Movies"
SelectMethod="GetMovies"
UpdateMethod="UpdateMovie"
Runat="server">
<UpdateParameters>
<asp:Parameter Name="title" />
<asp:Parameter Name="director" />
<asp:Parameter Name="dateReleased" Type="DateTime" />
<asp:Parameter Name="id" Type="Int32" />
</UpdateParameters>
</asp:ObjectDataSource>

</div>
</form>
</body>
</html>