Click here to Skip to main content
13,054,018 members (75,629 online)
Click here to Skip to main content
Add your own
alternative version


58 bookmarked
Posted 13 Jun 2006

Extending GridView by allowing Multiple Selections and Multi Column Sort

, 13 Jun 2006
Rate this:
Please Sign up or sign in to vote.
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" />

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

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

                   <HeaderStyle HorizontalAlign="Left" />
                   <FooterStyle HorizontalAlign="Left" />
               <asp:TemplateField HeaderText="Name"  SortExpression="LastName">
                   <HeaderStyle HorizontalAlign="Left" />
                       <asp:Label ID="LblName" runat="server"
                           Text='<%# trim(Eval ("LastName")) + ", " + trim( Eval ("FirstName"))%>'></asp:Label>

                 <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" >
                    <HeaderStyle HorizontalAlign="Left" />
                       <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" >
                    <HeaderStyle HorizontalAlign="Left" />
               <asp:TemplateField HeaderText="HireDate" SortExpression="HireDate">
                     <ItemStyle HorizontalAlign="Right" />
                   <HeaderStyle HorizontalAlign="Right" />
                       <asp:Label ID="LblHireDate" runat="server" Text='<%# Bind("HireDate",
                           "{0:d}") %>'></asp:Label>


           <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" />

Now all you need to do is to paste these 5 lines of code in <code>RowDataBound event 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)'#FFAA63'; else { if (RowState=='0')'white'; else'#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
    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"
    MultipleSortBtn.Value = "Sort Ascending"
End If


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Ali Khan (OKC)
Web Developer
United States United States
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.

You may also be interested in...

Comments and Discussions

GeneralSort data by only three or four column in gridview in c# Pin
sagarpatel895-Apr-16 0:53
membersagarpatel895-Apr-16 0:53 
QuestionHow to identify the value of the selected row in datagrid Pin
pistolpinoy27-Jun-11 14:47
memberpistolpinoy27-Jun-11 14:47 
GeneralIt works fine! Pin
ricpue1-Jun-09 5:52
memberricpue1-Jun-09 5:52 
Questionfirefox problem Pin
Member 47090526-Dec-07 21:18
memberMember 47090526-Dec-07 21:18 
GeneralRe: firefox problem Pin
Tony Montana13-Feb-08 19:16
memberTony Montana13-Feb-08 19:16 
GeneralThans and I've Q Pin
ab_dc21-Nov-07 1:20
memberab_dc21-Nov-07 1:20 
Questionmultiple row selection Pin
lotusflower4-Sep-07 10:40
memberlotusflower4-Sep-07 10:40 
GeneralExtending method to update cells Pin
beish19-Aug-07 23:12
memberbeish19-Aug-07 23:12 
QuestionOnly CheckBox gets highlighted Pin
osapunova20-Jul-07 2:08
memberosapunova20-Jul-07 2:08 
AnswerRe: Only CheckBox gets highlighted Pin
osapunova20-Jul-07 7:07
memberosapunova20-Jul-07 7:07 
GeneralNice except after page load event fires IE 6 Pin
Tim Vandeweerd19-Nov-06 12:35
memberTim Vandeweerd19-Nov-06 12:35 
Questionrow style chahge on condition Pin
doddamani praveen25-Jul-06 4:48
memberdoddamani praveen25-Jul-06 4:48 
AnswerRe: row style chahge on condition Pin
Ali Khan (OKC)2-Aug-06 4:33
memberAli Khan (OKC)2-Aug-06 4:33 
GeneralThere is one problem Pin
dtarczynski11-Jul-06 2:12
memberdtarczynski11-Jul-06 2:12 
GeneralRe: There is one problem Pin
Ali Khan (OKC)11-Jul-06 4:53
memberAli Khan (OKC)11-Jul-06 4:53 
GeneralRe: There is one problem Pin
dtarczynski11-Jul-06 5:28
memberdtarczynski11-Jul-06 5:28 
GeneralExample Pin
ovidiosilva3-Jul-06 17:34
memberovidiosilva3-Jul-06 17:34 
GeneralRe: Example Pin
Ali Khan (OKC)11-Jul-06 5:01
memberAli Khan (OKC)11-Jul-06 5:01 
GeneralGood Job Pin
Jennifer R30-Jun-06 4:18
memberJennifer R30-Jun-06 4:18 
GeneralExcellent Article Pin
RobertPJ21-Jun-06 11:18
memberRobertPJ21-Jun-06 11:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 13 Jun 2006
Article Copyright 2006 by Ali Khan (OKC)
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid