Welcome to Dream.In.Code
Become an Expert!

Join 150,402 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 966 people online right now. Registration is fast and FREE... Join Now!




CheckBoxes in GridView

 
Reply to this topicStart new topic

CheckBoxes in GridView

PsychoCoder
20 Mar, 2008 - 05:13 AM
Post #1

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 9,483



Thanked: 161 times
Dream Kudos: 9075
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
In my GridView I have an ItemTemplate for the items in the grid, one of the items is a CheckBox named cbSelect, here is how that is created


CODE

<ItemTemplate>
           <table style="width: 100%;" cellpadding="0" cellspacing="0" border="0">
                       <tr style="line-height: 150%; background-color: #DDE9EE; font-size: 11px;" onmouseover="this.style.backgroundColor='#E9F0F3';"
                                        onmouseout="this.style.backgroundColor='#DDE9EE';">
                           <!-- CHKB -->
                           <td class="tdAltL" style="text-align: left; width:25px;">
                                     <asp:CheckBox ID="cbSelect" runat="server" />                                            
                           </td>
                           <!-- QNUM -->
                           <td class="tdAltM" style="text-align: left; width:375px;">
                                    <strong><%#Eval("QID") %></strong><br />
                                    <a style="color: blue;" href="http://www.qmetro.com/<%#Eval("QID") %>" target="_blank">
                                     <%#Eval("QName") %></a>
                           </td>
                           <!-- LOC  -->
                           <td class="tdAltM" style="text-align: center; width:75px;">
                                      <%#Eval("QLocation") %>
                            </td>
                           <!-- EXP  -->
                          <td class="tdAltM" style="text-align: center; width:75px;">
                                     <%#Eval("QExpDate") %>
                         </td>
                         <!-- IMG  -->
                        <td class="tdAltR" style="text-align: center; width: 70px;">
                                    <span style="position: relative; top: 0px; left: 0px;">
                                   <img src="http://images.qmetro.com/cropped/64x48/<%#Eval("QImage") %>_thm.jpg" width="64"
                                                    height="48" alt=""></span>
                      </td>
                </tr>
         </table>
</ItemTemplate>



So as you can clearly see cbSelect does exist. I then have 2 methods, one for getting the checked items in the list (to hold them during paging) and one to repopulate the checked items if the user goes back to that page. To get the checked items I have


csharp

private void GetCheckedItems()
{
//instantiate new ArrayList to hold our checked items
checkedItems = new ArrayList();
//loop through each row in the GridView
foreach (GridViewRow row in gvUserQs.Rows)
{
//get the index of the current CheckBox
chkBoxIndex = (long)gvUserQs.DataKeys[row.RowIndex].Value;
CheckBox chk = (CheckBox)gvUserQs.FindControl("cbSelect");

//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) //<-- Exception happens here
{
bxChkd = true;
//see if the current value is in the Session, if not add it
if (!(checkedItems.Contains(chkBoxIndex)))
{
//add to the list
checkedItems.Contains(chkBoxIndex.ToString());
}
}
else
{
//remove from list since it's unchecked
checkedItems.Remove(chkBoxIndex.ToString());
}
}
//update Session with the list of checked items
Session["CheckedItems"] = chkdItems;
}



And to repopulate I have


csharp

private void RePopulateCheckedItems()
{
checkedItems = new ArrayList();
checkedItems = (ArrayList)Session["CheckedItems"];

//make sure we have selected items
if (!(checkedItems == null))
{
foreach (GridViewRow row in gvUserQs.Rows)
{
chkBoxIndex = (long)gvUserQs.DataKeys[row.RowIndex].Value;

if (checkedItems.Contains(chkBoxIndex))
{
CheckBox chk = (CheckBox)gvUserQs.FindControl("cbSelect");
chk.Checked = true;
}
results = (string[])checkedItems.ToArray(typeof(string));
//now create our delimited string
chkdItems = string.Join(",", results);
}
}
}



Then in my GridView's OnPageIndexChanging Event I call both methods, 1 before the page index changes, and 1 after, like so


csharp

protected void gvUserQs_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//get our list of selected Q's
GetCheckedItems();
gvUserQs.PageIndex = e.NewPageIndex;
BindGridView();
RePopulateCheckedItems();
}



The page loads just fine, but when I go to page I get a NullReferenceException in the line if (chk.Checked) in the GetCheckedItems method.

My CheckBox exists so why the exception?
User is offlineProfile CardPM
+Quote Post

PsychoCoder
RE: CheckBoxes In GridView
20 Mar, 2008 - 05:37 AM
Post #2

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 9,483



Thanked: 161 times
Dream Kudos: 9075
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
I figured out the problem (but that now causes another problem). I had to change mny method to look like


csharp

private void GetCheckedItems()
{
//instantiate new ArrayList to hold our checked items
checkedItems = new ArrayList();
//loop through each row in the GridView
foreach (GridViewRow row in gvUserQs.Rows)
{
//get the index of the current CheckBox
chkBoxIndex = (long)gvUserQs.DataKeys[row.RowIndex].Value;
//here I was using gvUserQs when I needed to be using row
CheckBox chk = (CheckBox)row.FindControl("cbSelect");
//add ArrayList to ViewState is if doesnt already exist
if (!(Session["CheckedItems"] == null))
{
checkedItems = (ArrayList)Session["CheckedItems"];
}

//now see if the current CheckBox is checked
if (chk.Checked)
{
bxChkd = true;
//see if the current value is in the ViewState, if not add it
if (!(checkedItems.Contains(chkBoxIndex)))
{
//add to the list
checkedItems.Contains(chkBoxIndex.ToString());
}
}
else
{
//remove from list since it's unchecked
checkedItems.Remove(chkBoxIndex.ToString());
}
}
//update ViewState with the list of checked items
Session["CheckedItems"] = chkdItems;
}



Now the problem is when I go back to the new page I get an


QUOTE

Exception Details: System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Collections.ArrayList'.



In this block of code


csharp

//add ArrayList to ViewState is if doesnt already exist
if (!(Session["CheckedItems"] == null))
{
checkedItems = (ArrayList)Session["CheckedItems"]; //<-- Here
}



Now to my eye it looks like this code should work, what am I missing?
User is offlineProfile CardPM
+Quote Post

PsychoCoder
RE: CheckBoxes In GridView
20 Mar, 2008 - 05:59 AM
Post #3

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 9,483



Thanked: 161 times
Dream Kudos: 9075
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
Update: got rid of all errors (I had the wrong variable at the bottom of the GetCheckedItems method), but the RePopulateCheckedItems isn't working, it isn't checking the items that were initially checked on a page, and it doesn't appear to be adding checked items to the ArrayList (getCheckedItems method)
User is offlineProfile CardPM
+Quote Post

PsychoCoder
RE: CheckBoxes In GridView
20 Mar, 2008 - 03:49 PM
Post #4

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 9,483



Thanked: 161 times
Dream Kudos: 9075
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
Well I believe I got it adding checked items to the ArrayList, but now I'm getting inconsistent results. Sometimes when I go back to a page the items I checked are indeed checked again, but the next time I go they aren't. Let me show all the code and explain what it is doing.


First my page level globals


csharp

private string chkdItems = string.Empty;
private string chkBoxIndex = string.Empty;
private bool bxChkd = false;
private string[] results;
private ArrayList checkedItems;
protected CheckBox chk;



Now this first method is used for cycling through the items in the GridView (for that page number) and adding each checked item to an ArrayList, the ArrayList is then added to the Session["CheckedItems"] so I can keep track of them through the paging process


csharp

private void GetCheckedItems()
{
//instantiate new ArrayList to hold our checked items
checkedItems = new ArrayList();
//loop through each row in the GridView
foreach (GridViewRow row in gvUserQs.Rows)
{
//get the index of the current CheckBox
chkBoxIndex = (string)gvUserQs.DataKeys[row.RowIndex].Value.ToString();
chk = (CheckBox)row.FindControl("cbSelect");
//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)
{
bxChkd = true;
//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;
}



This next method is used for rechecking items when/if the user pages back to page they've already been to


csharp

private void RePopulateCheckedItems()
{
checkedItems = new ArrayList();
checkedItems = (ArrayList)Session["CheckedItems"];

//make sure we have selected items
if (!(checkedItems == null))
{
foreach (GridViewRow row in gvUserQs.Rows)
{
chkBoxIndex = (string)gvUserQs.DataKeys[row.RowIndex].Value.ToString();

if (checkedItems.Contains(chkBoxIndex))
{
chk = (CheckBox)row.FindControl("cbSelect");
chk.Checked = bxChkd;
}
results = (string[])checkedItems.ToArray(typeof(string));
//now create our delimited string
chkdItems = string.Join(",", results);
}
}
}



I call them both in the GridView's PageChanging Event, along with rebinding the grid


csharp

protected void gvUserQs_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//get our list of selected Q's
GetCheckedItems();
gvUserQs.PageIndex = e.NewPageIndex;
BindGridView();
RePopulateCheckedItems();
}



Anyone got an ideas on why this is happening?

This post has been edited by PsychoCoder: 20 Mar, 2008 - 04:49 PM
User is offlineProfile CardPM
+Quote Post

Jayman
RE: CheckBoxes In GridView
20 Mar, 2008 - 05:27 PM
Post #5

Student of Life
Group Icon

Joined: 26 Dec, 2005
Posts: 7,327



Thanked: 66 times
Dream Kudos: 500
Expert In: Everything

My Contributions
Are you using the paging properties of the GridView or using the browser back button?
User is offlineProfile CardPM
+Quote Post

PsychoCoder
RE: CheckBoxes In GridView
20 Mar, 2008 - 05:34 PM
Post #6

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 9,483



Thanked: 161 times
Dream Kudos: 9075
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
Paging property of the GridView
User is offlineProfile CardPM
+Quote Post

Jayman
RE: CheckBoxes In GridView
20 Mar, 2008 - 06:35 PM
Post #7

Student of Life
Group Icon

Joined: 26 Dec, 2005
Posts: 7,327



Thanked: 66 times
Dream Kudos: 500
Expert In: Everything

My Contributions
Are you using Custom Paging?

You shouldn't need to handle anything in the grid when using the paging property. The grid should be updating automatically with the correct values.
Is this not the case?
User is offlineProfile CardPM
+Quote Post

PsychoCoder
RE: CheckBoxes In GridView
20 Mar, 2008 - 06:39 PM
Post #8

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 9,483



Thanked: 161 times
Dream Kudos: 9075
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
No, I lose the selected items when I page. So I came up with this solution, but it doesn't work consistently and I cant figure out why
User is offlineProfile CardPM
+Quote Post

Jayman
RE: CheckBoxes In GridView
21 Mar, 2008 - 06:36 PM
Post #9

Student of Life
Group Icon

Joined: 26 Dec, 2005
Posts: 7,327



Thanked: 66 times
Dream Kudos: 500
Expert In: Everything

My Contributions
How are you binding the GridView? Post the code please.

I use GridViews quite often, especially at work, and the GridView should be refreshing the data in the grid when you use the paging features.

User is offlineProfile CardPM
+Quote Post

PsychoCoder
RE: CheckBoxes In GridView
21 Mar, 2008 - 07:51 PM
Post #10

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 9,483



Thanked: 161 times
Dream Kudos: 9075
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
It is refreshing the data, I'm wanting to keep track of the items a user selects while they're paging. Then if they page back to a page they've been to I want it to check the items they had checked on that page. I think I have it working now, found a couple small errors in my code.
User is offlineProfile CardPM
+Quote Post

Jayman
RE: CheckBoxes In GridView
22 Mar, 2008 - 08:50 AM
Post #11

Student of Life
Group Icon

Joined: 26 Dec, 2005
Posts: 7,327



Thanked: 66 times
Dream Kudos: 500
Expert In: Everything

My Contributions
Oh, I see what you are trying to do now. Sorry I misunderstand what you were originally saying.

Glad to hear that you were able to resolve the problem.
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/9/09 07:14PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month