Community discussion forum

Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid (i.e. HotMail & Yahoo)

  • 9 years ago
  • Advertisement

    Simply the fastest line-level profiler for .NET ever

    “The low overhead means it has minimal impact on the execution of my program”
    Mark Everest, Development Team Leader, Renault F1 Team Ltd.

    Try out the new ANTS Profiler 4 for yourself. Download your 14-day trial now

  • 4 years ago

    Really nice code!!!


    This code produced following errors:


    'System.Web.UI.WebControls.BoundColumn' does not have a property named 'ID'


    Fixed: Deleted all 'ID=Boundcolumn1....' in the .aspx file


    It didn`t find the property Address error:


    Fixed: Adding 'stor_address as Address' to the sqlQuery in BindData function in .aspx.cs file

  • 4 years ago

    Code:

    foreach (DataGridItem i in MyDataGrid.Items)
               {
                   CheckBox deleteChkBxItem = (CheckBox) i.FindControl ("DeleteThis");
                   if (deleteChkBxItem.Checked)
                   {


    are u sure that is working ? i mean it always gives un checked objects

  • 4 years ago

    no matter what I do the checkboxes are always unchecked. What am I missing?
    looks like no data is posted, tested with a text box and the text is always empty.
    The data is in the form collection but when I loop over the items and check the checkboxes for being checked, they are always unchecked.

  • 4 years ago

    Same here. It always returning unchecked check boxes.

  • 4 years ago

    I had the same problem until I checked the <FORM> tags in the aspx page.  Ensure that you only have one <FORM> tag, and that it includes the <ASP: checkbox...> tag.

  • 4 years ago

    I was having the no boxes checked problem -- I think it was caused by the data being bound to the datagrid on postback, thus erasing any checks that may have been entered.  (My data was getting bound during the page_load event, which happened before the button click event handler)


    If you are experiencing a similar problem, make sure you loop through your datagrid before any binding occurs.

  • 4 years ago

    hi, and im using visual basic asp.net application to select item(s) in datagrid using checkbox and show the item selected in other datagrid on the same page, and i have a go button to transfer items... im done showing the selected items on the other grid but once i didn't check any of checkbox in datagrid i meet an error...  pls help me.. thanks a lot in advance.. hope someone post a sample code..

  • 4 years ago

    The code saved me finding the checkbox data grid solution on my own. Some comments after using it:
    The script in "select_deselectAll" has a side effect of affecting all checkboxes and radiobuttons on the page. A check should be added to ensure that only the relevant checkboxes are touched by the function (check the "frm.elements [ i ] .id" inside the for-loop).


    Checking if the "idVal" paramenter contains a static string should be moved outside the for-loop. Assign the results to two boolean vars and use the boolean vars inside the for-loop.


    In the "else if" section, add a "break;" statement after the line that deselected the header checkbox (the line with "//Uncheck main select all checkbox"). It has no purpose to continue the for-loop, as the header checkbox is already deselected.


    In addition, a more robust way of referencing the header checkbox than "frm.elements [ 1 ] " should be implemented, e.g. when there are other elements on the page in addition to the checkbox data grid.

  • 4 years ago

    Hi,,


    if the header checkbox was not check then
    i want to ask if the user selects all of the checkboxes then how can we write code to make the header checkbox checked


    thanks

  • 4 years ago

    I have improved the script. So, it can now check the "main checkbox" if all the checkboxes are checked. And it decheck the "main checkbox" if any checkbox is dechecked. It works as yahoo mail.


    The main point is to check all the checkbox when a checkbox's state is changed.


    (chkAll is the name of the main Checkbox, chkDelete is the name of the checkbox at every row.)



    <script language="JavaScript">
    <!--
    function confirmDelete (frm) {


    // loop through all elements
    for (i=0; i<frm.length; i++) {


       // Look for our checkboxes only
       if (frm.elements.name.indexOf ('chkDelete') !=-1) {
           // If any are checked then confirm alert, otherwise nothing happens
           if(frm.elements.checked) {
               return confirm ('Are you sure you want to delete your selection(s)?')
           }
       }
    }
    return false;
    }



    function select_deselectAll (chkVal, idVal) {
       var frm = document.forms[0];
       


       if (idVal.indexOf('chkDelete') != -1 && chkVal == true){
       
           var boolAllSelected = true;


           for (i=0; i<frm.length; i++) {
               if (frm.elements.id.indexOf('chkDelete') != -1 && frm.elements.checked == false){
                   boolAllSelected = false;    
                   break;
               }
           }
           
           if(boolAllSelected == true){
               
               for (j=0; j<frm.length; j++) {
                       if (frm.elements[j].id.indexOf ('chkAll') != -1) {
                           frm.elements[j].checked = true;
                           break;
                       }
               }
           }
           
       }
       else{
           for (i=0; i<frm.length; i++) {
               if (idVal.indexOf ('chkAll') != -1) {
                   if(chkVal == true) {
                       frm.elements.checked = true;
                   }
                   else {
                       frm.elements.checked = false;
                   }
               }
               else if (idVal.indexOf('chkDelete') != -1 && frm.elements.checked == false) {
                       for (j=0; j<frm.length; j++) {
                   
                           if (frm.elements[j].id.indexOf ('chkAll') != -1) {
                               frm.elements[j].checked = false;
                               break;
                           }
                       }
                   }
               }
           }
    }
    //-->
    </script>



  • 4 years ago


    [3] ravindra_reddy81@yahoo.co.in [/3]



    here is html code



    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="articlellist.aspx.vb" Inherits="table.articlellist"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
       <HEAD>
           <title>WebForm1</title>
           <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
           <meta content="Visual Basic .NET 7.1" name="CODELANGUAGE">
           <meta content="JavaScript" name="vs
    defaultClientScript">
           <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vstargetSchema">
           <SCRIPT language="JavaScript">
           function confirmdel(frm1)
           {        
           for (i=0; i<frm1.length; i++)
               {
               if(frm1.elements.checked == true)
                   {
                   var val=true;
                   break;
                   }
                   else
                   {
                   val=false;
                   }
               }
               if (val==true)
               {
               return confirm('Are you sure you want to Delete your selection(s)?');
               }
               else
               {
               alert('No item is selected for Delete');
               }
           }
           </SCRIPT>
           <SCRIPT language="JavaScript">
           
       function select
    deselectAll (chkVal, idVal)
    {
       var frm = document.forms[0];
       // Loop through all elements
       for (i=0; i<frm.length; i++)
       {
           // Look for our Header Template's Checkbox
           if (idVal.indexOf ('CheckAll') != -1)
           {
               // Check if main checkbox is checked, then select or deselect datagrid checkboxes
               if(chkVal == true)
               {
                   frm.elements.checked = true;
               }
               else
               {
                   frm.elements.checked = false;
               }
               // Work here with the Item Template's multiple checkboxes
           }
           else
            if (idVal.indexOf ('DeleteThis') != -1)
           {
               // Check if any of the checkboxes are not checked, and then uncheck top select all checkbox
               if(frm.elements.checked == false)
               {
                   document.Form1.CheckAll.checked=false;
                    //Uncheck main select all checkbox
               }            
           }
       }
    }
           </SCRIPT>
       </HEAD>
       <body MS_POSITIONING="GridLayout">
           <form id="Form1" method="post" runat="server">
               <asp:label id="Label1" style="Z-INDEX: 102; LEFT: 109px; POSITION: absolute; TOP: 93px" runat="server" Width="504px"></asp:label>
               <TABLE id="Table1" style="Z-INDEX: 104; LEFT: 457px; WIDTH: 196px; POSITION: absolute; TOP: 29px; HEIGHT: 27px" cellSpacing="1" cellPadding="1" width="196" border="0">
                   <TR>
                       <TD style="WIDTH: 155px"><asp:label id="Label2" runat="server" Width="137px"></asp:label></TD>
                       <td><A title="Sign Out" href="signout.aspx" runat="server">SignOut</A>
                       </td>
                   </TR>
               </TABLE>
               <asp:button id="Button2" style="Z-INDEX: 103; LEFT: 123px; POSITION: absolute; TOP: 365px" runat="server" Width="45px" Text="Add" Height="20px" BorderStyle="Groove" Font-Names="Verdana" Font-Size="8pt"></asp:button><asp:datagrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 159px; POSITION: absolute; TOP: 128px" runat="server" Width="446px" Height="15px" BorderStyle="Groove" Font-Names="Verdana" Font-Size="8pt" GridLines="Horizontal" ForeColor="#E0E0E0" BorderColor="Gray" BorderWidth="1px" BackColor="White" AutoGenerateColumns="False" AllowPaging="True" PageSize="7">
                   <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#E0E0E0"></SelectedItemStyle>
                   <EditItemStyle HorizontalAlign="Center" ForeColor="LightGray" BackColor="White"></EditItemStyle>
                   <AlternatingItemStyle BackColor="White"></AlternatingItemStyle>
                   <ItemStyle Font-Size="8pt" Font-Names="Verdana" HorizontalAlign="Center" Height="5px" ForeColor="Black" BorderStyle="Groove" BorderColor="Gray" BackColor="White"></ItemStyle>
                   <HeaderStyle Font-Size="8pt" Font-Names="Verdana" HorizontalAlign="Center" Height="15px" ForeColor="Black" BorderStyle="Groove" BackColor="#E0E0E0"></HeaderStyle>
                   <FooterStyle HorizontalAlign="Center" Height="24px" ForeColor="#E0E0E0" BorderStyle="Groove" BackColor="#E0E0E0"></FooterStyle>
                   <Columns>
                       <asp:TemplateColumn>
                           <HeaderTemplate>
    &nbs

  • 4 years ago

    [3]8[/3] purple [3]8[/3] [3]8[/3] [arial]ariel[/arial] b  ravindrareddy81@yahoo.co.in
    hi every body.here is my code to develop hotmail style and yahoomail style datagrid with confirm delete message.if u have any doubts send me mail i will send entire code to you.enjoy with this code.
    RAVINDRAREDDY
    ********************ravindra
    reddy81@yahoo.co.in



    here is my html code



    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="articlellist.aspx.vb" Inherits="table.articlellist"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
       <HEAD>
           <title>WebForm1</title>
           <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
           <meta content="Visual Basic .NET 7.1" name="CODELANGUAGE">
           <meta content="JavaScript" name="vs
    defaultClientScript">
           <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vstargetSchema">
           <SCRIPT language="JavaScript">
           function confirmdel(frm1)
           {        
           for (i=0; i<frm1.length; i++)
               {
               if(frm1.elements.checked == true)
                   {
                   var val=true;
                   break;
                   }
                   else
                   {
                   val=false;
                   }
               }
               if (val==true)
               {
               return confirm('Are you sure you want to Delete your selection(s)?');
               }
               else
               {
               alert('No item is selected for Delete');
               }
           }
           </SCRIPT>
           <SCRIPT language="JavaScript">
           
       function select
    deselectAll (chkVal, idVal)
    {
       var frm = document.forms[0];
       // Loop through all elements
       for (i=0; i<frm.length; i++)
       {
           // Look for our Header Template's Checkbox
           if (idVal.indexOf ('CheckAll') != -1)
           {
               // Check if main checkbox is checked, then select or deselect datagrid checkboxes
               if(chkVal == true)
               {
                   frm.elements.checked = true;
               }
               else
               {
                   frm.elements.checked = false;
               }
               // Work here with the Item Template's multiple checkboxes
           }
           else
            if (idVal.indexOf ('DeleteThis') != -1)
           {
               // Check if any of the checkboxes are not checked, and then uncheck top select all checkbox
               if(frm.elements.checked == false)
               {
                   document.Form1.CheckAll.checked=false;
                    //Uncheck main select all checkbox
               }            
           }
       }
    }
           </SCRIPT>    </HEAD>
       <body MS_POSITIONING="GridLayout">
           <form id="Form1" method="post" runat="server">
               <asp:label id="Label1" style="Z-INDEX: 102; LEFT: 109px; POSITION: absolute; TOP: 93px" runat="server" Width="504px"></asp:label>
               <TABLE id="Table1" style="Z-INDEX: 104; LEFT: 457px; WIDTH: 196px; POSITION: absolute; TOP: 29px; HEIGHT: 27px" cellSpacing="1" cellPadding="1" width="196" border="0">
                   <TR>
                       <TD style="WIDTH: 155px"><asp:label id="Label2" runat="server" Width="137px"></asp:label></TD>
                       <td><A title="Sign Out" href="signout.aspx" runat="server">SignOut</A>
                       </td>
                   </TR>
               </TABLE>
               <asp:button id="Button2" style="Z-INDEX: 103; LEFT: 123px; POSITION: absolute; TOP: 365px" runat="server" Width="45px" Text="Add" Height="20px" BorderStyle="Groove" Font-Names="Verdana" Font-Size="8pt"></asp:button><asp:datagrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 159px; POSITION: absolute; TOP: 128px" runat="server" Width="446px" Height="15px" BorderStyle="Groove" Font-Names="Verdana" Font-Size="8pt" GridLines="Horizontal" ForeColor="#E0E0E0" BorderColor="Gray" BorderWidth="1px" BackColor="White" AutoGenerateColumns="False" AllowPaging="True" PageSize="7">
                   <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#E0E0E0"></SelectedItemStyle>
                   <EditItemStyle HorizontalAlign="Center" ForeColor="LightGray" BackColor="White"></EditItemStyle>
                   <AlternatingItemStyle BackColor="White"></AlternatingItemStyle>
                   <ItemStyle Font-Size="8pt" Font-Names="Verdana" HorizontalAlign="Center" Height="5px" ForeColor="Black" BorderStyle="Groove" BorderColor="Gray" BackColor="White"></ItemStyle>
                   <HeaderStyle Font-Size="8pt" Font-Names="Verdana" HorizontalAlign="Center" Height="15px" ForeColor="Black" BorderStyle="Groove" BackColor="#E0E0E0"></HeaderStyle>
                   <FooterStyle Horiz

  • 4 years ago

    Thanks for posting this comment meef. I could not figure out why mine was not running either till i read your comment

  • 4 years ago

    Hi,


    I need this solution to work for a large number of items in a page view.


    Using this solution (and\or other similar ones), means iterating through all the items when the user might have checked just one or two.


    Is there a way to make this more efficient?


    Thanks.
    -Shefali


  • 3 years ago

    Hey ketcapli I get an error: Elements is null or not an object. It is the last line below:


    Code:

    function select_deselectAll (chkVal, idVal) {
      var frm = document.forms;
       


      if (idVal.indexOf('chkDelete') != -1 && chkVal == true){
       
          var boolAllSelected = true;


          for (i=0; i<frm.length; i++) {
              if (frm.elements.id.indexOf('chkDelete') != -1 && frm.elements.checked == false){
                  boolAllSelected = false;    
                  break;
              }
          }
           
          if(boolAllSelected == true){
               
              for (j=0; j<frm.length; j++) {
                      if (frm.elements[j].id.indexOf ('chkAll') != -1) {
                          frm.elements[j].checked = true;
                          break;
                      }
              }
          }
           
      }
      else{
          for (i=0; i<frm.length; i++) {
              if (idVal.indexOf ('chkAll') != -1) {
                  if(chkVal == true) {
                      frm.elements.checked = true;



    Any ideas? I can get the original function from http://www.developerfusion.com/show/4632/3/  to work, changed the control ids to yours...

  • 3 years ago

    hi,
    You must have given the names of the checkboxes as chk....
    All checkbox names must start with chk.

  • 3 years ago

    I did do that. Used chkDelete and chkAll. Any other ideas?

  • 3 years ago

    Hi everybody i am Raveendra Reddy working as a software engineer in spur software technologies,bangalore.
    Here is my code to resize the big images to small one and vise versa.Enjoy with the code.If you have any doubts send mail to
    ravindra_reddy81@yahoo.co.in



    Here is my code



    Imports System.Data
    Imports System.Drawing
    Imports System.Drawing.Image
    Imports System.Drawing.Imaging
    Public Class WebForm6
       Inherits System.Web.UI.Page


    Region " Web Form Designer Generated Code "



       'This call is required by the Web Form Designer.
       <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()


       End Sub


       Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
           'CODEGEN: This method call is required by the Web Form Designer
           'Do not modify it using the code editor.
           InitializeComponent()
       End Sub


    End Region


       Dim hight
       Dim width
       Dim source
       Dim destination
       Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
           'Put user code to initialize the page here
           hight = "200"
           width = "350"
           source = "C:\Inetpub\wwwroot\RICHTEXTEDITOR\image\indy1[1].jpg"
           destination = "C:\Inetpub\wwwroot\RICHTEXTEDITOR\image1\indy1[1].jpg"
           Call sendFile(hight, width, source, destination)
       End Sub
       Sub sendFile(ByVal hight As Integer, ByVal width As Integer, ByVal source As String, ByVal destination As String)
           ' create New image and bitmap objects. Load the image file and put into a resized bitmap.  
           Dim getimage As System.Drawing.Image = System.Drawing.Image.FromFile(source)
           Dim thisFormat = getimage.RawFormat
           Dim imgOutput As New Bitmap(getimage, width, hight)
           ' Set the contenttype    
           'Response.Write(thisFormat.GetType())
           If thisFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif) Then
               Response.ContentType = "image/gif"
           Else
               Response.ContentType = "image/jpeg"
           End If
           ' send the resized image to the viewer  
           imgOutput.Save(Response.OutputStream, thisFormat) ' output to the user
           imgOutput.Save(destination, thisFormat)
           ' tidy up  
           getimage.Dispose()
           imgOutput.Dispose()
       End Sub
    End Class














  • 3 years ago

    hi,
    first I would like to thank you. I found your code most helpful.  But I am still getting an error stating that OnClick is not an element of CheckBox. Why am I getting this and how do fix it?
    thank you,
    jr. techie

  • 3 years ago

    Hi everyone,


    If you have any troubles on  Yahoo Like select deselect main checkbox please add your code to your post and please add your detailed explanation.


    For javascript codes one important thing is your browser. Sometimes a script may run at IE but not at Mozilla. You must check your code at different browsers.


    And did you try Raveendra Reddy's full HTML code with behind code?


    And last, you must add the scripts inside the head tags. <head><script></script></head>

  • 3 years ago

    Hello,
           I'm new to asp.net. I had gone through the code and it was quite helpful. Let me mention the problem now.... I have got a user control with similar interface of yahoo inbox where i want to select multiple records by cheking the chekbox next to each record and if i press the delete button it should delete the checked records.


    But i don't use any code behind file. I want the javascript code for checkbox selection_deselection to be written in the page load event of the user control itself. But when i do this i get an error in the following code.  I wrote the code like this..


    <script runat=server>


     public void Page_Load (Object Sender, EventArgs E)
     {
     ----
     ----


     "//--> \n" +
      "</script>";            


    //Allows our .NET page to add client-side script blocks when page loads, instead of the conventional HTML JS tags.            
     RegisterClientScriptBlock ("clientScript", jsScript);


      ---
     ----


     }


    </script>




    Please help!


    Regards,  
      Sunil

  • 3 years ago

    This is an awesome bit of code and well needed! got it working pretty easily too.  Well written tutorial.  The only thing I had issues with was when I added the newest code (for unchecking/checking the chkAll when all or not all were selected).  I debugged and found that it seemed that some index references were missing - I tried to comment where i made changes.  Here's what I got working:


           function select_deselectAll (chkVal, idVal) {
               var frm = document.forms[0]; // thombo added  [ 0 ]
                 


               if (idVal.indexOf('chkDelete') != -1 && chkVal == true){
                 
                   var boolAllSelected = true;


                   for (i=0; i<frm.length; i++) {
                       if (frm.elements.id.indexOf('chkDelete') != -1 && frm.elements.checked == false){  // thombo added [ i ]
                           boolAllSelected = false;    
                           break;
                       }
                   }
                     
                   if(boolAllSelected == true){
                         
                       for (j=0; j<frm.length; j++) {
                           if (frm.elements[j].id.indexOf ('chkAll') != -1) {
                               frm.elements[j].checked = true;
                               break;
                           }
                       }
                   }
                     
               }
               else {    
                   for (i=0; i<frm.length; i++) {
                       if (idVal.indexOf ('chkAll') != -1) {
                           if(chkVal == true) {
                               frm.elements.checked = true; // thombo added [ i ]
                           }
                           else {
                               frm.elements.checked = false; // thombo added [ i ]
                           }
                       }
                       else if (idVal.indexOf('chkDelete') != -1 && frm.elements.checked == false) { // thombo added [ i ]
                           for (j=0; j<frm.length; j++) {
                           
                               if (frm.elements[j].id.indexOf ('chkAll') != -1) {
                                   frm.elements[j].checked = false;
                                   break;
                               }
                           }
                       }
                   }
               }

  • 3 years ago

    aaaaaaaaaah, sorry for the post, now I see what happened...apparently [ 0 ] and [ i ] (remove the spaces) are reserved for the Forum codes and get parsed out when you post the code.  That's pretty annoying!


    Quote:
    [1]Posted by thombo on 27 Jan 2005 04:14 PM[/1]
    This is an awesome bit of code and well needed! got it working pretty easily too.  Well written tutorial.  The only thing I had issues with was when I added the newest code (for unchecking/checking the chkAll when all or not all were selected).  I debugged and found that it seemed that some index references were missing - I tried to comment where i made changes.  Here's what I got working:


           function select_deselectAll (chkVal, idVal) {
               var frm = document.forms[ 0 ]; // thombo added  [ 0 ]
                 


               if (idVal.indexOf('chkDelete') != -1 && chkVal == true){
                 
                   var boolAllSelected = true;


                   for (i=0; i<frm.length; i++) {
                       if (frm.elements[ i ].id.indexOf('chkDelete') != -1 && frm.elements[ i ].checked == false){  // thombo added [ i ]
                           boolAllSelected = false;    
                           break;
                       }
                   }
                     
                   if(boolAllSelected == true){
                         
                       for (j=0; j<frm.length; j++) {
                           if (frm.elements[j].id.indexOf ('chkAll') != -1) {
                               frm.elements[j].checked = true;
                               break;
                           }
                       }
                   }
                     
               }
               else {    
                   for (i=0; i<frm.length; i++) {
                       if (idVal.indexOf ('chkAll') != -1) {
                           if(chkVal == true) {
                               frm.elements[ i ].checked = true; // thombo added [ i ]
                           }
                           else {
                               frm.elements[ i ].checked = false; // thombo added [ i ]
                           }
                       }
                       else if (idVal.indexOf('chkDelete') != -1 && frm.elements[ i ].checked == false) { // thombo added [ i ]
                           for (j=0; j<frm.length; j++) {
                           
                               if (frm.elements[j].id.indexOf ('chkAll') != -1) {
                                   frm.elements[j].checked = false;
                                   break;
                               }
                           }
                       }
                   }
               }


  • 3 years ago

    Does the WebForms Checkbox  have  the 'OnClick" event ?
    Because when I tried to include checkboxes within the datagrid to try out the multiple checkbox items, it gave me an error. Maybe I am wrong, but please can you clarify?


    Thanks,
    Adarsh

  • 3 years ago

    I noticed a bit of lag when unchecking single checkbox items with about 500 entries in my datagrid so i restructured the code to be a bit more efficient.  This code cycles through all checkboxes a little less, but in order to determine whether the header checkbox needs to be checked when an item is checked, im not sure how to avoid this.  Maybe it could use even more work, but I definitely see an improvement.  I changed the names to chkItem and chkHeader.  


    Code:

    function select_deselectAll (chkVal, idVal) {
       var frm = document.forms[0];


       // Determine whether it is a header checkbox or a regular item checkbox
       if ( idVal.indexOf('chkItem') != -1 ) { // Regular checkbox item
           if ( chkVal == true ) { // Checkbox being checked
               var boolAllSelected = true;


               // Go through all checkbox elements to determine if they are all checked
               for (i=0; i<frm.length; i++) {
                   if (frm.elements.id.indexOf('chkItem') != -1 && frm.elements.checked == false){
                       boolAllSelected = false;    
                       break;
                   }
               }


               // If all checkboxes are checked need to check the header checkbox
               if( boolAllSelected == true ){
                   // Find the header checkbox and check it
                   for (j=0; j<frm.length; j++) {
                       if (frm.elements[j].id.indexOf ('chkHeader') != -1) {
                           frm.elements[j].checked = true;
                           break;
                       }
                   }
               }
           }
           else if ( chkVal == false ) { // Checkbox being unchecked
               // Find the header checkbox and uncheck it
               for (j=0; j<frm.length; j++) {


                   if (frm.elements[j].id.indexOf ('chkHeader') != -1) {
                       frm.elements[j].checked = false;
                       break;
                   }
               }
           }


       }
       else if ( idVal.indexOf ('chkHeader') != -1 ) { // Header checkbox item


           // Set the checked value for each of the checkbox items equal to the header box's checked value (chkVal)
           for (i=0; i<frm.length; i++) {
               if (frm.elements.id.indexOf ('chkItem') != -1) {
                   frm.elements.checked = chkVal;
               }
           }
       }
    }


  • 3 years ago

    Hi
    Thank you for your code it most helpful for me. But i have problem about select all function because i have checkbox control for 2 columns inside datagrid . When i click select all button it checking all checkbox inside datagrid so i need check only first column. Please help me.

  • 3 years ago

    wherever you see " idVal.indexOf('chkDelete')  != -1 ", that is checking if the checkbox name contains the phrase "chkDelete".    So all you should have to do is make sure that the checkboxes in column 2 have a different name and that should work, make sense?


    either that or if the 2nd column doesnt have it's own selectAll checkbox then just omit the line:
    OnClick="javascript: return select_deselectAll (this.checked, this.id);
    from the 2nd column's checkboxes.  


    i believe both of these options should work, though i have not tested.


    thombo

  • 3 years ago

    Hi Adarsh,


    Yes of course. If you look within the datagrid's template columns, you'll notice the the checkbox has the onClick handler:


    Code:
    asp:CheckBox ID="CheckAll" OnClick="javascript: return select_deselectAll (this.checked, this.id);" runat="server"/>


    All the code provided work exactly as written. Aside from db connection and query modifications you may make, you should be good to go. Go over any modifications you may have made to the original code which may be causing you your problem.

  • 3 years ago

    I have a squiggly line when I try to use OnClick too.... "Could not find any attribute "OnClick" of element "CheckBox"

  • 3 years ago

    I have an issue I run into with implementing this.  When I select my checkboxes and submit the form, it loops through it returns false for each checkbox.  Can anyone tell my why it is doing this?  It is getting past "if not deleteChkBxItem is Nothing then", but it doesn't get inside the conditional of "if deleteChkBxItem.Checked = True".


    Here is my code:


    order.aspx

    Code:

    <%@ Page Language="VBScript" aspcompat=true Src="ordercart.aspx.vb" Inherits="OrderCart.Cart" %>
    <%@ Register TagPrefix="MDS" TagName="RightUserBox" Src="/includes/rightuserbox.ascx" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
       <title>Management Development Seminars :: Special Topic Seminars</title>
       <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
       <meta content="VB" name="CODELANGUAGE" />
       <script type="text/javascript">
           function select
    deselectAll (chkVal, idVal)
           {
               var frm = document.forms[0];
               //Loop through all elements
               for (i=0; i<frm.length; i++)
               {
                   //Look for our Header Template's Checkbox
                   if (idVal.indexOf('CheckAll') != -1)
                   {
                       //Check if main checkbox is checked, then select or deselect datagrid checkboxes
                       if(chkVal==true) {
                           frm.elements.checked = true;                
                       }
                       else
                       {
                           frm.elements.checked = false;
                       }
                       //Work here with the Item Template's multiple checkboxes
                   }
                   else if (idVal.indexOf('chxRemove') != -1)
                   {
                       //Check if any of the checkboxes are not checked, and then uncheck top select all checkbox
                       if(frm.elements.checked == false)
                       {
                           frm.elements.checked = false; //Unchecked main select all checkbox
                       }
                   }
                     
               }
           }
           
           function confirmDelete(frm) {
               //loop through all elements
               for(i=0; i<frm.length; i++) {
                   //Look for our checkboxes only
                   if(frm.elements.name.indexOf("chxRemove") !=-1) {
                       //If any are checked then confirm alert, otherwise nothing happens
                       if(frm.elements.checked) {
                           return confirm('Are you sure you want to delete your selection(s)?');
                       }
                   }
               }
           }
       </script>
       <style type="text/css" media="screen">
           @import url('/css/main.css');
           @import url('/css/forms.css');
           @import url('/css/tables.css');
           @import url('/css/seminars.css');                
       </style>
       <style type="text/css" media="print">
           @import url('/css/print/main.css');
       </style>
    <style type="text/css" media="screen">
       .date-box {
           float: left;
           margin: 2px;
           color: #000;
           background: #fff;
           border: #000 solid 1px;    
       }
       
       #tblCart {
           width: 100%;
           border-collapse: collapse;
           padding: 0px;
           border: 0px;        
       }
       
       #tblCar tbody tr {
           vertical-align: middle;
       }
       
       #tblCart tbody tr td {
           font-family: "lucida grande", verdana, sans-serif;
           font-size: 8pt;
           padding: 3px 8px;
           border-left: 1px solid #D9D9D9;
       }
       
       #dg {
           width: 100%;
           border-collapse: collapse;
           padding: 0px;
           border: 0px;
       }
       
       #dg tbody tr {
           vertical-align: middle;
       }
       
       #dg tbody tr td {
           font-family: "lucida grande", verdana, sans-serif;
           font-size: 8pt;
           padding: 3px 8px;
           border-left: 1px solid #D9D9D9;
       }
       
       #chbx {
           width: 25px;
       }
    </style>    
    </head>
    <body>
    <!-- #include virtual="/includes/top.inc" -->
    <!-- #include virtual="/includes/navigation.inc" -->
    <div id="maincontent">
       <div id="leftcontent">
           <fieldset>
               <legend>Order</legend>
               <form id="frm

  • 3 years ago

    For anyone that might have a similar issue, here is the solution.


    order.aspx.vb under page_load:

    Code:

               If Not IsPostBack Then
                   MyDataGrid.DataBind()
               End If

  • 3 years ago

    Is it possible to send source in easier format, like ZIP?

  • 3 years ago

    I am new to .net and have used most of the code here to implement a datagrid with the option to select all/deselect all.  That part works, but when I go to delete an item that's checked, the datagrid is empty.  If I try to "rebind" the grid, then the checkbox values are false.  Can anyone help?

  • 3 years ago

    Polash26,


    the entire code is listed and it's all a simple matter of cut and paste. I will be posting the entire code in VB.Net within a few days in zip format though


    - JM

  • 3 years ago

    Quote:
    [1]Posted by DMarko1 on 16 Jun 2005 03:44 PM[/1]
    Polash26,


    the entire code is listed and it's all a simple matter of cut and paste. I will be posting the entire code in VB.Net within a few days in zip format though


    - JM



    Thanks for your reply.
    Can't do cut and paste, because it appears like as below, do you also have CS version?



    <%@ Page Language="VBScript" aspcompat=true Src="ordercart.aspx.vb"
    Inherits="OrderCart.Cart" %> <BR><%@ Register TagPrefix="MDS"
    TagName="RightUserBox" Src="/includes/rightuserbox.ascx" %> <BR><!DOCTYPE
    html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    <BR>"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <BR><html> <BR><head> <BR>   <title>Management Development
    Seminars :: Special Topic Seminars</title> <BR>   <meta
    http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <BR>  
    <meta content="VB" name="CODELANGUAGE" /> <BR>   <script
    type="text/javascript"> <BR>       function select
    deselectAll (chkVal,
    idVal)

  • 3 years ago

    Hi. I see, but when I highlight the code and paste it into, say notepad, it's the exact way as in my article.


    So I really don't know what to say.


    If you still have difficulties send me an email and I'll send you the code, and in whatever version you prefer.


    - Jimmy Markatos

  • 3 years ago

    I am a Novice


    I am making an email module in which i have maintained a 'status bit' at DATABASE
    This it tells whether user has read this mail before or not


    The problem is that i can successfully retrieve values from database but i want to Show
    those rows in BOLD whose 'status bit' is True,so that user can diffrentiate between new and old mails.


    For this i have made status as datakeyfield but i don't know WHEN and HOW should i retieve this
    value in order to make it bold

  • 3 years ago

    Hello all,


    Due to popular demand, I am posting the link for all those interested in the VB.NET version of this code.


    Download here - http://members.aol.com/dmarko1/dnjcode/MultiChkBxDG_VB.zip


    - Jimmy Markatos

  • 3 years ago

    Hi Jim,


    I have an issue with this multi-select thing. If I use paging (default), everytime I change the page number or sort the page, the DataGrid rebinds and all the things in the checkboxes are lost. As a result, I can only check checkboxes in one page at a time only. I don't know if you have any solution to save the checkbox status across pages?


    I could think of embedding another column into the database and to save the checkbox status to solve this problem, but it is kind of bulky. I don't know if there is any other way to do this, I read somewhere before that the solution is to bind the datagird only once at first, but I don't know how come this is possible given the fact that the datagrid needs to be rebind with every page change or sort.


    Thank you,
    Jack

  • 3 years ago

    Hey JackLi,


    Yeah I know and sites like AOL WebMail, for instance do the exact same thing. If you page, your selections are lost; maybe this is a good thing. But when I wrote the article so long ago, I didn't really feel the need for it.


    However, one way I can think off the top is to grab the checked values in one of nine ways to persist state - Nine Options for Managing Persistent User State in Your ASP.NET Application.


    Having said that, I think the best way would most probably be is store the checked values, and CurrentPageIndex in ViewState, and when the appropriate page is selected you would repopulate the checked boxes from ViewState using the same kind of JavaScript I wrote in selected all the checkboxes for instance.


    And furthermore you would also use ViewState to then send the cumulative values to the delete function all at once, when the user decides to delete all they've selected.


    This approach is far more scalable friendly, furthered by the fact that you also don't return and give the client thousands of records to choose from.


    Plus regarding the rebind of the DataGrid, when you cache you Grid all database interaction ceases as the DataGrid calls upon the Cache for its data. I covered this in .NET Data Caching


    Hope this helps jackLi


    - JM

  • 3 years ago

    Hey Jim,


    Thanks for your reply.


    I want to make sure that I got this right: If I store an ArrayList of ids for checkboxes that got checked on a specific page in a ViewState together with their CurrentPageIndex, and then repopulate them using JavaScript everytime the user revisits that page, it will work just fine as long as the datagrid is always sorted by one specific field. Yet, if I sort the datagrid again (at any time) using some other field, then the ViewState-stored ids for those checked checkboxes are no longer valid, is that right? I actually do not have a good understanding of how VS handles paging and sorting at the same time with their built-in ViewState, so correct me if I am wrong about the data structures that you proposed for this custom ViewState.


    I thought of saving the row ids of the original (database) table into a ViewState, and trace them back, but usually I put these ids in hidden controls, making it hard to match up the ViewState value with already-processed HTML using JavaScript.


    Thank you,
    Jack

  • 3 years ago

    Hi,


    Actually I think your proposed database method will still fall short with respect to any sorting and plus you're maintaining an added layer of database interaction, alongside your databinding - not good.


    It's simply a matter of grabbing these values when you page so before you rebind and advance the grid, you'd store the checkbox values, CurrentPageIndex and the Sortfield as well into ViewState or Session State. Notice how the DeleteStore method checked and pulled out the checked box values. It would be like this but in reverse that you would thereby read these values from state management, then "rebind" the grid at that page with the correct checked values.


    Then when someone pages back to the respective page you call your method responsible for reassigning the grid with the appropriate checked values.




    Let me know if I can help you further. I may write an article about this soon, cause I have encounter this question a couple of times before


    -Jimmy Markatos

  • 3 years ago

    Hi Jim,


    I think I got it now, you also store the SortField in the ViewState and just update the ViewState accordingly if ever the grid is rebind. Makes great sense to me. Thanks a lot Jim, your advice is actually more helpful than those of my brother, who is the VS group.

  • 3 years ago

    Thank you jackLi, I do appreciate it


    I will also at some point soon tackle that and create a full fledged version of this with all the features we've dsicussed.


    Best Regards,


    Jimmy Markatos

  • 3 years ago

    I copy pasted the code in this tutorial exactly as they are, however in the server side function when i loop through the datagrid's checkboxes, they are always false (checked=false)!


    What could the problem be? Any ideas?

  • 3 years ago


    That is very strange, as I just copied the code to test it for fun, and I got none of the problems you've encountered. Other than this I really don't see why you would be getting that. This, of course is silly to ask, but something must be checked in order to return a checkbox=true.


    In any event, I have updated methodology found in this article in Part 2, where it covers how to multi-select checkboxes and maintain state across pages with sorting.


    You can find it on DNJ - Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid - Part 2: Maintaining CheckBox State Across Pages with Sorting.


    Hope this helps.

  • 3 years ago


    Hey jackLi, I am proud to say that I have tackled this issue and you can find the solution on dotnetjunkies, Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid - Part 2: Maintaining CheckBox State Across Pages with Sorting.


    -Jimmy Markatos

  • 3 years ago

    Hello all,


    The article "Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid" you may have read here on developerfusion is Part 1 written a while ago, and it covered only a simple example of checking a series of checkboxes within one page on a DataGrid, whereby you could then delete your items, but offered no paging nor any maintaining of state.


    I have recently improved on this in Part 2 of the article, and it demonstrates how to multi-select checkboxes across pages with sorting on a page-by-page basis


    You can find it on DNJ - Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid - Part 2: Maintaining CheckBox State Across Pages with Sorting.


    - Jimmy Markatos

  • 3 years ago

    Hello all,


    Since I have had Part II of my multi-select article published on DNJ, 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 the back back.


    You can see the article here - and then go to the forum listing on dotnetjunkies - Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid - Part 2: Maintaining CheckBox State Across Pages


    Then view the enhanced code in the forum - Highlight and maintain multi-selected checkbox row colors.


    - Jimmy Markatos

  • 3 years ago

    I am having trouble with the

    Code:
    ClientScript.RegisterClientScriptBlock(Of Boolean, "jsScriptConfirmOption")()[\code]


    I am using asp.net 2.0 and i found your code really useful. Unfortunately i dont know how to translate this one section of it.
    I've changed the use of the code slightly from not having one delete button, but an accept button and a delete button. I need a different action for either button. the accept buttton updates and of couse the delete button deletes. can anyone tell me what the correct syntex
    this is my code...

    Code:
    Sub Page_PreRender(ByVal Sender As Object, ByVal E As EventArgs)
           Dim nl As String = Environment.NewLine
           Dim jsScriptConfirmOption As New StringBuilder()
           With jsScriptConfirmOption


               .Append("<script language=JavaScript>" & nl)
               .Append("<!--" & nl & nl)


               .Append("function confirmDelete (frm) {" & nl & nl)
               .Append(" // loop through all elements" & nl & nl)
               .Append(" for (i=0; i<frm.length; i++) {" & nl & nl)
               .Append(" // Look for our checkboxes only" & nl)
               .Append(" if (frm.elements.name.indexOf ('CHKOption') !=-1) {" & nl & nl)
               .Append(" // If any are checked then confirm alert, otherwise nothing happens" & nl)
               .Append(" if(frm.elements.checked) {" & nl & nl)
               .Append(" return confirm ('Are you sure you want to delete your selection(s)?')" & nl & nl)
               .Append(" }" & nl)
               .Append(" }" & nl)
               .Append(" }" & nl)
               .Append(" }" & nl & nl)


               .Append("function confirmAccept (frm) {" & nl & nl)
               .Append(" // loop through all elements" & nl & nl)
               .Append(" for (i=0; i<frm.length; i++) {" & nl & nl)
               .Append(" // Look for our checkboxes only" & nl)
               .Append(" if (frm.elements.name.indexOf ('CHKOption') !=-1) {" & nl & nl)
               .Append(" // If any are checked then confirm alert, otherwise nothing happens" & nl)
               .Append(" if(frm.elements.checked) {" & nl & nl)
               .Append(" return confirm ('Are you sure you want to accept your selection(s)?')" & nl & nl)
               .Append(" }" & nl)
               .Append(" }" & nl)
               .Append(" }" & nl)
               .Append(" }" & nl & nl)


               .Append("/Using modified select_deselectAll script function of my original one,")
               .Append(" from Developerfusion.com forum members - ketcapli & thombo")
               .Append(" Forum Post - [http://www.developerfusion.co.uk/forums/topic-22773]
    /")


               .Append("function select_deselectAll (chkVal, idVal) {" & nl)
               .Append(" var frm = document.forms[0];" & nl)
               .Append(" if (idVal.indexOf('CHKOption') != -1 && chkVal == true){" & nl)
               .Append(" var AllAreSelected = true;" & nl)
               .Append(" for (i=0; i<frm.length; i++) {" & nl)
               .Append(" if (frm.elements.id.indexOf('CHKOption') != -1 && frm.elements.checked == false){ " & nl)
               .Append(" AllAreSelected = false;" & nl)
               .Append(" break;" & nl)
               .Append(" } " & nl)
               .Append(" } " & nl)
               .Append(" if(AllAreSelected == true){"