C# .NET - How to insert selected records from a GridView into another table

Asked By Gabe Martin on 16-Nov-09 05:01 AM
I have a gridview that I am using as a wishlist, but I want to have the functionality of allowing users to add their items from their wishlist to their respective shopping cart. I have programmed the user login to pull up the respective user's wishlist and I have programmed a button to remove unwanted items. How can I program a checkbox that can be selected by the user, then have the user click on the CheckOut button to copy those items and the associated information to the shopping cart?

See Code Below

<%@ Page MasterPageFile="eCommerce.master" Language="vb" Debug="True"%>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Drawing" %>

<SCRIPT Runat="Server">

Sub Page_Load

If Session("LoggedIn") <> True Then
Response.Redirect("Loginwl.aspx")
End If

If Not Page.IsPostBack Then
Dim User As String
TheAccountLabel.Text = Session("LoginName")
End If

End Sub

Sub Get_Rows (Src As Object, Args As SqlDataSourceStatusEventArgs)

If Args.AffectedRows = 0 Then
NoItemsMessage.Visible = True
End If

End Sub


Sub Submit_Form (Src As Object, Args As EventArgs)

Dim OrderTotal As Label = ShopCartGrid.FooterRow.FindControl("OrderTotal")
Session("OrderTotal") = OrderTotal.Text
Response.Redirect("SubmitForm.aspx")

End Sub

</SCRIPT>

<asp:Content id="WishList" ContentPlaceHolderID="CONTENT" Runat="Server">

<asp:Label Text="Wish List for" Font-Size="14pt" ForeColor="#990000"
Runat="Server"/><br/>
<br/>
<table border="0">
<tr>
<td><asp:Label id="TheAccountLabel" Runat="Server"/></td>
</tr>
</table>

<asp:Label id="NoItemsMessage" Runat="Server"
Text="Zero Items!" EnableViewState="False" Visible="False"
Width="180" Height="40" BackColor="#E0E0E0" ForeColor="#990000"
BorderStyle="Solid" BorderWidth="1" BorderColor="#C0C0C0"
Style="margin-top:10px; padding:15px"/>

<asp:Panel Width="550" Runat="Server"
ForeColor="#990000" HorizontalAlign="Right">
<asp:Label id="ErrMessage" Text=" " EnableViewState="False" Runat="Server"/>
</asp:Panel>

<asp:AccessDataSource id="ShopCartSource" Runat="Server"
DataFile="/Databases/BooksDB.mdb"
OnSelected="Get_Rows"

SelectCommand="SELECT * FROM WishList WHERE TheAccount = TheAccountLabel ORDER BY BookId"

DeleteCommand="DELETE FROM WishList
WHERE TheAccount=@TheAccount AND BookID=@BookID"
>
<SelectParameters>
<asp:ControlParameter Name="TheAccount" ControlId="TheAccountLabel"
PropertyName="Text"/>
</SelectParameters>
<DeleteParameters>
<asp:ControlParameter Name="TheAccount" ControlId="TheAccountLabel"
PropertyName="Text"/>
</DeleteParameters>

</asp:AccessDataSource>

<asp:GridView id="ShopCartGrid" DataSourceID="ShopCartSource" Runat="Server"
AutoGenerateColumns="False"
DataKeyNames="TheAccount, BookID"
Cellpadding="3"
ShowFooter="True"
HeaderStyle-BackColor="#990000"
HeaderStyle-ForeColor="#FFFFFF"
EditRowStyle-BackColor="#E0E0E0">

<Columns>

<asp:TemplateField
ItemStyle-Width="50">
<ItemTemplate>
<asp:CheckBox UnChecked='<%# Eval("id") %>' Runat="Server"/>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField
HeaderText="ID"
ItemStyle-Width="50">
<ItemTemplate>
<asp:Label Runat="Server"
Text='<%# Eval("BookID") %>'/>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField
HeaderText="Title"
ItemStyle-Width="350">
<ItemTemplate>
<asp:Label Runat="Server"
Text='<%# Eval("BookTitle") %>'/>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField
HeaderText="Price"
ItemStyle-HorizontalAlign="Right"
ItemStyle-Width="60">
<ItemTemplate>
<asp:Label Runat="Server"
Text='<%# String.Format("{0:N}", Eval("BookPrice")) %>'/>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField
HeaderText="Ui"
ItemStyle-Width="60">
<ItemTemplate>
<asp:Label Runat="Server"
Text='<%# Eval("ui") %>'/>
</ItemTemplate>
<ItemTemplate>
<asp:Label Runat="Server"
Text='<%# Eval("Ui") %>'
Width="25" Font-Size="9pt" Style="text-align:right"/>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField
HeaderText="Edit"
ItemStyle-Width="175"
FooterStyle-BackColor="#E0E0E0">
<ItemTemplate>
<asp:Button Text="Remove" CommandName="Delete" Runat="Server"
Font-Size="10pt" Width="75"/>
</ItemTemplate>
<FooterTemplate>
<asp:Button Text="Checkout ยป" OnClick="Submit_Form" Runat="Server"
Font-Size="10pt" Width="75" Style="margin-top:5px"/>
</FooterTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>

</asp:Content>
 

re - Web Star replied to Gabe Martin on 16-Nov-09 06:08 AM

follows these steps for that type of shopping cart with wishlist.

step 1; first u add more item in your wishlist as u done.

step2: select some item from wishhllist by selecting checkbox in gridview.

Step3: on click event of checkout button u put this code for getting all checked row id

//Namespaces needed
using System.Collections;


/// <summary>
/// method to retrieve all the selected items in the GridView
/// NOTE: This is so we dont lose track of them while paging
/// </summary>
private void GetCheckedItems(string crtl,GridView grdView)
{
    //instantiate new ArrayList to hold our checked items
    ArrayList checkedItems = new ArrayList();
    CheckBox chk;
    string chkBoxIndex = string.Empty;
    //loop through each row in the GridView
    foreach (GridViewRow row in grdView.Rows)
    {
        //get the index of the current CheckBox
        chkBoxIndex = (string)grdView.DataKeys[row.RowIndex].Value.ToString();
        chk = (CheckBox)row.FindControl(ctrl);
        //add ArrayList to Session is if doesnt already exist
        if (!(Session["CheckedItems"] == null))
        {
            checkedItems = (ArrayList)Session["CheckedItems"];
        }

        //now see if the current CheckBox is checked
        if (chk.Checked)
        {
            //see if the current value is in the Session, if not add it
            if (!(checkedItems.Contains(chkBoxIndex)))
            {
                //add to the list
                checkedItems.Add(chkBoxIndex);
            }
            else
            {
                //remove from list since it's unchecked
                checkedItems.Remove(chkBoxIndex);
            }
        }

    }
    //update Session with the list of checked items
    Session["CheckedItems"] = checkedItems;
}

Step4: after the u can populate that selected id on the shopping cart page from database.

Reply to Web star from Gabe - Gabe Martin replied to Web Star on 16-Nov-09 06:34 PM

Hello Web Star,

Thank you for replying to my question.  The answer you provided is in C#.  If you look at the code that I have provided, I am programming in VB.  Do you have the same code in VB?   Thanks!

-Gabe