Sorting columns - modify background color of selected column header

Hi -

I have a datagrid that is set to allow sorting and paging.  It works great.  What I would like to do now, for usability sake, is to dynamically change the background color of the column header the user is sorting by.  I will like to do this dynamically as part of the sorting function.

For example: I have a datagrid with 3 columns with the headers "Company Name", "Production Name", and "Audition Dates".  By default the datagrid loads info sorted by the "Company Name" column.  I would like to dynamically set the background color of that header to red.  If the sorts by "Production Name" then the I'd like the background color for this column changes to red and the background color for "Company Name" goes to white.

Here is my code:
<Script Runat="Server">
Dim strSortField as String

Sub Page_Load
  If Not isPostBack Then
    BindDataGrid(Session( "SortField" )) 
  End If
End Sub

'Sort command - set the session variable to the users choice and resort the information in the datagrid
Sub dgrdAuditions_SortCommand (s as Object, e as DataGridSortCommandEventArgs)
  strSortField = e.SortExpression
  Session("SortField") = strSortField
End Sub

'Get data from database and bind to datagrid object
Sub BindDataGrid (strSortField)
  Dim conPubs As OleDbConnection
  Dim dadTitles As OleDBDataAdapter
  Dim dstTitles As DataSet
  Dim strSQL as String

  conPubs  = New OleDbConnection( "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source=c:\inetpub\wwwroot\411Net\theaterDB.mdb" ) 
  strSQL = "Select * From tblAuditions WHERE ExpireDate > Now Order By " & strSortField
  dadTitles = New OleDBDataAdapter( strSQL, conPubs )
  dstTitles = New DataSet
  dadTitles.Fill( dstTitles )

  dgrdTitles.DataSource = dstTitles
End Sub

'Paging command - page the information in the datagrid to the selected chunk
Sub dgrdTitles_PageIndexChanged( s As Object, e As DataGridPageChangedEventArgs )
  dgrdTitles.CurrentPageIndex = e.NewPageIndex
End Sub


(HTML removed for brevity....)

<form runat="server">
  Runat="Server" >

      <HeaderStyle HorizontalAlign="left" BackColor="#FFFFFF" ForeColor="#3D3DB6" Font-Name="Verdana, Arial, Helvetica, sans-serif" Font-Bold="true" Font-Size="smaller" /> 
      <ItemStyle VerticalAlign="top" BackColor="#F2F2F2" Font-Name="Verdana, Arial, Helvetica, sans-serif" Font-Size="smaller" /> 
      <AlternatingItemStyle BackColor="#E5E5E5" Font-Name="Verdana, Arial, Helvetica, sans-serif" Font-Size="smaller" /> 
      <FooterStyle HorizontalAlign="center" BackColor="#E8EBFD" ForeColor="#3D3DB6" Font-Name="Verdana, Arial, Helvetica, sans-serif" Font-Bold="true" Font-Size="smaller" /> 
      <PagerStyle HorizontalAlign="center" BackColor="white" Font-Name="Verdana, Arial, Helvetica, sans-serif" Font-Size="smaller" /> 
      <asp:BoundColumn DataField="ID"
      <asp:BoundColumn DataField="CompanyName"
        HeaderText="Company Name"
        HeaderText="Production Name"
      <asp:BoundColumn DataField="AuditionDates"
        HeaderText="Audition Dates"


What is the best way to achieve this?  Is there a way that I can get the index of the selected column from the sorting function?  Then I could loop through the datagrid columns and reset the background colors of the headers.  I want to reuse this code for multiple datagrids, which may or may not have the same number of columns and definitely have different text for the headers.

Any assistance would be great!


11/28/2005 4:24:59 AM 72751 articles. 3 followers. Follow

2 Replies

Similar Articles

[PageSpeed] 39

This should help you to get started - put it into the SortCommand event handler before the databindign happens:
For Each colThis As DataGridColumn In DataGrid1.Columns
            If colThis.SortExpression = e.SortExpression Then
                colThis.ItemStyle.BackColor = Drawing.Color.Red
                colThis.ItemStyle.BackColor = Drawing.Color.White
            End If
This is a basic way of doing what you want and you can optimize it further if you want(adding header styles, making colours stored with the datagrid itself and setting only a background of previously used column instead of all the columns)


Bug [MCSD]
11/28/2005 1:24:41 PM

Thanks for the help!  I was able to successfully implement your idea, with a few tweaks of my own. 

For anyone interested, here is the solution I came up with.  The following code will set the CssClass for the selected column header to provide a visual clue as to which column is sorted.
Sub UpdateColumnHeaders(ByVal dg As DataGrid, SortExpression as String)
   Dim c As DataGridColumn
   For Each c In dg.Columns
      If c.SortExpression = SortExpression Then
        c.HeaderStyle.CssClass = "Sorted"
        c.HeaderStyle.CssClass = "NotSorted"
      End If
End Sub

For the CSS, I created the following:
.Sorted, .Sorted a, .Sorted a:link, .Sorted a:active {
  background-color: #009;
  text-decoration: none;
  font-weight: bold;

.Sorted a:hover, .Sorted a:visited {
  background-color: #009;
  text-decoration: underline;

.NotSorted {

Happy coding and thanks again!

11/29/2005 1:25:34 AM

Similar Artilces:

When is a column not a column?
I have several extremely similar datawindows that I have to maintain that go against the same table. Recently, I had to add a column to that table, and also add the column to ALL of these datawindows that go against this table. I added the column to the first datawindow, set up the edit control style, etc. I then did a copy/paste of the columns edit control to the remaining dw's (of course remembering to first add the column in SQL). Everything (update props, column specs, column props) seems to indicate that the pasted column is linked to the column I selected, HOWEVER, when I...

Gridview sorted column header font color
I have a gridview and one of the columns allows sorting.  This particular column header acts as a link and the font is displayed in the default browsers link color instead of the same color as the other columns.  I know this is because it is a link but how can I get it to always be the color I want?  For instance white?  But only in the grid not in the whole page? It's a known bug. It's fixed in the July CTP and for the final release.This posting is provided "AS IS" with no warranties, and confers no rights. Do I have to do a complete uninstall of the current version ...

Can you control selectability of DataGrid column headers?
We have a DataTable with sorting enabled.  The person that I am working for has a complaint:  he wants the user to be able to select a column for sorting whenever the mouse is over the text in the header text of the column;  as things stand now, the cursor must be positioned  just below the text before the browser will allow selection.  Is there a way to control this, or  is this functionality that is internal to the browser? This behavior appears to only be an issue in Internet Explorer, not Firefox. the sort headers are simply an anchor...

Datagrid sort -Sorting a column which is mapped to database column
How do I sort a datagrid column ,which is not mapped to database column. I'm able to sort other columns from the same datagrid which are mapped to database column and this grid has one of the columns which is not mapped to database column. But need to know how to sort the column which is not mapped to database column.     needtoknow: How do I sort a datagrid column ,which is not mapped to database column. I'm able to sort other columns from the same datagrid which are mapped to database column and this grid has one of the columns which is not mapped to database ...

2 select columns in a datagrid, how to pick up which column selected?
I have a datagrid with 2 button columns 1: buttonColumn.Text="Se", 2: uttonColumn.Text="Velg". Both have the same CommandName (=Select). In my sub, DataGrid_ItemCommand(sender As Object, e As DataGridCommandEventArgs), I want to determine, in my sub, which of the columns was selected. How do I do that? Please advise, Tom Do they have to have the same commandname? You're apparently not doing the standard SelectCommand stuff (since you're using the ItemCommand), so you could just check the different commandnames and execute accordingly. If you seriou...

How I sort the gridview column after column
I have the following columns in my gridview(VB) Type   FirstName   LastName    Company   City How I can sort the gridview firstly by column 1, after that by column 2 and so on. Thanks in advance.   You can write your SQL SELECT statement this way: SELECT Type ,  FirstName,   LastName,    Company,   City  FROM yourtable ORDER BY 1 ASC, 2, 3,4, 5 OR SELECT Type,  FirstName,   LastName,    Company,   City  FROM yourtable ORDER BY  Type&...

Sorting Columns within columns
In sent items, I need to be able to sort first by 'To' and then by 'Date' so that all mail sent to one person is grouped together and in date order. (Bit like the sort you can do in Excel).There only appears to be one sort option. Any ideas anyone? Sort by date first, then by the To, as Sorts normally do a minimum movement approach, that should get you what you want, but it would always be a manual process - you can't store the double sort Cheers Dave -- Dave Parkes [NSCS] Occasionally resident at You can regist...

Header column sorting
Hello all ; We have a u_dw with 5 columns one column have edit style of dddw. When we sorting this column by clicking it's header it's sorts the column by it's code and not by the display column. How can we change that behavior , that the sorting will sort by the display value ? Thanks Here's one generic solution: For all dddw's, add a computed column with a standard name such as <dddw_column_name>_display. For the expression use "LookUpDisplay ( column )". Extend PFC to check for exis...

Is there a way to add extra control to header of a Grid column, but still keep the default column name? thanks
I am using Grid, and I add template field <asp:TemplateField HeaderText="name" SortExpression="something">if I want to have special header, I can use HeaderTemplate, but with HeaderTemplate added ,the headertext will not show, if there a way I can just add a control beside the headertext? since I don't want to handle the column sort. thanks I am sure there is a better way to do this, but in the past I have used the following method although I left out the commandname and arguments protected void GridView1_DataBound(object sender, EventArgs e) { string celltext = GridView1.H...

How I can get the column header name when i clicked on the concerned column header
Hi All I had a problem in getting the columnheader name . I had tried with dw.getcolumnname but not successfull . I was in very big dilema where to write the code(i mean what 'event') . Suppose i had a fullname as my columnheader then i should able to get the fullname when i click on that column. thanks vasu Vasu: You will want to code this in the clicked event. You can look at GetBandatPointer() and GetObjectatPointer() functions in help. HTH, Austin "vasu" <> wrote in message ...

Sort on column without highlighting the column
Hi there, I have a grid style datawindow and when I click the column header in order to sort the data the entire column is selected (highlighted). Is there a way to sort by clicking on the column header but without highlighting the entire column? Thanks, Gerry. An aside. I can turn the grid property off, but then I loose the capability to move and resize the columns. Gerry. On 21 Apr 2004 09:35:52 -0700, Gerry <> wrote: >Hi there, > >I have a grid style datawindow and when I click the column header in >order to sort the data the enti...

selecting where cloumn = column OR column = value
Hi I have a gridview with a sql data source and a few drop down lists where i choose values to sorth what i would like to retrive from the table. The problem im facing is that when i pass values to the database, i can sort out and retrive my items when both my listboxes have selected values. But when i want to select everything from the table where the column = clumn or cloumn = value i dont get anything back. I have 2 dropdown lists. One for category and one for location. These are populated drom the database by selecting the column and retriving destinct values. I have a function t...

The performance of query was good when only select a few columns, and slow when number of columns in SELECT increased
Hi! I have a query like this: select t1.port_num, t1.asof_date, t1.curr_code, t1.pl1, t1.pl2, t1.pl3 from test_table1 t1, test_table2 t2 where t1.port_num = t2.port_num and .... I ran the SHOWNPLAN on this query, the query plan showed that the indexes were used. The test_table1 has about 1.7 million records, test_tables about 10,000 records. Table Index LOCK ------------------ --------------------------- ---------------- ------ test_table1 ...

Select, one column into various columns
Hello, What I want to do is have a select statement against a table that looks something like this: USER_ID                                   TYPE_OF_LEAVE                                   VALID_FROM         &n...

Column Header Sort
I'm using my own sort service to put an arrow on the header of the column of my grid dw. When I sort the dw with the "Sorting multiple columns" window, it works fine. When I use a click on the column header it doesn't work The of_setcolumnheader is true, all the names of the columns are xxxxx_t and it works last week. What's wrong? Francis ---== Posted via the PFCGuide Web Newsreader ==--- Are you using a bitmap to display the arrow ? If so, could it be that you are clicking on the bitmap rather than...

Web resources about - Sorting columns - modify background color of selected column header -

Background Music (album) - Wikipedia, the free encyclopedia
^ Morris, Kurt. " Background Music – Overview" . Allmusic . Rovi Corporation . . Retrieved ...

Android App OStream Speeds Up Facebook Experience By Synchronizing Content In Background
Facebook’s newly revamped Android application was rebuilt with a focus on speed, and startup oStream wants to help users of devices on that operating ...

Background for Dick Armey’s Endorsement of “Nothing for the Nation”
To truly grasp the profound nature of Dick Armey’s endorsement of Nothing for the Nation: Who Got What Out of Iraq, one must understand the events ...

Parse launches analytics tool, background jobs feature at first Developer Day conference
Parse , the Facebook-owned app development platform, held its first Developer Day conference in San Francisco Thursday, and the company launched ...

Easy Background Tasks in ASP.NET
As I work on the badge implementation for Stack Overflow, I needed a way to call the code that detects and awards the badges out of band. Traditionally ...

Wallpaper Studio Pro HD - Themes & Backgrounds for iPad on the iTunes App Store
Get Wallpaper Studio Pro HD - Themes & Backgrounds on the App Store. See screenshots and ratings, and read customer reviews.

Rolling background checks to protect children
BACKGROUND screening checks will be monitored in real-time to ensure people who commit offences cannot continue to work with children and other ...

Record for US gun background checks
More US residents applied to purchase handguns, rifles and other firearms from licensed dealers on Black Friday than any other day on record, ...

AP: Executive Action Imminent To Expand Background Checks For Gun-Buyers
AP: Executive Action Imminent To Expand Background Checks For Gun-Buyers

Rubio: Gun background checks couldn't have stopped "terror attack"
The Florida senator says gun violence occurs, not because of lax gun laws, but because of mental health issues and cultural changes in the U.S. ...

Resources last updated: 12/14/2015 12:16:37 PM