Click here to Skip to main content
Click here to Skip to main content

Multi-select ASP.NET datagrid

By , 7 Mar 2004
 

Sample image

Introduction

ASP.NET datagrid is a very powerful and flexible control, however some features like multi-select is not natively available. This article shows how easily this functionality can be achieved with a few simple tricks.

Background

One of the projects I was working on had a User Inteface requirement for multi-selection of grid rows. User wanted Hotmail or Yahoo style multi-selection facility along with highlighting the selection (hard part).

Using the code

After testing and applying some javascript and grid related coding techinque, I came up with the following working solution.

  • Add Template column for CHECKBOXES for selection (Hotmail/Yahoo style)
  • Add client-side onclick() and javascript for checkboxes, to highlight and mark checked rows.
  • Add server side CheckedChanged() event for preserving highlights. [because everytime on postback datagrid resets colors for the selection]
<Columns>
 <asp:TemplateColumn>
  <HeaderTemplate>
   <asp:CheckBox id="chkAll" 
      onclick="javascript:SelectAllCheckboxes(this);" runat="server" 
    AutoPostBack="false" ToolTip="Select/Deselect All" />
  </HeaderTemplate>
  <ItemTemplate> 
    <asp:CheckBox id="chkSelect" onclick="javascript:HighlightRow(this);"
        runat="server"OnCheckedChanged= "grdEmployees_CheckedChanged" 
        AutoPostBack="false" />
  </ItemTemplate> 
 </asp:TemplateColumn> 
</Columns>

SelectAllCheckBoxes()

This function is used to have Hotmail style selection, it iterate through every check box on the form and then selects/deselects the checkboxes.

HighlightRow()

The only challenge left was to highlight and un-highlight the rows on selection and deselection. For which, I used HighlightRow() function, please note one very important thing when using <asp:CheckBox> control. It surrounds <SPAN> tags around CHECKBOX and therfore in javascript you have to get the children of the <SPAN> tag.

    //-------------------------------------------------------------
    // Select all the checkboxes (Hotmail style)
    //-------------------------------------------------------------
    function SelectAllCheckboxes(spanChk){
    
    // Added as ASPX uses SPAN for checkbox 
    var oItem = spanChk.children;
    var theBox=oItem.item(0)
    xState=theBox.checked;    

        elm=theBox.form.elements;
        for(i=0;i<elm.length;i++)
        if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)
            {
            //elm[i].click();
            if(elm[i].checked!=xState)
            elm[i].click();
            //elm[i].checked=xState;
            }
    }

    //-------------------------------------------------------------
    //----Select highlish rows when the checkboxes are selected
    //
    // Note: The colors are hardcoded, however you can use 
    //       RegisterClientScript blocks methods to use Grid's
    //       ItemTemplates and SelectTemplates colors.
    //         for ex: grdEmployees.ItemStyle.BackColor OR
    //                 grdEmployees.SelectedItemStyle.BackColor
    //-------------------------------------------------------------
    function HighlightRow(chkB)    {
    var oItem = chkB.children;
    xState=oItem.item(0).checked;    
    if(xState)
        {chkB.parentElement.parentElement.style.backgroundColor='lightcoral';
           // grdEmployees.SelectedItemStyle.BackColor
         chkB.parentElement.parentElement.style.color='white'; 
           // grdEmployees.SelectedItemStyle.ForeColor
        }else 
        {chkB.parentElement.parentElement.style.backgroundColor='white'; 
             //grdEmployees.ItemStyle.BackColor
         chkB.parentElement.parentElement.style.color='black'; 
             //grdEmployees.ItemStyle.ForeColor
        }
    }
    // -->

This was the client side story. So far so good. One may argue why not use the plain simple HTML checkbox control? The answer is ASP.NET server control has a viewstate and therefore posting a page retains the rows selection.

Server Side

Now, On the server side we have to make sure the highlights are intact, because on every postback ASP.NET renders grid and loses the highlights. Following method is used for re-rendering the highlights.

Public Sub grdEmployees_CheckedChanged(ByVal sender As Object, _
    ByVal e As System.EventArgs)
  Dim chkTemp As CheckBox = CType(sender, CheckBox)

  Dim dgi As DataGridItem 

  dgi = CType(chkTemp.Parent.Parent, DataGridItem)
  If (chkTemp.Checked) Then 

    dgi.BackColor = grdEmployees.SelectedItemStyle.BackColor 
    dgi.ForeColor = grdEmployees.SelectedItemStyle.ForeColor
  Else 

    dgi.BackColor = grdEmployees.ItemStyle.BackColor
    dgi.ForeColor = grdEmployees.ItemStyle.ForeColor 
  End If
End Sub

Getting your selection

Its easy! Iterate through the DataGridItems collection and grab the checkbox [for ex. DemoGridItem.Cells(0).Controls(1)]. And verify its CHECKED property. Oh, also you can use DataKeyField of the dataset to grab specific datarows. Check out the attached code and you will love to find out how easy it is to multi-select rows.

Conclusion

Follow the downloaded code, you can simply use any SQL database. This is my very first article, hope .NET lovers would like it. Feedback is welcome.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Prashant Nayak (.Net Lover)
Web Developer
United States United States
Cranking code more than 12 years. Technical/Project lead/MCSD. Offered services to various industuries like S/W, Telecom, Publishing, Insurance etc.
 
When not on computer, I play/swim/read with my kids and help my better half (of course my lovely wife) to clean house. Solving challenging S/W problems is my passion. Hate non-productive meetings. Do lots of GOOGLE and Eat/Drink/Sleep around MSDN.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membermanoj kumar choubey7-Feb-12 19:30 
GeneralMy vote of 5memberMember 782175621-Apr-11 10:23 
GeneralMy vote of 1memberbadri vishal23-Nov-10 19:18 
GeneralMy vote of 1memberDima Pasko27-Aug-09 11:49 
GeneralMy vote of 1memberJitesh Sachdeva12-Jan-09 17:04 
GeneralMultiSelect via Client-SidememberTodd Lucas1-Sep-06 12:31 
GeneralRe: MultiSelect via Client-SidememberPatrick Olurotimi Ige19-Sep-06 14:44 
NewsMultiple Gridviews or Checkbox columnsmemberMcDude15-Jun-06 13:10 
GeneralRe: Multiple Gridviews or Checkbox columnsmemberCode Buster10-Aug-06 19:36 
Generalunselect check box based on others ckbxmemberJamshidi3-Mar-06 12:09 
GeneralCommand button in data GridmemberS.Das2-Mar-06 20:28 
GeneralJavascript FunctionsmemberShadi Rahmani4-Sep-05 21:40 
GeneralRe: Javascript Functionsmemberenjoycrack5-Sep-05 0:12 
AnswerRe: Javascript FunctionsmemberSasi Atia12-Feb-06 20:52 
GeneralRe: Javascript Functionsmemberhb3219-Mar-08 3:47 
Generalc# versionmemberLoic Deniel23-Aug-05 22:16 
GeneralRe: c# versionsussAnonymous26-Oct-05 8:04 
Questionhow to get cell Text when AutoGenerateColumns="false"memberhostlike4-Aug-05 19:57 
GeneralModified client scriptmemberdpadevet21-Jul-05 3:26 
GeneralRe: Modified client scriptmemberhtb huang19-Mar-07 12:32 
GeneralButton instead of CheckBoxmemberJureshka7-Jul-05 4:53 
GeneralMozilla Firefox Browersmembertaithien22-Jun-05 23:55 
GeneralRe: Mozilla Firefox Browersmemberwildwildwolf20-Jul-05 9:50 
Generalscript correctionmember][Turpa28-Mar-05 0:51 
General,memberHui Yee4-Mar-05 16:34 
Generalhope!membertengtium3-Mar-05 2:56 
GeneralRe: hope!memberzedaspintas5-Apr-05 23:35 
GeneralDude, this is been done before and better on DotNetJunkies. Be original!sussAnonymous9-Jan-05 6:13 
GeneralRe: Dude, this is been done before and better on DotNetJunkies. Be original!sussAnonymous10-Jan-05 3:22 
GeneralRe: Dude, this is been done before and better on DotNetJunkies. Be original!sussAnonymous31-Aug-05 2:30 
GeneralRe: Dude, this is been done before and better on DotNetJunkies. Be original!memberChetan Sharma14-Aug-06 11:51 
GeneralRe: Dude, this is been done before and better on DotNetJunkies. Be original!memberMikel Dublin24-Sep-07 0:16 
GeneralnothingsussAnonymous10-Dec-04 4:16 
GeneralDatagrid Check all function problemsussshiva kumar5828-Nov-04 22:27 
GeneralDatagrid Check all function problemmembershiva kumar5828-Nov-04 22:27 
GeneralDoesn't workmembercah_batak11-Nov-04 21:38 
GeneralTHX for sharingmemberesman21-Nov-04 13:50 
GeneralSome little BugfixingssussGrischa Brockhaus25-Oct-04 6:21 
GeneralRe: Some little Bugfixingsmembershakespeare218919-Dec-04 19:15 
Generalform.element problemmemberMrKhalid11-Sep-04 9:39 
GeneralData Gridmemberyathiraju_n9-Sep-04 19:39 
GeneralRe: Data Gridmemberrizingstar7730-Nov-05 11:24 
GeneralYea, it works...i did itmemberK.Nagalinga Reddy29-Aug-04 5:38 
GeneralRe: Yea, it works...i did itsussAnonymous6-May-05 9:35 
GeneralJust Great but I Would Like one Select..memberManolo Herrera18-Aug-04 7:51 
GeneralCheckedChanged event does not firememberBharat Gadhia18-Aug-04 6:49 
GeneralRe: CheckedChanged event does not firememberwildwildwolf19-Jul-05 12:16 
GeneralLoad form with check boxes populatedsussAnonymous13-Aug-04 13:55 
GeneralRe: Load form with check boxes populatedmemberPrashant Nayak (.Net Lover)16-Aug-04 3:15 
GeneralSome column not changememberQ_Quek8-Aug-04 18:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130617.1 | Last Updated 8 Mar 2004
Article Copyright 2003 by Prashant Nayak (.Net Lover)
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid