0 Replies - 1242 Views - Last Post: 04 April 2014 - 10:34 PM Rate Topic: -----

#1 laos   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 06-March 14

How to get the correct value of "e.Item.ItemIndex"

Posted 04 April 2014 - 10:34 PM

Hi All,

I have two separate web pages, one will display my product (book), and another page will handle the shopping cart and checkout.

From my default.aspx page, i pass in product id (pid) by using following code:
<asp:Button ID="Button1" runat="server" Text="Add To Cart" PostBackUrl='<%# "~/ShoppingCart.aspx?pid=" & databinder.eval(container.dataitem,"pid") %>' />



Problem1:
With the following code, I am able to add new item. I can check out and the data in the data table will save to database, into "Transactions" table.

But i cannot edit the shopping cart.
With only one row of record in the shopping cart, the moment i click on "edit", instead of showing me the update or cancel control, that particular row will be deleted. If I click on delete, nothing will happen.

With more than one row of record in the shopping cart, say 3, when i click on edit for one of the item, that item will be deleted, and the other two items remain in the shopping cart.
The second time i click on edit(any one of the two remaining items), now the update or cancel contorl appear.
Sub problem1 If i change the quantity and click on Update, i receive error message "System.ArgumentOutOfRangeException was unhandled by user code".
Sub problem2 If I click cancel, that row of record will be deleted.


I am guessing the value of "e.Item.ItemIndex" was wrong. How to solve these problems?

ShoppingCart.aspx
<%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="ShoppingCart.aspx.vb" Inherits="ShoppingCart" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<asp:Panel id="pnlShowCart" runat="server">
  <h1>View Cart</h1>

  <asp:DataGrid id="dgCart" runat="server"
      AutoGenerateColumns="false" GridLines="None" CellPadding="3"
      Width="100%" DataKeyField="ItemID"
      OnEditCommand="dgCart_Edit"
      OnCancelCommand="dgCart_Cancel"
      OnUpdateCommand="dgCart_Update"
      OnItemCommand="dgCart_Delete"
      >
    <HeaderStyle Font-Names="arial" BackColor="#003366"
        ForeColor="#FFFFFF" Font-Bold="true" Font-Size="10" />
    <ItemStyle Font-Names="arial" Font-Size="10" />
    <Columns>
      <asp:BoundColumn DataField="Title" HeaderText="Book Title"
          ReadOnly="true" />
      <asp:BoundColumn DataField="Cost" HeaderText="Cost"
          ReadOnly="true" />
      <asp:TemplateColumn HeaderText="Quantity">
        <ItemTemplate>
          <%# Container.DataItem("Quantity") %>
        </ItemTemplate>
        <EditItemTemplate>
          <asp:TextBox id="txtQuantity" runat="server" Width="50"
              Text='<%# Container.DataItem("Quantity") %>' />
        </EditItemTemplate>
      </asp:TemplateColumn>
          <asp:EditCommandColumn EditText="Edit" CancelText="Cancel"
          UpdateText="Update" />
       <asp:ButtonColumn 
                 HeaderText="" 
                 ButtonType="LinkButton" 
                 Text="Delete" 
                 CommandName="dgCart_Delete"/>

    </Columns>
  </asp:DataGrid>
  <p align="right"><strong>Total: <asp:Label id="lblTotal"
      runat="server" /></strong></p>
  <p align="right"><asp:LinkButton id="lbContinue"
      Text="Continue Shopping" runat="server"
      onclick="ContinueShopping" /> |
      <asp:LinkButton id="lbCheckOut" Text="Checkout"
      runat="server" onclick="CheckOut" /></p>
</asp:Panel>
</asp:Content>




ShoppingCart.aspx.vb
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO


Partial Class ShoppingCart
    Inherits System.Web.UI.Page

    Dim Conn As New SqlConnection("Data Source=ServerName;Initial Catalog=EWAPP;Integrated Security=True")
    Dim DA As SqlDataAdapter
    Dim DS As New DataSet()
    Dim DR As DataRow
    Dim CartDT As DataTable
    Dim CartView As DataView

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        pnlShowCart.Visible = True
        CartDT = Session("Cart")
        If CartDT Is Nothing Then
            CartDT = New DataTable("Cart")
            CartDT.Columns.Add("CartID", GetType(Integer))
            CartDT.Columns("CartID").AutoIncrement = True
            CartDT.Columns("CartID").AutoIncrementSeed = 1
            CartDT.Columns.Add("ItemID", GetType(Integer))
            CartDT.Columns.Add("Title", GetType(String))
            CartDT.Columns.Add("Quantity", GetType(Integer))
            CartDT.Columns.Add("Cost", GetType(Decimal))
            Session("Cart") = CartDT
        End If

        Dim ItemID As Integer = Request.QueryString("pid")
        Dim objItemInfo As DataSet = FindItem(ItemID)

        Dim blnMatch As Boolean = False
        For Each DR In CartDT.Rows
            If DR("ItemID") = ItemID Then
                DR("Quantity") += 1
                blnMatch = True
                Exit For
            End If
        Next

        If Not blnMatch Then
            DR = CartDT.NewRow()
            DR("ItemID") = ItemID
            DR("Title") = objItemInfo.Tables("ItemInfo").Rows(0).Item("title")
            DR("Quantity") = 1
            DR("Cost") = objItemInfo.Tables("ItemInfo").Rows(0).Item("price")
            CartDT.Rows.Add(DR)
        End If


        dgCart.DataSource = CartDT
        dgCart.DataBind()
        lblTotal.Text = "$" & GetItemTotal()



    End Sub

    Sub AddToCart(s As Object, e As DataListCommandEventArgs)

        'pnlShowCart.Visible = True

        'Dim ItemID As Integer = DataList1.DataKeys(e.Item.ItemIndex)
        Dim ItemID As Integer = Request.QueryString("pid")
        Dim objItemInfo As DataSet = FindItem(ItemID)

        Dim blnMatch As Boolean = False
        For Each DR In CartDT.Rows
            If DR("ItemID") = ItemID Then
                DR("Quantity") += 1
                blnMatch = True
                Exit For
            End If
        Next

        If Not blnMatch Then
            DR = CartDT.NewRow()
            DR("ItemID") = ItemID
            DR("Title") = objItemInfo.Tables("ItemInfo").Rows(0).Item("title")
            DR("Quantity") = 1
            DR("Cost") = objItemInfo.Tables("ItemInfo").Rows(0).Item("price")
            CartDT.Rows.Add(DR)
        End If


        dgCart.DataSource = CartDT
        dgCart.DataBind()
        lblTotal.Text = "$" & GetItemTotal()
    End Sub

    Function FindItem(ItemID As Integer) As DataSet
        Dim objItemInfo As New DataSet()

        DA = New SqlDataAdapter( _
          "SELECT * FROM BOOK WHERE PID=" & ItemID, Conn)
        DA.Fill(objItemInfo, "ItemInfo")

        Return objItemInfo
    End Function

    Function GetItemTotal() As Decimal
        Dim decRunningTotal As Decimal = 0

        For Each DR In CartDT.Rows
            decRunningTotal += _
                Decimal.Round(DR("Cost") * DR("Quantity"), 2)
        Next

        Return decRunningTotal
    End Function

    Sub dgCart_Edit(s As Object, e As DataGridCommandEventArgs)
        Response.Write(e.Item.ItemIndex)
        dgCart.EditItemIndex = e.Item.ItemIndex

        dgCart.DataSource = CartDT
        dgCart.DataBind()
    End Sub

    Sub dgCart_Cancel(s As Object, e As DataGridCommandEventArgs)
        dgCart.EditItemIndex = -1

        dgCart.DataSource = CartDT
        dgCart.DataBind()
    End Sub

    Sub dgCart_Update(s As Object, e As DataGridCommandEventArgs)
        Dim txtQuantity As TextBox
        Dim intCartID As Integer

        intCartID = dgCart.DataKeys(e.Item.ItemIndex)
        txtQuantity = e.Item.FindControl("txtQuantity")

        For Each DR In CartDT.Rows
            If DR("CartID") = intCartID Then
                DR("Quantity") = Int32.Parse(txtQuantity.Text)
                Exit For
            End If
        Next

        lblTotal.Text = "$" & GetItemTotal()
        dgCart.EditItemIndex = -1

        dgCart.DataSource = CartDT
        dgCart.DataBind()
    End Sub

    Sub dgCart_Delete(s As Object, e As DataGridCommandEventArgs)

        CartDT.Rows(e.Item.ItemIndex).Delete()

        dgCart.DataSource = CartDT
        dgCart.DataBind()

        lblTotal.Text = "$" & GetItemTotal()
    End Sub

    Sub ContinueShopping(s As Object, e As EventArgs)
        'pnlShowCart.Visible = False
        'pnlShowItems.Visible = True
        Response.Redirect("Default.aspx")
    End Sub

    Sub CheckOut(ByVal s As Object, ByVal e As EventArgs)

        Dim strSQL As String = "INSERT INTO TRANSACTIONS (PID,T_QTY,TRANDATE) values (@pid,@t_qty,@datetime)"

        Try
            Conn.Open()
            If CartDT IsNot Nothing Then
                'save transaction from temp table to database
                For Each DR In CartDT.Rows
                    'Response.Write(DR("ItemID"))   
                    'Response.Write(DR("Title").ToString)
                    'Response.Write(DR("Quantity"))
                    'Response.Write(DR("Cost"))
                    Dim command As New SqlCommand(strSQL, Conn)
                    command.Parameters.Add("@pid", SqlDbType.Int).Value = Val(DR("ItemID"))
                    command.Parameters.Add("@t_qty", SqlDbType.Int).Value = Val(DR("Quantity"))
                    command.Parameters.Add("@datetime", SqlDbType.DateTime).Value = DateAndTime.Now
                    command.ExecuteNonQuery()

                Next
            End If
        Catch ex As Exception
            Response.Write(ex.Message)
        Finally
            Conn.Close()
        End Try

        'redirect to payment screen


    End Sub

End Class




Is This A Good Question/Topic? 0
  • +

Page 1 of 1