Library tutorials & articles

Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid/GridView - Part 2: Maintaining CheckBox State Acr

Introduction

In my previous article Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid (i.e. HotMail & Yahoo) that I had written about two years ago, I demonstrated how one could multi-select checkboxes in a DataGrid page, and then cumulatively deleted them all. Initially, I did not make use of any paging with that example, but rather left it rudimentary simply to illustrate how to multi-select a series of checkboxes and then delete them all in one pass. But the limitation there was that this worked on a per-page basis, so once you selected any given checkboxes in that page, then paged to the next, and finally returned to the previous page, all your selections were reset.

Most of the web sites that offer this type of functionality, including AOL Web Mail, display the same abovementioned effect. You're allow only to select and delete whatever checkboxes are presented on that page alone, before proceeding to the next. Having said that, we’ll take care of this in this article, and not only be able to select and delete across pages in one nice batch delete, but also, and here is the cool part, in this article I’ll show you how to repopulate the given page with the precise checkboxes that were selected earlier - even if you go back and check something new in that page.

To make this all come about I utilize Session State to store my checkboxed values that comprise of the DataGrid's DataKeyField and, use its DataKeys properties to sift through and grab the selected checkbox values and repopulate the appropriate checkboxes in the given page. I have also implemented caching using Session State for added performance and scalability, alongside bi-directional column sorting. Therefore, by means of the DataGrid's DataKeys property, your checkbox selections will persist across pages even sorting in any direction as well. Pretty awesome! And furthermore, the use of Session State helps prevent multiple users from getting data crisscrossed.

Typically, there are other methodologies for accomplishing the same end result. One way I've come across was by means of wiring up each CheckBox with an event handler using OnCheckedChanged. Thereby, each time a given checkbox is selected the page get's posted back and stores the appropriate values in any given state capturing method. However, although this technique works, it leaves much to be desired it terms of smoothness and presentation. My method performs all actions on a page by page level, and only when paging occurs is when it'll do what's it supposed to do. In turn, you have a smooth application with non of the constant post back effect for each checkbox selection.

Moving forward, for brevity I won’t reiterate the techniques discussed in Part 1 of this article, but rather I’ll begin by listing the code in its entirety (both the main page and its code-behind), then discuss the logic and code responsible for the effect. Incidentally, as the original code was written in C#, most readers typically requested from me the VB version, so in light of such, the code presented here will all be in VB.

Comments

  1. 10 Apr 2008 at 11:15

    hi all, 

    i faced the same problem, but i have paging in the grid view, so my problem is

    when user checks one record in a page and goes to the next page and selects some records there, when he returns to the previous page we need to keep the checked state of whatever records he had checked earlier. When he is finished checking through the pages, he needs a list of records he has checked to delete them form database

    iam a new in this forum, i need any one help me as i searched alot and i didn't find any solution

    thanks

  2. 01 Jun 2007 at 21:23

    Hi Dimitrios,

    Thanks for such a great tutorial. It works for me. Keep it up.

    Oleg

  3. 13 May 2007 at 14:42

    sir,I am new to this gridview.I want to delete checked rows from my database.In the grid view i have 4 columns,and compan name is the first column.I want to take the value of the company name column and use it in delete query.I am using the following code,but after executing the line string cname=row.cells[0].text,cname is showing the null value.Why?

    my code under delete buttonclick event is this

       
            foreach(GridViewRow row in Exp
    SummaryGrid.Rows)
               
            {
               string  cname = row.cells[0].text;
                string del = "delete from expsummary where company=" + cname;
                CheckBox cb = (CheckBox)row.Cells[4].Controls[1];
                if (cb.Checked==true)
                {
                    SqlCommand delsql = new SqlCommand();
                    delsql.Connection = conn;
                    delsql.CommandText = del;
                    delsql.CommandType = CommandType.Text;
                    SqlDataAdapter da = new SqlDataAdapter(del, conn);
                    da.DeleteCommand = delsql;
                    DataSet ds2 = new DataSet();
                    da.Update(ds2, "exp
    summary");
                }


            }

































  4. 02 May 2007 at 16:45

    Do you have the C# version of this code somewhere? I just came across this situation with check boxes and paging. I'm using VS2005C# and my code has check boxes on each row and I'm iterating thru them to check if they are checked but if you select a few on the first page and them switch to the second page of the gridview then switch back the gridview loses what items are checked. I could use some help converting your VB into C# 2005. 

  5. 23 Oct 2006 at 18:25

    Hey Thanks! Good suggestions. Now the question remains in getting to those :-) As for .NET 2.0, this article has it already included.

    Thanks again!

  6. 19 Jul 2006 at 08:15

    Having tried your solution I was impressed by the ease with which it worked and it started me thinking of extensions to the principle.

    Can I request that you extend the sample code with some additional features?

    Firstly add an option to take all the selected records and then insert them into another file. One possible use of this would be to create a shopping 'wish list'.

    Secondly to add an update feature. One use of this would be to amend prices of a products in price list, and produce a listing/report before committing the amendments.

    Thirdly, add a count of records selected (displayed in the footer?).

    And to be really cheeky, can you do it in ASP.NET 2.0 (in case you finish your version before I finish mine)    ;-)

     

  7. 19 May 2006 at 21:30

    Got if figured out. Seems that I inadvertantly had two select_deselectAll routines so it didn't know which to use. Even though in visual studeo it indicates that you cant, via a squiggle under the onclick, have an OnClick event for the asp:Checkbox, you can point it to a javascript routine since that runs only on the client. Also I removed the OnCheckChanged. - john

  8. 18 May 2006 at 23:34

    In net 1.1 how do you get the CheckAll to work? First, I cant use the OnClick since it is not available.  Second, if I try to use the OnCheckChanged event I cant point it to the javascript selectdeselectAll routine because it is not a member of 'ASP.mDatagridaspx'.  How do you apply events to a datagrid checkbox?  Other things are working fine but sure frustrating to not figure this out.  - john

  9. 03 Feb 2006 at 14:35

    Yevgeniy,


    No, not at all. No big deal really. We all hope to learn, as I from you as well.:D


    Thanks, and equal respect to you.:)


    -Jimmy

  10. 03 Feb 2006 at 13:46

    Well Dimitrios... must admit when you provided those links on StringBuilder vs static concatenation, I just quickly looked through them and was sure that was just another article advocating for static concatenations when the number of strings is known. Now I read it carefully and was surprised and ashamed... It seems like it's me who would be "seeding bad practices" in such a case... Sorry and my respect to you...

  11. 03 Feb 2006 at 13:11

    No, I appreciate the point you're trying to get across Yevgeniy. At any rate, as I indicated earlier, I agree with you when the concatenation is for minimal strings, but when you are concatenating numerous strings or functions the overhead in instantiation is overall justified I feel, and better practice.


    But either way, you're not really going to notice much truly in the way of performance, especially when you apply other performance enhancing techniques, ie, disabling debugging and tracing, closing connections, or even better bind a Datagrid from a Datareader instead of a DataSet for even greater advantages in speed, etc. In .NET, it's the collective means, rather than one tweak, that'll determine a scalable and efficient application.


    This applies to looping page size, that in my experience simply displaying a few hundred per page is still ill-advised, and with anything one does in greater magnitude, comes with it degrading performance regardless of much code manipulation.

  12. 03 Feb 2006 at 07:42

    I meant that instead of


    stringBuilder.Append(str1);
    stringBuilder.Append(str2);
    stringBuilder.Append(str3);


    you'd better use


    str1 + str2 + str3


    That's definitelly gonna be better.


    As for looping through form elements, I agree, it raises an issue only on a large amount of form elements. But who knows how large is going to be a particular page in question your readers will be working on.

  13. 02 Feb 2006 at 16:42

    Yevgeniy,


    Thanks for your input, but I would have to disagree on looping through all the elements on the given page being a performance issue, when it's looping through 10 checkboxes per page, not a million. Additionally, utilizing state management via session or viewstate further enhances performance and scalability. So there's no such thing as suboptimal when you perform the task at hand in the manner best suited.


    Now regarding your bias using the Stringbuilder class, again I would disagree. First of all, it's good practice in using Stringbuilder as there is performance advantages over static string concatenation - How StringBuilder string concatenation affects performance , string builder vs string concatenation "+" and Use StringBuilder to Build Strings Efficiently. So in my example it’s fine and justified.


    I will however give you this though, that I definitely agree with you on not using StringBuilder for 5 lines of code. Incidentally, in Part 1 of my article I did in fact use string concatenation if that makes a difference for you.


    But all in all Yevgeniy, I wouldn't just go out and post comments on articles unless you truly have facts to support your claims, which is why the statements you’ve made can "seed a bad practice, especially among newbies."

  14. 01 Feb 2006 at 15:33

    You see, Dimitros,


    while thank you very much for this article and other I was lucky to read before, I must admit there are times when you suggest a way to solve a problem in a quite suboptimal way.


    It's rarely good to loop through all form elements to find checkboxes appropriate. Well must admit under normal circumstances it can hardly pose a performance hit, but still when number of records is high or the html file is large (which is not good, I know, but I saw times when there seemed to be no other way), it takes a certain amount of time to iterate through all elements. I think it's better to have a client-side array of ids of all checkboxes in question. And on the server side you just emit client side code for each checkbox to register itself with that array. In this case anytime you need to loop through all checkboxes you simply loop through array elements which is much better from performanse standpoint.


    Then, I saw how you suggested to create client-side code via a long series of StringBuilder's Append method while it could have been done through static string concatenation. You can seed a bad practice, especially among newbies


    No time to write more, gotta be going Next time I'll write more.


    Thank you for your articles. Usually, I like them


    Yevgeniy


  15. 22 Jan 2006 at 20:52

    Hello all,


    Since I have had this article published here, I have now also been able to implement a way to highlight the selected row or entire set of rows and maintain this state across pages just as in my article, with of course the added benefit of showing users which row(s) they've checked, even when they happen to page back.


    To get this going, follow these four steps.


    First, add the style properties to the DataGrid:


    Code:

    <SelectedItemStyle BackColor="#F5EDED" ForeColor="Black">
    </SelectedItemStyle>


    <ItemStyle BackColor="White" ForeColor="Black">
    </ItemStyle>



    Second, add the highlightChkBxRow(this); JavaScript function call to both checkbox onClick events, so it now becomes:


    Code:

    OnClick="javascript: highlightChkBxRow(this); return select_deselectAll (this.checked, this.id);"


    Third, in the code behind - add the following JS function within the Registered Script Block section to handle the client side checkboxes:


    Code:

    .Append ("function highlightChkBxRow(chkbx) {" & nl & nl)
    .Append (" if (chkbx.id.indexOf ('DeleteThis') != -1) {" & nl & nl)
    .Append (" if (chkbx.checked) {" & nl & nl)
    .Append (" chkbx.parentElement.parentElement.style.backgroundColor='#F5EDED';" & nl)
    .Append (" chkbx.parentElement.parentElement.style.color='#000000';" & nl)
    .Append (" } else {" & nl & nl)
    .Append (" chkbx.parentElement.parentElement.style.backgroundColor='#FFFFFF';" & nl)
    .Append (" chkbx.parentElement.parentElement.style.color='#000000';" & nl & nl)
    .Append (" }" & nl & nl)
    .Append (" } else {" & nl & nl)
    .Append (" var frm = document.forms[0];" & nl & nl)
    .Append (" for (h = 0; h < frm.length; h++) {" & nl & nl)
    .Append (" if (frm.elements[h].id.indexOf ('DeleteThis') != -1) {" & nl & nl)
    .Append (" if (chkbx.id.indexOf ('CheckAll') != -1 && chkbx.checked) {" & nl & nl)
    .Append (" frm.elements[h].parentElement.parentElement.style.backgroundColor='#F5EDED';" & nl)
    .Append (" frm.elements[h].parentElement.parentElement.style.color='#000000';" & nl & nl)
    .Append (" } else {" & nl & nl)
    .Append (" frm.elements[h].parentElement.parentElement.style.backgroundColor='#FFFFFF';" & nl)
    .Append (" frm.elements[h].parentElement.parentElement.style.color='#000000';" & nl & nl)


    .Append (" }" & nl)
    .Append (" }" & nl)
    .Append (" } //loop" & nl)
    .Append (" }" & nl)
    .Append ("}" & nl)



    And, finally to maintain our selected rows across pages, replace the RePopulateCheckBoxes () method with the one listed below:


    Code:

    Sub RePopulateCheckBoxes ()


    CheckedItems = New ArrayList


    CheckedItems = Session ("CheckedItems")


    If Not IsNothing(CheckedItems) Then


    'Loop through DataGrid Items
    For Each dgItem in MyDataGrid.Items


    ChkBxIndex = MyDataGrid.DataKeys(dgItem.ItemIndex)


    'Repopulate DataGrid with items found in Session
    If CheckedItems.Contains(ChkBxIndex) Then


    CheckBox = CType(dgItem.FindControl("DeleteThis"), CheckBox)
    CheckBox.Checked = True


    dgItem.ForeColor = MyDataGrid.SelectedItemStyle.ForeColor
    dgItem.BackColor = MyDataGrid.SelectedItemStyle.BackColor


    Else


    dgItem.ForeColor = MyDataGrid.ItemStyle.ForeColor
    dgItem.BackColor = MyDataGrid.ItemStyle.BackColor


    End If


    Next


    End If


    'Copy ArrayList to a new array
    Results = CheckedItems.ToArray(GetType(String))


    'Concatenate ArrayList with comma to properly send for deletion
    deletedIds = String.Join(",", Results)


    End Sub



    And that's it. You're now able to offer the user the added functionality of highlighting the row they've checked or all the rows and persist their selections across pages!


    -Jimmy Markatos

  16. 01 Jan 1999 at 00:00

Leave a comment

Sign in or Join us (it's free).

AddThis

Related podcasts

  • CodeCast Episode 4: State of .NET, IE8, ASP.NET MVC, and O'Reilly Media

    CodeCast Episode 4: State of .NET, IE8, ASP.NET MVC, and O'Reilly MediaHosts Ken Levy and Markus Egger discuss the new State of .NET events, IE8, ASP.NET MVC, followed by an interview from PDC with two editors from O'Reilly Media. More on ASP.NET MVC can be found at http://asp.net/mvc. Interview...

Events coming up

  • Dec 6

    Developing AJAX Web Applications with Castle Monorail

    London, United Kingdom

    Monorail is the model-view-controller engine of the Castle Project, bringing many of the best ideas of Ruby on Rails to the .NET world. In this talk, David De Florinier and Gojko Adzic show how Monorail makes it easy to develop .NET based AJAX applications, and how to use the Castle Project to build Web 2.0 applications effectively. Come to this session if you are a .NET web developer. Everyone is welcome!