Link to home
Start Free TrialLog in
Avatar of gogetsome
gogetsomeFlag for United States of America

asked on

Send Gridview values to cart *urgent please help*

Hello, I'm still struggling with my first cart and could really use some help. I followed a tutorial and had a shoping cart working which takes the value from a bound dropdown list which populates some lables with the selected dataView row. Well, that was all good but not very practicle when dealing with 60,000 items. I need a method to be able to do a search against the data base via invtId and dsiplay the data in a gridview, click a select button and populate the lables. Enter the quantity requested and click the btnAdd to send the row to the cart.  I started to do this and hit a newby snag.

In attempting to convert the drop down to the gridvew I'm getting the following error: Object reference not set to an instance of an object.
which is occuring in the getSelectedProduct function here: dvProduct.RowFilter = GridView1.SelectedIndex

I'm including the entire code of the project in a humble attempt to obtain much needed help.

The Order page:
Imports System.Data
Imports System.Data.SqlClient


Partial Class _default
    Inherits System.Web.UI.Page

    Private selectedProduct As product

    Protected Sub page_load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'If Not IsPostBack Then
        '    ddlProducts.DataBind()
        'End If
        selectedProduct = Me.GetSelectedProduct
        lblId.Text = selectedProduct.id
        lblInvtId.Text = selectedProduct.invtId
        lblDescr.Text = selectedProduct.descr
        lblLocation.Text = selectedProduct.location
        lblQtyOnHand.Text = selectedProduct.qtyOnHand
    End Sub

    Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
        lblId.Text = GridView1.Rows(e.CommandArgument).Cells(1).Text
        lblInvtId.Text = GridView1.Rows(e.CommandArgument).Cells(2).Text
        lblDescr.Text = GridView1.Rows(e.CommandArgument).Cells(4).Text
        lblLocation.Text = GridView1.Rows(e.CommandArgument).Cells(6).Text
        lblQtyOnHand.Text = GridView1.Rows(e.CommandArgument).Cells(3).Text
    End Sub

    Private Function GetSelectedProduct() As product
        Dim dvProduct As DataView = CType(SqlDataSource2.Select( _
        DataSourceSelectArguments.Empty), DataView)
        dvProduct.RowFilter = GridView1.SelectedIndex
        'dvProduct.RowFilter = "id = '" & ddlProducts.SelectedValue & "'"
        Dim product As New product
        product.id = dvProduct(0)("Id").ToString
        product.invtId = dvProduct(0)("InvtId").ToString
        product.descr = dvProduct(0)("descr").ToString
        product.location = dvProduct(0)("location").ToString
        product.qtyOnHand = dvProduct(0)("qtyOnHand").ToString
        Return product
    End Function

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        If Page.IsValid Then
            Dim cartItem As New cartItem
            cartItem.product = selectedProduct
            cartItem.quantity = CType(txtQuantity.Text, Integer)
            Me.addToCart(cartItem)
            Response.Redirect("cart.aspx")
        End If
    End Sub

    Private Sub addToCart(ByVal CartItem As cartItem)
        Dim cart As SortedList = getCart()
        Dim sId As String = selectedProduct.id
        If cart.ContainsKey(sId) Then
            cartItem = CType(cart(sId), cartItem)
            cartItem.quantity += CType(txtQuantity.Text, Integer)
        Else
            cart.Add(sId, cartItem)
        End If

    End Sub

    Private Function getCart() As SortedList
        If Session("Cart") Is Nothing Then
            Session.Add("Cart", New SortedList)
        End If
        Return CType(Session("cart"), SortedList)
    End Function

End Class

The Product class:

Public Class product
    Public id As String
    Public invtId As String
    Public descr As String
    Public location As String
    Public qtyOnHand As String
End Class

The cartItem class:

Public Class cartItem
    Public product As product
    Public quantity As Integer

    Public Function Display() As String
        Return "Inventory ID:" & "" & "" & product.invtId & " Quantity Requested: " & "" & "" & quantity.ToString() & " From: " & "" & "" & product.location
    End Function
End Class

The cart page:
Partial Class cart
    Inherits System.Web.UI.Page

    Private Cart As SortedList

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Cart = getCart()
        If Not IsPostBack Then
            Me.displayCart()
        End If
    End Sub

    Private Function getCart() As SortedList
        If Session("cart") Is Nothing Then
            Session.Add("Cart", New SortedList)
        End If
        Return CType(Session("Cart"), SortedList)
    End Function

    Private Sub displayCart()
        lstCart.Items.Clear()
        Dim CartItem As cartItem
        Dim CartEntry As DictionaryEntry
        For Each CartEntry In Cart
            CartItem = CType(CartEntry.Value, cartItem)
            lstCart.Items.Add(CartItem.Display)
        Next
    End Sub

    Protected Sub btnRemove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRemove.Click
        If lstCart.SelectedIndex > -1 And Cart.Count > 0 Then
            Cart.RemoveAt(lstCart.SelectedIndex)
            Me.displayCart()
        End If
    End Sub

    Protected Sub btnEmpty_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnEmpty.Click
        Cart.Clear()
        lstCart.Items.Clear()
        lblMessage.Text = ""
    End Sub

Order page source code:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="order.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;<br />
        <asp:TextBox ID="txtInvtId" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" /><br />
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource2"
            Width="731px">
            <Columns>
                <asp:CommandField ShowSelectButton="True" />
                <asp:BoundField DataField="id" HeaderText="id" SortExpression="id" />
                <asp:BoundField DataField="invtId" HeaderText="invtId" SortExpression="invtId" />
                <asp:BoundField DataField="qtyOnHand" HeaderText="qtyOnHand" SortExpression="qtyOnHand" />
                <asp:BoundField DataField="descr" HeaderText="descr" SortExpression="descr" />
                <asp:BoundField DataField="siteId" HeaderText="siteId" SortExpression="siteId" />
                <asp:BoundField DataField="location" HeaderText="location" SortExpression="location" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:test%>"
            SelectCommand="SELECT [id], [invtId], [qtyOnHand], [descr], [siteId], [location] FROM [testInventory] WHERE ([invtId] = @invtId) ORDER BY [siteId]">
            <SelectParameters>
                <asp:ControlParameter ControlID="txtInvtId" Name="invtId" PropertyName="Text" Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
        <br />
        <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DB_210580_qualwebConnectionString %>"
            SelectCommand="SELECT [id], [invtId], [qtyOnHand], [descr], [siteId], [location] FROM [testInventory] WHERE ([siteId] < @siteId) ORDER BY [siteId]">
            <SelectParameters>
                <asp:Parameter DefaultValue="100" Name="siteId" Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
        &nbsp; &nbsp; &nbsp;
        <br />
        <br />
        <asp:DropDownList ID="ddlProducts" runat="server" DataSourceID="SqlDataSource1" DataTextField="invtId"
            DataValueField="id" AutoPostBack="True">
        </asp:DropDownList>
        <br />
        <br />
        <asp:Label ID="Label1" runat="server" Text="ID: "></asp:Label>
        <asp:Label ID="lblId" runat="server"></asp:Label><br />
        <asp:Label ID="Label2" runat="server" Text="QTY On Hand: "></asp:Label>
        <asp:Label ID="lblQtyOnHand" runat="server"></asp:Label><br />
        <asp:Label ID="Label3" runat="server" Text="Inventory ID: "></asp:Label>
        <asp:Label ID="lblInvtId" runat="server"></asp:Label><br />
        <asp:Label ID="Label4" runat="server" Text="Description: "></asp:Label>
        <asp:Label ID="lblDescr" runat="server"></asp:Label><br />
        <asp:Label ID="Label5" runat="server" Text="Location: "></asp:Label>
        <asp:Label ID="lblLocation" runat="server"></asp:Label><br />
        <asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox>&nbsp;
        <br />
        <br />
        <asp:Button ID="btnAdd" runat="server" Text="Add to Cart" />
        <asp:Button ID="btnCart" runat="server" PostBackUrl="~/cart.aspx" Text="Go to Cart" /><br />
        <br />
        <asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label></div>
    </form>
</body>
</html>

Cart source code:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="cart.aspx.vb" Inherits="cart" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        cart page<br />
        <br />
        <asp:ListBox ID="lstCart" runat="server" Height="135px" Width="538px"></asp:ListBox>
        <asp:Button ID="btnRemove" runat="server" Text="Remove Item" />
        <asp:Button ID="btnEmpty" runat="server" Text="Empty Cart" /><br />
        <br />
        <asp:Button ID="btnContinue" runat="server" PostBackUrl="~/order.aspx" Text="Continue Shopping"
            Width="126px" />
        <asp:Button ID="btnCheckout" runat="server" Text="Check Out" /><br />
        <br />
        <asp:Label ID="lblMessage" runat="server" Width="155px"></asp:Label><br />
   
    </div>
    </form>
</body>
</html>






Avatar of GavinMannion
GavinMannion

Change

GridView1.SelectedIndex

To

GridView1.Rows[GridView1.SelectedIndex].Cells[4].Text;

Where 4 is whatever cell your info is in.....
Avatar of gogetsome

ASKER

Thank you GavinMannion for assisting. I changed the getSelectedProduct function's RowFilter to:
 dvProduct.RowFilter = GridView1.Rows(GridView1.SelectedIndex).Cells(1).Text

cells(1) is the id column which is the primary key.

But the error has changed to this:

System.ArgumentOutOfRangeException was unhandled by user code
  Message="Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
  ParamName="index"
  Source="mscorlib"
  StackTrace:
       at System.Collections.ArrayList.get_Item(Int32 index)
       at System.Web.UI.WebControls.GridViewRowCollection.get_Item(Int32 index)
       at _Default.GetSelectedProduct() in C:\Documents and Settings\Scott Baldridge\My Documents\Visual Studio 2005\WebSites\cart\order.aspx.vb:line 33
       at _Default.page_load(Object sender, EventArgs e) in C:\Documents and Settings\Scott Baldridge\My Documents\Visual Studio 2005\WebSites\cart\order.aspx.vb:line 14
       at System.Web.UI.Control.OnLoad(EventArgs e)
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
ASKER CERTIFIED SOLUTION
Avatar of GavinMannion
GavinMannion

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The selected index has a value of -1

I moved the selectedProduct code out of page_load and the page will now at least load. I populate the gridView and select a row which I would like to populate the labels. I'm using the commandArgument in the gridview's rowCommand for the primary key or the index. Sorry still trying to understand all this. I chagned teh commandSrgument to commandName for all the cells except for the primary key cell.

This is what I have now:

 Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
        selectedProduct = Me.GetSelectedProduct
        lblId.Text = selectedProduct.id
        lblInvtId.Text = selectedProduct.invtId
        lblDescr.Text = selectedProduct.descr
        lblLocation.Text = selectedProduct.location
        lblQtyOnHand.Text = selectedProduct.qtyOnHand

        lblId.Text = GridView1.Rows(e.CommandArgument).Cells(1).Text
        lblInvtId.Text = GridView1.Rows(e.CommandName).Cells(2).Text
        lblDescr.Text = GridView1.Rows(e.CommandName).Cells(4).Text
        lblLocation.Text = GridView1.Rows(e.CommandName).Cells(6).Text
        lblQtyOnHand.Text = GridView1.Rows(e.CommandName).Cells(3).Text
    End Sub

    Private Function GetSelectedProduct() As product
        Dim dvProduct As DataView = CType(SqlDataSource2.Select( _
        DataSourceSelectArguments.Empty), DataView)
        dvProduct.RowFilter = GridView1.Rows(GridView1.SelectedIndex).Cells(1).Text
        Dim product As New product
        product.id = dvProduct(0)("Id").ToString
        product.invtId = dvProduct(0)("InvtId").ToString
        product.descr = dvProduct(0)("descr").ToString
        product.location = dvProduct(0)("location").ToString
        product.qtyOnHand = dvProduct(0)("qtyOnHand").ToString
        Return product
    End Function
I see that you have accepted my answer even though your new code does not look 100% correct.

I was 90% sure you would use e.CommandArgument and not e.CommandName when finding the row.

Did it work?
Thanks Gavin for helping. You are correct I did change it back to e.command Argument.