Click here to Skip to main content
Licence 
First Posted 13 Jun 2006
Views 97,921
Bookmarked 55 times

Extending GridView by allowing Multiple Selections and Multi Column Sort

By | 13 Jun 2006 | Article
Extending GridView by allowing Multiple Selections, changing Selected row color and Multi Column Sort

Multiple selections and changing selected row color:

Gridview provides built in support for single row selection. Selecting multiple rows from the Gridview control is not difficult at all, however it will be nice if we can change the background Color of the selected row and can easily identify multiple selected rows. To implement this idea I searched on the internet but unfortunately couldn’t find any easy and optimal way to accomplish the task. There can be many solutions to implement the same idea however I believe the approach I am using is very easy and efficient.

 The HTML below shows a Gridview control with Data from Northwind Employees table. 

 <asp:GridView ID="DataGV" runat="server"  AutoGenerateColumns="False" cellpadding="4"

  GridLines="Horizontal" BackColor="White" BorderColor="#336666" BorderStyle="Double"

  BorderWidth="3px" Font-Bold="True" Font-Names="Verdana" Font-Size="X-Small"  Height="1px"

  Width="100%" AllowSorting="True" HorizontalAlign="Center" DataKeyNames="EmployeeID" 

  DataSourceID="SqlDataSource1" AllowPaging="True" PageSize="50">

        

           <RowStyle BackColor="White" ForeColor="#333333" />

            <Columns>

            

               <asp:TemplateField HeaderText="Select">

                <ItemTemplate>

                               <asp:CheckBox ID="CheckBox1" runat="server"/>

                          

      <asp:Label ID="LBLEmpID" runat="server" Text='<%# container.dataitem("EmployeeID") %>'

            Visible="false"></asp:Label>

       

                  </ItemTemplate>

                    <HeaderStyle HorizontalAlign="Left" />

                    <FooterStyle HorizontalAlign="Left" />

                </asp:TemplateField>                                  

                <asp:TemplateField HeaderText="Name"  SortExpression="LastName">

                    <HeaderStyle HorizontalAlign="Left" />

                    <ItemTemplate>

                        <asp:Label ID="LblName" runat="server" Text='<%# trim(Eval ("LastName")) + ", " + trim( Eval ("FirstName"))%>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>           

              

                  <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" >

                     <HeaderStyle HorizontalAlign="Left" />

                </asp:BoundField>                 

                        <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" >

                     <HeaderStyle HorizontalAlign="Left" />

                </asp:BoundField>               

                <asp:TemplateField HeaderText="HireDate" SortExpression="HireDate">

                      <ItemStyle HorizontalAlign="Right" />

                    <HeaderStyle HorizontalAlign="Right" />

                    <ItemTemplate>

                        <asp:Label ID="LblHireDate" runat="server" Text='<%# Bind("HireDate", "{0:d}") %>'></asp:Label>

                    </ItemTemplate>                       

                </asp:TemplateField>     

                                               

              </Columns>  

            

            <HeaderStyle BackColor="White" Font-Bold="True" ForeColor="Black" Font-Size="Small" VerticalAlign="Top"/>

            <AlternatingRowStyle BackColor="#D6E3F7" />

                        <FooterStyle BackColor="#009900" Font-Bold="True" ForeColor="White" Font-Size="Small" HorizontalAlign="Right" />  

                   <PagerSettings PageButtonCount="30" Mode="NumericFirstLast" NextPageText="" PreviousPageText="" Position="TopAndBottom" />

            <PagerStyle BackColor="Silver" ForeColor="White" HorizontalAlign="Center" Font-Names="Verdana" Font-Size="Small" />  

        </asp:GridView>

Now all you need to do is to paste these 5 lines of code in RowDataBound evenet handler of your Gridview control.

If e.Row.RowType = DataControlRowType.DataRow Then    '1

Dim Chk As CheckBox = e.Row.FindControl("CheckBox1")    '2

Page.ClientScript.RegisterStartupScript(Me.GetType(), "MyScript", " function HighlightSelected(colorcheckboxselected, RowState) { if (colorcheckboxselected.checked) colorcheckboxselected.parentElement.parentElement.style.backgroundColor='#FFAA63'; else { if (RowState=='0') colorcheckboxselected.parentElement.parentElement.style.backgroundColor='white'; else colorcheckboxselected.parentElement.parentElement.style.backgroundColor='#D6E3F7'; } }", True)    '3

Chk.Attributes.Add("onclick", "HighlightSelected(this,'" + Convert.ToString(e.Row.RowState) + "' );")    '4

End If    '5

The code also accounts for Alternating Row. If you are not using Alternating Row in your Gridview, you can easily modify the code accordingly. 

 

 

Multi column sort:

Gridview provides built in support for single column sorting. In some situations multiple column sort can be very helpful for the users e.g. sorting employees by Hire Date and then by Last name or City name. Again implementing multiple columns sort is quite simple task.

 

I implemented multiple sort by Checkboxlist, Label and button controls. The label displays the sorting criteria user selects by checking/unchecking Checkboxes, and Click event handler of button implements the multiple sort.  I wrote the following code in button’s click event handler.

         If ViewState("Direction") = SortDirection.Ascending Then

            ViewState("Direction") = SortDirection.Descending

        Else

            ViewState("Direction") = SortDirection.Ascending

        End If

         DataGV.Sort(SortingLBL.Text, ViewState("Direction"))

 

I also wanted to show the sort direction in which the columns were sorted so I added the following code in Grridview Sorting event handler to change the text/value property of the button.

         If ViewState("Direction") Is Nothing Then

         ElseIf ViewState("Direction") = SortDirection.Ascending Then

            MultipleSortBtn.Value = "Sort Descending"

         Else

            MultipleSortBtn.Value = "Sort Ascending"

        End If

 

 

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

Ali Khan (OKC)

Web Developer

United States United States

Member

I work for Hertz Corporation as System Developer /Analyst and have exposure to various development environments, web applications, databases, along with information and project management techniques.

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

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionHow to identify the value of the selected row in datagrid Pinmemberpistolpinoy14:47 27 Jun '11  
GeneralIt works fine! Pinmemberricpue5:52 1 Jun '09  
Questionfirefox problem PinmemberMember 470905221:18 6 Dec '07  
GeneralRe: firefox problem PinmemberTony Montana19:16 13 Feb '08  
GeneralThans and I've Q Pinmemberab_dc1:20 21 Nov '07  
Questionmultiple row selection Pinmemberlotusflower10:40 4 Sep '07  
GeneralExtending method to update cells Pinmemberbeish123:12 9 Aug '07  
QuestionOnly CheckBox gets highlighted Pinmemberosapunova2:08 20 Jul '07  
Thanks a lot for great solution. I have a small problem. I use your code and have only checkbox highlighted / un-highlighted. Not entire row. Thank you for your help.
AnswerRe: Only CheckBox gets highlighted Pinmemberosapunova7:07 20 Jul '07  
GeneralNice except after page load event fires IE 6 PinmemberTim Vandeweerd12:35 19 Nov '06  
Questionrow style chahge on condition Pinmemberdoddamani praveen4:48 25 Jul '06  
AnswerRe: row style chahge on condition PinmemberAli Khan (OKC)4:33 2 Aug '06  
GeneralThere is one problem Pinmemberdtarczynski2:12 11 Jul '06  
GeneralRe: There is one problem PinmemberAli Khan (OKC)4:53 11 Jul '06  
GeneralRe: There is one problem Pinmemberdtarczynski5:28 11 Jul '06  
GeneralExample Pinmemberovidiosilva17:34 3 Jul '06  
GeneralRe: Example PinmemberAli Khan (OKC)5:01 11 Jul '06  
GeneralGood Job PinmemberJennifer R4:18 30 Jun '06  
GeneralExcellent Article PinmemberRobertPJ11:18 21 Jun '06  

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120529.1 | Last Updated 13 Jun 2006
Article Copyright 2006 by Ali Khan (OKC)
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid