Groups | Blog | Home
all groups > asp.net datagrid control > october 2005 >

asp.net datagrid control : wiring up a datagrid button


martinharvey via DotNetMonster.com
10/29/2005 7:48:38 AM
This is probably a very simple problem but i would appreciate some help.

I have wired up a datagrid button with the following code.

Sub AddProduct(sender As Object, e As DataGridCommandEventArgs)
Dim ProductID As Integer = CType(dg.DataKeys(e.Item.ItemIndex), Integer)
' Create the connection object
Dim connection As New SqlConnection(ConfigurationSettings.AppSettings
("connectionString"))
' Create and initialize the command object
Dim command As New SqlCommand("SP_AddToCart", connection)
command.CommandType = CommandType.StoredProcedure.....................
.....

This code works fine on the page


I am trying to compile a public shared function using the following

Imports System
Imports System.Data
ImportS System.Data.SqlClient
Imports System.configuration
Imports System.Web

Namespace worldshop
Public Class ShoppingCart

Public Shared Function AddProduct(sender As Object, e As
DataGridCommandEventArgs)
Dim ProductID As Integer = CType(dg.DataKeys(e.Item.ItemIndex), Integer)
' Create the connection object
Dim connection As New SqlConnection(connectionString)
' Create and initialize the command object
Dim command As New SqlCommand("SP_AddToCart", connection)
command.CommandType = CommandType.StoredProcedure

But i get the the following error:

Public Shared Function AddProduct(sender As Object, e As DataGridCommandEven
tArgs)
~~~~~~~~~~~~~~~~~~~~~~~~
C:\worldshopdevelopement\ShoppingCart.vb(53) : error BC30451: ?? 'dg' ????????
??
? Dim ProductID As Integer = CType(dg.DataKeys(e.Item.ItemIndex), Integer)

Can anyone tell me where i am going wrong

Many thanks

Martin


--
alvinz_c
11/9/2005 1:40:26 AM
Did you set the DataKeyField property in the DataGrid declaration in HTML ?
For instance,

<asp:DataGrid DataKeyField="MyIDInDB" ................>

Likewise, try to cast it to integer using Int32.Parse()

Dim ProductID As Integer = Int32.Parse(dg.DataKeys(e.Item.ItemIndex))



AddThis Social Bookmark Button