How to select and write records from a GridView

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tsubasa
    New Member
    • Aug 2008
    • 64

    How to select and write records from a GridView

    I am working on a wish list where users add products to their list for future purhcases. I am using a GridView to display the records by users after they have login to the shopping cart. How can I program a method so that a user can select items from the wish list and have them placed in the shopping cart?

    See Attachment!

    Thank you!
    Attached Files
  • tsubasa
    New Member
    • Aug 2008
    • 64

    #2
    Selecting records in GridView and inserting them to another table.

    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
    Code:
    <%@ 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>
    Last edited by Frinavale; Nov 16 '09, 02:17 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #3
      Hi Tsubasa,

      I think I've come across your question before but because I didn't know what you were using as a "Shopping Cart" I didn't know what a good starting point for answering your question would be.

      Now that you've posted your code it's a Little more clear as to what you're trying to do but I still don't see a shopping cart.

      What is your "Shopping Cart"?
      Is it an Object stored in session?
      Is it a table in a database?
      Is it something else??
      Do you even have a shopping cart?

      Anyways, the first thing I'm going to suggest is adding a ID for the checkbox so that you can locate it using the FindControl method.

      Then when the user clicks the "checkout" button, loop through all of the rows in the GridView and check if the checkbox is checked....if so, do whatever you need to do to add the item to this "shopping cart".

      -Frinny

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        I did run across this question before.
        I've merged the questions together.

        -Frinny

        Comment

        • tsubasa
          New Member
          • Aug 2008
          • 64

          #5
          Hello Frinny!

          Thank you for responding. Yes, I am using a table called "ShopCart" in MS. Access as my shopping cart. I am using an ID in the table for each row, if you look just after the Column you will see this code:
          Code:
          <asp:TemplateField 
              ItemStyle-Width="50"> 
              <ItemTemplate> 
                <asp:CheckBox UnChecked='<%# Eval("id") %>' Runat="Server"/> 
              </ItemTemplate> 
            </asp:TemplateField>
          Here is where I have associated the ID in the WishList table. Is this correct so far?

          -Gabe
          Last edited by Frinavale; Nov 18 '09, 02:10 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            This code doesn't make sense.

            First of all a ASP.NET CheckBox does not have an UnChecked property so I'm not really sure what you're doing here.

            Secondly, you should be using a static ID for the CheckBox because you will want to know the ID you used so that you can use it to retrieve the CheckBox from the GridViewRow using the GridView's FindControl method....

            That way you can loop through all of the rows in your GridView, use the FindControl method to retrieve the CheckBox (via it's ID) and determine whether or not it has been checked.

            If so, do the logic to remove the item from the wishlist and add the item to the shopping cart (which requires you updating both tables).

            -Frinny

            Comment

            • tsubasa
              New Member
              • Aug 2008
              • 64

              #7
              Ok, I have removed the code and have written it this way:
              Code:
               <asp:CheckBoxField
                  HeaderText="ID"
                  DataField="ID"
                  ItemStyle-HorizontalAlign="Center"/>
              Will this work with a FindControl loop?

              -Gabe
              Last edited by Frinavale; Nov 18 '09, 02:10 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.

              Comment

              • tsubasa
                New Member
                • Aug 2008
                • 64

                #8
                Here is what I have changed, since I want the records to come from a dynamic source or column such as ID.
                Code:
                <asp:TemplateField HeaderText="ID" InsertVisible="False">
                      <ItemTemplate>
                         <asp:CheckBox ID="id" runat="server" Text='<%# Eval("id") %>' />
                       </ItemTemplate>
                    </asp:TemplateField>
                Then what I have done is used the following code to loop through the selected checkboxes.
                Code:
                Sub Submit_Form (Src As Object, Args As EventArgs)
                
                Dim Grd As String = "GridView Items Checked:<br />"
                For Each gvr As GridViewRow In ShopCartGrid.Rows
                  Dim chk As CheckBox = DirectCast(gvr.FindControl("id"), CheckBox)
                  If chk.Checked Then
                    Grd += (chk.Text + "<br />")
                  End If
                Next
                GrdLiteral.Text = Grd
                
                
                End Sub

                I added this at the bottom of my page to view my data
                Code:
                <asp:Label id="GrdLiteral" Runat="Server"  ForeColor="#0000FF"/>
                And here is what I have come up with when I select a few records:

                GridView Items Checked:
                4
                3
                2

                So I think that from here I need to write the code so that the selected records can be inserted into the ShopCart table. I will work on this next.

                -Gabe
                Last edited by Frinavale; Nov 18 '09, 02:11 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.

                Comment

                • Frinavale
                  Recognized Expert Expert
                  • Oct 2006
                  • 9749

                  #9
                  Sounds like you got it to work!
                  Congrats :)

                  -Frinny

                  Comment

                  • tsubasa
                    New Member
                    • Aug 2008
                    • 64

                    #10
                    LOL...OK, I need your help. How can I also pull the associated information, then insert them into another table. Thanks!

                    -Gabe

                    I got stuck!

                    Comment

                    • Frinavale
                      Recognized Expert Expert
                      • Oct 2006
                      • 9749

                      #11
                      In your submit_form method, when your're the CheckBox.Checke d value....

                      If the CheckBox is checked then you know that that GridViewRow has been selected by the user.

                      You need to retrieve the data you need from the GridViewRow and then "do stuff" with it to add it to the shopping cart. (By "do stuff" I mean retrieve data for the item from the database if you need to...or update the shopping cart table...or whatever you need to do to add the item to your shopping cart..and perhaps remove it from the wish list).

                      I'm not sure what you're using as the DataSource for your wish list (you may have said something) but it is probably easier to grab this information from the DataSource based on the "ID" of the row that is checked rather than trying to extract the data from the GridViewRow itself...either way will work but I just find it easier to use the data source.


                      So, for example...

                      Code:
                      Sub Submit_Form (Src As Object, Args As EventArgs)
                       
                      Dim Grd As String = "GridView Items Checked:<br />"
                      For Each gvr As GridViewRow In ShopCartGrid.Rows
                        Dim chk As CheckBox = DirectCast(gvr.FindControl("id"), CheckBox)
                        If chk.Checked Then
                          'Grd += (chk.Text + "<br />")
                          
                          'Here, retrieve the ID of the item...hopefully you have an ID...
                          'say your the ID of your item is stored in the last cell in the GridView
                          'you would retrieve it like:
                         Dim itemID As Integer
                         Integer.TryParse(gvr.Cells(gvr.Cells.Count - 1).Text, itemID)
                      
                          'Now that you know the ItemID you can do Stuff
                      
                          'If you need more than just the ItemID you can use the same
                          'method to retrieve information from the GridViewRow...the thing is
                          'that you need to know what cell that the information exists in.
                      
                         'That is why I recommend using the DataSource for the GridView instead
                         'Because if you're using the DataSource (and it's a table) then you can
                         'more easily access the data (because you can use column names).
                         'For example, your data source was a DataTable stored in a variable
                         'named _theWishListDataSource:
                      
                         'Grabbing the rows in the data source with the ItemID:
                         Dim selectedRows() As DataRow = _
                              _theWishListDataSource.Select('ID='" + itemID.ToString + "'")
                         If selectedRows IsNot Nothing AndAlso selectedRows.Count >0 Then
                           Dim theDataRow As DataRow = selectedRows(0)
                           Dim moreInfo As String =  theDataRow.Item("columnName")
                          '......
                         End If
                      
                        End If
                      Next
                      End Sub

                      Hope this makes sense.

                      -Frinny

                      Comment

                      • tsubasa
                        New Member
                        • Aug 2008
                        • 64

                        #12
                        Hi Frinny!

                        Let me give this a try and see what I can do. I will get back to you later, ok. Also, my reply might be a little late because of the upcoming holiday. As always, much thanks!

                        -Tsu

                        Comment

                        • tsubasa
                          New Member
                          • Aug 2008
                          • 64

                          #13
                          Hi Frinny!

                          I worked out the code, but my management has changed their mind on how they would like the functions presented in the wishlist. They would rather that I have a link that will present the item along with details. This I have managed to workout. As for the checkboxes, I would like to code a checkall to place a checkmark in all of the items listed, then I would like to click on the CheckOut button to place a copy of these items in a table called ShopCart. The ShopCart table has the same fields as the WishList.

                          -Tsu
                          Code:
                          <%@ 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 View_Details (Src As Object, Args As CommandEventArgs)
                          
                            Response.Redirect("Details.aspx?BookID=" & Args.CommandName)
                          
                          End Sub
                          
                          
                          Sub Submit_Form (Src As Object, Args As EventArgs)
                          
                          Dim Grd As String
                          For Each gvr As GridViewRow In ShopCartGrid.Rows
                            Dim chk As CheckBox = DirectCast(gvr.FindControl("id"), CheckBox)
                            If chk.Checked Then
                              Grd += (chk.Text + "<br />")
                            End If
                          Next
                          GrdLiteral.Text = Grd
                          
                          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/>
                          <table border="0">
                          <tr>
                            <td><asp:Label id="TheAccountLabel" Font-Size="12pt" ForeColor="#990000" 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
                              HeaderText="BookID"
                              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="Check All">
                              <ItemTemplate>
                                <asp:CheckBox ID="id" Runat="Server"/>
                              </ItemTemplate>
                           </asp:TemplateField>
                              
                            <asp:TemplateField
                              ItemStyle-Width="120"
                              FooterStyle-BackColor="#E0E0E0">
                              <ItemTemplate>
                                <asp:Button Text="Remove" CommandName="Delete" Runat="Server"
                                  Font-Size="10pt" Width="75"/>
                                <asp:LinkButton Text="Details" Runat="Server"
                                  OnCommand="View_Details"
                                  CommandName='<%# Eval("BookID") %>'/>
                              </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:Label id="GrdLiteral" Runat="Server"
                            
                            ForeColor="#0000FF"/>
                          
                          
                          </asp:Content>
                          -Tsu
                          Last edited by Frinavale; Nov 30 '09, 02:18 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.

                          Comment

                          • Frinavale
                            Recognized Expert Expert
                            • Oct 2006
                            • 9749

                            #14
                            I would write the "check all checkboxes" function using JavaScript.

                            You'll have to place a checkbox in the Header of the "checkbox column" to let the user "select/unselect all checkboxes".

                            You'll have to write a JavaScript method that will "check" all of the checkboxes.

                            Then in your GridView's RowDataBound event you will have to indicate that the JavaScript method should be called when the "select/unselect all" checkbox is clicked.

                            For example:
                            Code:
                                Protected Sub MyGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles MyGridView.RowDataBound
                            
                              If e.Row.RowType = DataControlRowType.Header Then
                                Dim checkAllCkbxs As CheckBox = Ctype(e.Row.FindControl("checkAllCheckbox"), CheckBox)
                                If checkAllCkbxs IsNot Nothing
                                  checkAllCkbxs.Attributes.Add("onclick","checkAllCheckBoxes(this,'"+MyGridView.ClientID+"');")
                                End If
                              End If
                            End Sub
                            The JavaScript function "checkAllCheckB oxes" is passed 2 parameters: "this" which refers to the checkbox element, and the ClientID of the GridView.

                            The JavaScript function will have to get a reference to the GridView (which is an HTML table client side), loop through all of the rows check/uncheck the check boxes in the GridView/Table depending on whether or not the "check All" checkbox was checked.

                            The following JavaScript code is not guaranteed to work but is meant to be a guideline to help you:

                            Code:
                            function checkAllCheckBoxes(checkAllCheckBoxElement, gridViewClientID)
                              var gridViewElement = document.getElementById(gridViewClientID);
                              var checked = checkAllCheckBoxElement.checked;
                            
                              if(gridViewElement.rows.length > 0){
                                for(i = 0; i < gridViewElement.rows.length; i++)
                                {
                                  cell = gridViewElement.rows[i].cells[0]; //<--the cell the checkbox is in
                                  for(j = 0; j < cell.childNotes.length; j++)
                                  { //looping through the childNodes of the cell looking for the checkbox
                                    if(cell.childNodes[j].type == "checkbox"){
                                      cell.childNodes[j].checked = checked;
                                    }
                                }
                              }
                            -Frinny

                            Comment

                            • tsubasa
                              New Member
                              • Aug 2008
                              • 64

                              #15
                              Thanks Frinny! I will work on this.

                              -Tsu

                              Comment

                              Working...