473,468 Members | 4,274 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How to select and write records from a GridView

tsubasa
64 New Member
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 Images
File Type: jpg sample 1.jpg (18.7 KB, 334 views)
Nov 13 '09 #1

✓ answered by Frinavale

Somewhere you are attempting to use something that has not been instantiated yet. You get a null reference exception ("Object reference not set to an instance of an object") when you try to use something that does not exist. Make sure that your objects have been instantiated (using the keyword "new" to instantiate them). If your objects are being instantiated by some other code, make sure that they exist by testing if they are nothing before you try to use them.

Here's an example of checking if an object has been instantiated in VB.NET:
Expand|Select|Wrap|Line Numbers
  1. If myObject IsNot Nothing Then
  2.   'then the object exists.
  3. Else
  4.  'then the object does not exist.
  5. End If
  6.  
Or you could use:
Expand|Select|Wrap|Line Numbers
  1. If myObject Is Nothing Then
  2.  'then the object does not exist.
  3. Else
  4.   'then the object exists.
  5. End If
  6.  
In your case, make sure that anything retrieved from the database exists before you attempt to use it.

-Frinny

21 4596
tsubasa
64 New Member
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
Expand|Select|Wrap|Line Numbers
  1. <%@ Page MasterPageFile="eCommerce.master" Language="vb" Debug="True"%>
  2. <%@ Import Namespace="System.Data.OleDb" %>
  3. <%@ Import Namespace="System.Drawing" %>
  4.  
  5. <SCRIPT Runat="Server">
  6.  
  7. Sub Page_Load
  8.  
  9.   If Session("LoggedIn") <> True Then
  10.   Response.Redirect("Loginwl.aspx")
  11.   End If
  12.  
  13.   If Not Page.IsPostBack Then
  14.     Dim User As String
  15.     TheAccountLabel.Text = Session("LoginName")
  16.   End If
  17.  
  18. End Sub
  19.  
  20. Sub Get_Rows (Src As Object, Args As SqlDataSourceStatusEventArgs)
  21.  
  22.   If Args.AffectedRows = 0 Then
  23.     NoItemsMessage.Visible = True
  24.   End If
  25.  
  26. End Sub
  27.  
  28.  
  29. Sub Submit_Form (Src As Object, Args As EventArgs)
  30.  
  31.   Dim OrderTotal As Label = ShopCartGrid.FooterRow.FindControl("OrderTotal")
  32.   Session("OrderTotal") = OrderTotal.Text
  33.   Response.Redirect("SubmitForm.aspx")
  34.  
  35. End Sub
  36.  
  37. </SCRIPT>
  38.  
  39. <asp:Content id="WishList" ContentPlaceHolderID="CONTENT" Runat="Server">
  40.  
  41. <asp:Label Text="Wish List for" Font-Size="14pt" ForeColor="#990000" 
  42. Runat="Server"/><br/>
  43. <br/>
  44. <table border="0">
  45. <tr>
  46.   <td><asp:Label id="TheAccountLabel" Runat="Server"/></td>
  47. </tr>
  48. </table>
  49.  
  50. <asp:Label id="NoItemsMessage" Runat="Server"
  51.   Text="Zero Items!" EnableViewState="False" Visible="False"
  52.   Width="180" Height="40" BackColor="#E0E0E0" ForeColor="#990000"
  53.   BorderStyle="Solid" BorderWidth="1" BorderColor="#C0C0C0" 
  54.   Style="margin-top:10px; padding:15px"/>
  55.  
  56. <asp:Panel Width="550" Runat="Server"
  57. ForeColor="#990000" HorizontalAlign="Right">
  58.   <asp:Label id="ErrMessage" Text=" " EnableViewState="False" Runat="Server"/>
  59. </asp:Panel>
  60.  
  61. <asp:AccessDataSource id="ShopCartSource" Runat="Server"
  62.   DataFile="/Databases/BooksDB.mdb"
  63.   OnSelected="Get_Rows"
  64.  
  65.   SelectCommand="SELECT * FROM WishList WHERE TheAccount = TheAccountLabel ORDER BY BookId"
  66.  
  67.     DeleteCommand="DELETE FROM WishList
  68.                  WHERE TheAccount=@TheAccount AND BookID=@BookID"
  69. >
  70.   <SelectParameters>
  71.     <asp:ControlParameter Name="TheAccount" ControlId="TheAccountLabel"
  72.     PropertyName="Text"/>
  73.   </SelectParameters>
  74.   <DeleteParameters>
  75.     <asp:ControlParameter Name="TheAccount" ControlId="TheAccountLabel"
  76.     PropertyName="Text"/>
  77.   </DeleteParameters>
  78.  
  79. </asp:AccessDataSource>
  80.  
  81. <asp:GridView id="ShopCartGrid" DataSourceID="ShopCartSource" Runat="Server"
  82.   AutoGenerateColumns="False"
  83.   DataKeyNames="TheAccount, BookID"
  84.   Cellpadding="3"
  85.   ShowFooter="True"
  86.   HeaderStyle-BackColor="#990000"
  87.   HeaderStyle-ForeColor="#FFFFFF"
  88.   EditRowStyle-BackColor="#E0E0E0">
  89.  
  90.    <Columns>
  91.  
  92.   <asp:TemplateField
  93.     ItemStyle-Width="50">
  94.     <ItemTemplate>
  95.       <asp:CheckBox UnChecked='<%# Eval("id") %>' Runat="Server"/>
  96.     </ItemTemplate>
  97.   </asp:TemplateField>
  98.  
  99.   <asp:TemplateField
  100.     HeaderText="ID"
  101.     ItemStyle-Width="50">
  102.     <ItemTemplate>
  103.       <asp:Label Runat="Server"
  104.         Text='<%# Eval("BookID") %>'/>
  105.     </ItemTemplate>
  106.   </asp:TemplateField>
  107.  
  108.   <asp:TemplateField
  109.     HeaderText="Title"
  110.     ItemStyle-Width="350">
  111.     <ItemTemplate>
  112.       <asp:Label Runat="Server"
  113.         Text='<%# Eval("BookTitle") %>'/>
  114.     </ItemTemplate>
  115.  </asp:TemplateField>
  116.  
  117.  <asp:TemplateField
  118.     HeaderText="Price"
  119.     ItemStyle-HorizontalAlign="Right"
  120.     ItemStyle-Width="60">
  121.     <ItemTemplate>
  122.       <asp:Label Runat="Server"
  123.         Text='<%# String.Format("{0:N}", Eval("BookPrice")) %>'/>
  124.     </ItemTemplate>
  125.  </asp:TemplateField>
  126.  
  127. <asp:TemplateField
  128.     HeaderText="Ui"
  129.     ItemStyle-Width="60">
  130.     <ItemTemplate>
  131.       <asp:Label Runat="Server"
  132.         Text='<%# Eval("ui") %>'/>
  133.     </ItemTemplate>
  134.     <ItemTemplate>
  135.       <asp:Label Runat="Server"
  136.         Text='<%# Eval("Ui") %>'
  137.         Width="25" Font-Size="9pt" Style="text-align:right"/>
  138.     </ItemTemplate>    
  139.   </asp:TemplateField>
  140.  
  141.   <asp:TemplateField
  142.     HeaderText="Edit"
  143.     ItemStyle-Width="175"
  144.     FooterStyle-BackColor="#E0E0E0">
  145.     <ItemTemplate>
  146.       <asp:Button Text="Remove" CommandName="Delete" Runat="Server"
  147.         Font-Size="10pt" Width="75"/>
  148.     </ItemTemplate>
  149.     <FooterTemplate>
  150.       <asp:Button Text="Checkout »" OnClick="Submit_Form" Runat="Server"
  151.         Font-Size="10pt" Width="75" Style="margin-top:5px"/>
  152.     </FooterTemplate>
  153.   </asp:TemplateField>
  154.  
  155.  </Columns>
  156. </asp:GridView>
  157.  
  158. </asp:Content>
Nov 16 '09 #2
Frinavale
9,735 Recognized Expert Moderator Expert
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
Nov 16 '09 #3
Frinavale
9,735 Recognized Expert Moderator Expert
I did run across this question before.
I've merged the questions together.

-Frinny
Nov 16 '09 #4
tsubasa
64 New Member
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:
Expand|Select|Wrap|Line Numbers
  1. <asp:TemplateField 
  2.     ItemStyle-Width="50"> 
  3.     <ItemTemplate> 
  4.       <asp:CheckBox UnChecked='<%# Eval("id") %>' Runat="Server"/> 
  5.     </ItemTemplate> 
  6.   </asp:TemplateField> 
Here is where I have associated the ID in the WishList table. Is this correct so far?

-Gabe
Nov 16 '09 #5
Frinavale
9,735 Recognized Expert Moderator Expert
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
Nov 17 '09 #6
tsubasa
64 New Member
Ok, I have removed the code and have written it this way:
Expand|Select|Wrap|Line Numbers
  1.  <asp:CheckBoxField
  2.     HeaderText="ID"
  3.     DataField="ID"
  4.     ItemStyle-HorizontalAlign="Center"/>
Will this work with a FindControl loop?

-Gabe
Nov 17 '09 #7
tsubasa
64 New Member
Here is what I have changed, since I want the records to come from a dynamic source or column such as ID.
Expand|Select|Wrap|Line Numbers
  1. <asp:TemplateField HeaderText="ID" InsertVisible="False">
  2.       <ItemTemplate>
  3.          <asp:CheckBox ID="id" runat="server" Text='<%# Eval("id") %>' />
  4.        </ItemTemplate>
  5.     </asp:TemplateField>
Then what I have done is used the following code to loop through the selected checkboxes.
Expand|Select|Wrap|Line Numbers
  1. Sub Submit_Form (Src As Object, Args As EventArgs)
  2.  
  3. Dim Grd As String = "GridView Items Checked:<br />"
  4. For Each gvr As GridViewRow In ShopCartGrid.Rows
  5.   Dim chk As CheckBox = DirectCast(gvr.FindControl("id"), CheckBox)
  6.   If chk.Checked Then
  7.     Grd += (chk.Text + "<br />")
  8.   End If
  9. Next
  10. GrdLiteral.Text = Grd
  11.  
  12.  
  13. End Sub

I added this at the bottom of my page to view my data
Expand|Select|Wrap|Line Numbers
  1. <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
Nov 18 '09 #8
Frinavale
9,735 Recognized Expert Moderator Expert
Sounds like you got it to work!
Congrats :)

-Frinny
Nov 18 '09 #9
tsubasa
64 New Member
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!
Nov 18 '09 #10
Frinavale
9,735 Recognized Expert Moderator Expert
In your submit_form method, when your're the CheckBox.Checked 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...

Expand|Select|Wrap|Line Numbers
  1. Sub Submit_Form (Src As Object, Args As EventArgs)
  2.  
  3. Dim Grd As String = "GridView Items Checked:<br />"
  4. For Each gvr As GridViewRow In ShopCartGrid.Rows
  5.   Dim chk As CheckBox = DirectCast(gvr.FindControl("id"), CheckBox)
  6.   If chk.Checked Then
  7.     'Grd += (chk.Text + "<br />")
  8.  
  9.     'Here, retrieve the ID of the item...hopefully you have an ID...
  10.     'say your the ID of your item is stored in the last cell in the GridView
  11.     'you would retrieve it like:
  12.    Dim itemID As Integer
  13.    Integer.TryParse(gvr.Cells(gvr.Cells.Count - 1).Text, itemID)
  14.  
  15.     'Now that you know the ItemID you can do Stuff
  16.  
  17.     'If you need more than just the ItemID you can use the same
  18.     'method to retrieve information from the GridViewRow...the thing is
  19.     'that you need to know what cell that the information exists in.
  20.  
  21.    'That is why I recommend using the DataSource for the GridView instead
  22.    'Because if you're using the DataSource (and it's a table) then you can
  23.    'more easily access the data (because you can use column names).
  24.    'For example, your data source was a DataTable stored in a variable
  25.    'named _theWishListDataSource:
  26.  
  27.    'Grabbing the rows in the data source with the ItemID:
  28.    Dim selectedRows() As DataRow = _
  29.         _theWishListDataSource.Select('ID='" + itemID.ToString + "'")
  30.    If selectedRows IsNot Nothing AndAlso selectedRows.Count >0 Then
  31.      Dim theDataRow As DataRow = selectedRows(0)
  32.      Dim moreInfo As String =  theDataRow.Item("columnName")
  33.     '......
  34.    End If
  35.  
  36.   End If
  37. Next
  38. End Sub

Hope this makes sense.

-Frinny
Nov 19 '09 #11
tsubasa
64 New Member
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
Nov 20 '09 #12
tsubasa
64 New Member
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
Expand|Select|Wrap|Line Numbers
  1. <%@ Page MasterPageFile="eCommerce.master" Language="vb" Debug="True"%>
  2. <%@ Import Namespace="System.Data.OleDb" %>
  3. <%@ Import Namespace="System.Drawing" %>
  4.  
  5. <SCRIPT Runat="Server">
  6.  
  7. Sub Page_Load
  8.  
  9.   If Session("LoggedIn") <> True Then
  10.   Response.Redirect("Loginwl.aspx")
  11.   End If
  12.  
  13.   If Not Page.IsPostBack Then
  14.     Dim User As String
  15.     TheAccountLabel.Text = Session("LoginName")
  16.   End If
  17.  
  18. End Sub
  19.  
  20. Sub Get_Rows (Src As Object, Args As SqlDataSourceStatusEventArgs)
  21.  
  22.   If Args.AffectedRows = 0 Then
  23.     NoItemsMessage.Visible = True
  24.   End If
  25.  
  26. End Sub
  27.  
  28. Sub View_Details (Src As Object, Args As CommandEventArgs)
  29.  
  30.   Response.Redirect("Details.aspx?BookID=" & Args.CommandName)
  31.  
  32. End Sub
  33.  
  34.  
  35. Sub Submit_Form (Src As Object, Args As EventArgs)
  36.  
  37. Dim Grd As String
  38. For Each gvr As GridViewRow In ShopCartGrid.Rows
  39.   Dim chk As CheckBox = DirectCast(gvr.FindControl("id"), CheckBox)
  40.   If chk.Checked Then
  41.     Grd += (chk.Text + "<br />")
  42.   End If
  43. Next
  44. GrdLiteral.Text = Grd
  45.  
  46. End Sub
  47.  
  48. </SCRIPT>
  49.  
  50. <asp:Content id="WishList" ContentPlaceHolderID="CONTENT" Runat="Server">
  51.  
  52. <asp:Label Text="Wish List for" Font-Size="14pt" ForeColor="#990000" 
  53. Runat="Server"/>
  54. <br/>
  55. <table border="0">
  56. <tr>
  57.   <td><asp:Label id="TheAccountLabel" Font-Size="12pt" ForeColor="#990000" Runat="Server"/></td>
  58. </tr>
  59. </table>
  60.  
  61. <asp:Label id="NoItemsMessage" Runat="Server"
  62.   Text="Zero Items!" EnableViewState="False" Visible="False"
  63.   Width="180" Height="40" BackColor="#E0E0E0" ForeColor="#990000"
  64.   BorderStyle="Solid" BorderWidth="1" BorderColor="#C0C0C0" 
  65.   Style="margin-top:10px; padding:15px"/>
  66.  
  67. <asp:Panel Width="550" Runat="Server"
  68. ForeColor="#990000" HorizontalAlign="Right">
  69.   <asp:Label id="ErrMessage" Text=" " EnableViewState="False" Runat="Server"/>
  70. </asp:Panel>
  71.  
  72. <asp:AccessDataSource id="ShopCartSource" Runat="Server"
  73.   DataFile="/Databases/BooksDB.mdb"
  74.   OnSelected="Get_Rows"
  75.  
  76.   SelectCommand="SELECT * FROM WishList WHERE TheAccount = TheAccountLabel ORDER BY BookId"
  77.  
  78.     DeleteCommand="DELETE FROM WishList
  79.                  WHERE TheAccount=@TheAccount AND BookID=@BookID"
  80. >
  81.   <SelectParameters>
  82.     <asp:ControlParameter Name="TheAccount" ControlId="TheAccountLabel"
  83.     PropertyName="Text"/>
  84.   </SelectParameters>
  85.   <DeleteParameters>
  86.     <asp:ControlParameter Name="TheAccount" ControlId="TheAccountLabel"
  87.     PropertyName="Text"/>
  88.   </DeleteParameters>
  89.  
  90. </asp:AccessDataSource>
  91.  
  92. <asp:GridView id="ShopCartGrid" DataSourceID="ShopCartSource" Runat="Server"
  93.   AutoGenerateColumns="False"
  94.   DataKeyNames="TheAccount, BookID"
  95.   Cellpadding="3"
  96.   ShowFooter="True"
  97.   HeaderStyle-BackColor="#990000"
  98.   HeaderStyle-ForeColor="#FFFFFF"
  99.   EditRowStyle-BackColor="#E0E0E0">
  100.  
  101.    <Columns>
  102.  
  103.   <asp:TemplateField
  104.     HeaderText="BookID"
  105.     ItemStyle-Width="50">
  106.     <ItemTemplate>
  107.       <asp:Label Runat="Server"
  108.         Text='<%# Eval("BookID") %>'/>
  109.     </ItemTemplate>
  110.   </asp:TemplateField>
  111.  
  112.   <asp:TemplateField
  113.     HeaderText="Title"
  114.     ItemStyle-Width="350">
  115.     <ItemTemplate>
  116.       <asp:Label Runat="Server"
  117.         Text='<%# Eval("BookTitle") %>'/>
  118.     </ItemTemplate>
  119.  </asp:TemplateField>
  120.  
  121.  <asp:TemplateField
  122.     HeaderText="Price"
  123.     ItemStyle-HorizontalAlign="Right"
  124.     ItemStyle-Width="60">
  125.     <ItemTemplate>
  126.       <asp:Label Runat="Server"
  127.         Text='<%# String.Format("{0:N}", Eval("BookPrice")) %>'/>
  128.     </ItemTemplate>
  129.  </asp:TemplateField>
  130.  
  131. <asp:TemplateField
  132.     HeaderText="Ui"
  133.     ItemStyle-Width="60">
  134.     <ItemTemplate>
  135.       <asp:Label Runat="Server"
  136.         Text='<%# Eval("ui") %>'/>
  137.     </ItemTemplate>
  138.     <ItemTemplate>
  139.       <asp:Label Runat="Server"
  140.         Text='<%# Eval("Ui") %>'
  141.         Width="25" Font-Size="9pt" Style="text-align:right"/>
  142.     </ItemTemplate>    
  143.   </asp:TemplateField>
  144.  
  145.   <asp:TemplateField
  146.     HeaderText="Check All">
  147.     <ItemTemplate>
  148.       <asp:CheckBox ID="id" Runat="Server"/>
  149.     </ItemTemplate>
  150.  </asp:TemplateField>
  151.  
  152.   <asp:TemplateField
  153.     ItemStyle-Width="120"
  154.     FooterStyle-BackColor="#E0E0E0">
  155.     <ItemTemplate>
  156.       <asp:Button Text="Remove" CommandName="Delete" Runat="Server"
  157.         Font-Size="10pt" Width="75"/>
  158.       <asp:LinkButton Text="Details" Runat="Server"
  159.         OnCommand="View_Details"
  160.         CommandName='<%# Eval("BookID") %>'/>
  161.     </ItemTemplate>
  162.     <FooterTemplate>
  163.       <asp:Button Text="Checkout »" OnClick="Submit_Form" Runat="Server"
  164.         Font-Size="10pt" Width="75" Style="margin-top:5px"/>
  165.     </FooterTemplate>
  166.   </asp:TemplateField>
  167.  
  168.  </Columns>
  169. </asp:GridView>
  170.  
  171. <asp:Label id="GrdLiteral" Runat="Server"
  172.  
  173.   ForeColor="#0000FF"/>
  174.  
  175.  
  176. </asp:Content>
-Tsu
Nov 30 '09 #13
Frinavale
9,735 Recognized Expert Moderator Expert
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:
Expand|Select|Wrap|Line Numbers
  1.     Protected Sub MyGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles MyGridView.RowDataBound
  2.  
  3.   If e.Row.RowType = DataControlRowType.Header Then
  4.     Dim checkAllCkbxs As CheckBox = Ctype(e.Row.FindControl("checkAllCheckbox"), CheckBox)
  5.     If checkAllCkbxs IsNot Nothing
  6.       checkAllCkbxs.Attributes.Add("onclick","checkAllCheckBoxes(this,'"+MyGridView.ClientID+"');")
  7.     End If
  8.   End If
  9. End Sub
  10.  
The JavaScript function "checkAllCheckBoxes" 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:

Expand|Select|Wrap|Line Numbers
  1. function checkAllCheckBoxes(checkAllCheckBoxElement, gridViewClientID)
  2.   var gridViewElement = document.getElementById(gridViewClientID);
  3.   var checked = checkAllCheckBoxElement.checked;
  4.  
  5.   if(gridViewElement.rows.length > 0){
  6.     for(i = 0; i < gridViewElement.rows.length; i++)
  7.     {
  8.       cell = gridViewElement.rows[i].cells[0]; //<--the cell the checkbox is in
  9.       for(j = 0; j < cell.childNotes.length; j++)
  10.       { //looping through the childNodes of the cell looking for the checkbox
  11.         if(cell.childNodes[j].type == "checkbox"){
  12.           cell.childNodes[j].checked = checked;
  13.         }
  14.     }
  15.   }
-Frinny
Nov 30 '09 #14
tsubasa
64 New Member
Thanks Frinny! I will work on this.

-Tsu
Nov 30 '09 #15
tsubasa
64 New Member
Hello Frinny!

I have managed to work out the checkall and uncheck all script. See below:
Expand|Select|Wrap|Line Numbers
  1. Private Sub ToggleCheckState(ByVal checkState As Boolean)
  2.     ' Iterate through the ShopCartGrid.Rows property
  3.     For Each row As GridViewRow In ShopCartGrid.Rows
  4.         ' Access the CheckBox
  5.         Dim cb As CheckBox = row.FindControl("id")
  6.         If cb IsNot Nothing Then
  7.             cb.Checked = checkState
  8.         End If
  9.     Next
  10. End Sub
  11.  
  12.  
  13. Protected Sub CheckAll_Click(sender As Object, e As EventArgs) _
  14.     Handles CheckAll.Click
  15.  
  16.     ToggleCheckState(True)
  17. End Sub
  18.  
  19. Protected Sub UncheckAll_Click(sender As Object, e As EventArgs) _
  20.     Handles UncheckAll.Click
  21.  
  22.     ToggleCheckState(False)
  23. End Sub
And as we have converse in our previous postings. I have managed to write the BookID that are selected manually or with the checkall. What I need help in is trying to figure out how I can write the BookID, BookTitle, BookPrice, Ui from the records selected in the GridView to a another table called ShopCart with the same fields "BookID, BookTitle, BookPrice, Ui.

-Tsu
Dec 14 '09 #16
tsubasa
64 New Member
Hi Frin!

I have been looking over the code and I want to try and figure this out on my own. I will get back with you brother if I can't make it happen.

-Tsu
Dec 15 '09 #17
Frinavale
9,735 Recognized Expert Moderator Expert
:) I think that you should have enough knowledge to get this one.
Let me know if you get stuck on anything specific :)

-Frinny
Dec 15 '09 #18
tsubasa
64 New Member
Hi Frinny!

Sorry to bug you brother, but I got stuck. If you can, show me how you would insert the selected checkbox records and the associated datat into another table with the same fields called ShopCart. Thanks!

-Tsu
Dec 17 '09 #19
Frinavale
9,735 Recognized Expert Moderator Expert
It's pretty much the same thing as post number 11 in this thread.

Loop through all of the rows in your GridView and for the ones that are checked implement code that retrieves data from that row and moves/merges it into the other table.

What do you have so far for this moving process?

-Frinny
Dec 17 '09 #20
tsubasa
64 New Member
This is what I have so far, but when I attempt this I automatically get this error. "Object reference not set to an instance of an object"
Expand|Select|Wrap|Line Numbers
  1. Sub Submit_Form (Src As Object, Args As EventArgs)
  2.  
  3. Dim Grd As String
  4. For Each gvr As GridViewRow In ShopCartGrid.Rows
  5.   Dim chk As CheckBox = DirectCast(gvr.FindControl("id"), CheckBox)
  6.   If chk.Checked Then
  7.     Grd = (chk.Text)
  8.   End If
  9.  
  10.   Dim FVBookID As Label = FormViewDisplay.FindControl("BookID")
  11.   Dim FVBookTitle As Label = FormViewDisplay.FindControl("BookTitle")
  12.   Dim DBConnection As OleDbConnection
  13.   Dim DBCommand As OleDbCommand
  14.   Dim SQLString As String
  15.   Dim SQLAddString As String
  16.  
  17.   DBConnection = New OleDbConnection( _
  18.     "Provider=Microsoft.Jet.OLEDB.4.0;" & _
  19.     "Data Source=" & Server.MapPath("/Databases/BooksDB.mdb"))
  20.   DBConnection.Open()
  21.  
  22. '-----------Check for Duplicate records first --------------------
  23.   SQLString = "SELECT Count(*) FROM ShopCart " & _
  24.               "WHERE OrderNumber = '" & Session("OrderNumber") & "' " & _
  25.               "AND BookID = '" & FVBookID.Text & "'"
  26.   DBCommand = New OleDbCommand(SQLString, DBConnection)
  27.   If DBCommand.ExecuteScalar() = 0 Then
  28. '--------------Add Records to Shopcart table ----------------------
  29.  
  30.      SQLAddString = "INSERT INTO ShopCart (OrderDate, BookID, BookTitle) WHERE BookID = 'Grd' VALUES (Today, FVBookID.Text, FVBookTitle.Text)"
  31.     DBCommand = New OleDbCommand(SQLAddString, DBConnection)
  32.     DBCommand.ExecuteNonQuery()
  33.  
  34.  
  35.   End If
  36. Next
  37. DBConnection.Close()
  38.  
  39. End Sub
If you can help me solve, I would really appreciate it. Thanks Frinny!

-Tsu
Dec 17 '09 #21
Frinavale
9,735 Recognized Expert Moderator Expert
Somewhere you are attempting to use something that has not been instantiated yet. You get a null reference exception ("Object reference not set to an instance of an object") when you try to use something that does not exist. Make sure that your objects have been instantiated (using the keyword "new" to instantiate them). If your objects are being instantiated by some other code, make sure that they exist by testing if they are nothing before you try to use them.

Here's an example of checking if an object has been instantiated in VB.NET:
Expand|Select|Wrap|Line Numbers
  1. If myObject IsNot Nothing Then
  2.   'then the object exists.
  3. Else
  4.  'then the object does not exist.
  5. End If
  6.  
Or you could use:
Expand|Select|Wrap|Line Numbers
  1. If myObject Is Nothing Then
  2.  'then the object does not exist.
  3. Else
  4.   'then the object exists.
  5. End If
  6.  
In your case, make sure that anything retrieved from the database exists before you attempt to use it.

-Frinny
Dec 21 '09 #22

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: P | last post by:
Hello, I am having a difficult time updating a record via a stored procedure using the gridview and sqldatasource. I cannot seem to be able to find a way to set everything up so that I can pass...
6
by: Terry | last post by:
Good morning! How do I determine which SELECT button was clicked in a GridView? The multiple SELECT buttons will be used for an application approval process. Thank you in advance for your...
1
by: K B | last post by:
Hi. I have a gridview with sqldatasource, etc. For the grid, I also have a search textbox. If the user needs to filter the records, I want to dynamically adjust the SELECT statement for the...
3
by: dbarker1 | last post by:
Hello All, I am developing a web front end using the standard datagrid in the 1.1 framework. Currently it allows users to navigate through records 20 at a time via previous and next buttons. ...
1
by: David W | last post by:
I am looking for a gridview example for including a multi-select box - either for in-line editing or master-detail records. For example, I have 3 tables: Product, Category, and ProductCategory...
1
by: Mr. SweatyFinger | last post by:
I have a gridview and a sqlserver datasource. I also have a dropdownlist of countries. The gridview displays a bunch of crap about whatever country is selected in the countries dropdownlist I...
4
by: cmrhema | last post by:
hello I am using a gridview to display records. I have set page index for the grid. I have populated the gridview. After every 10 records I will move to the next page. All these works fine. ...
1
by: BlackMustard | last post by:
hi all, i am currently using the following union select statement to select records from two of my tables to a gridview in asp.net: SELECT ConcertName AS Name, ConcertDate AS Date, ConcertTime AS...
1
by: rbrowning1958 | last post by:
Hello, I wonder whether someone can explain to me how data is fetched from a database server when using ASP.NET 2.0's gridview with paging enabled? My SQL DataSource has a simple "select * from...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.