Saturday, August 7, 2010

Highlight a table row with 1 line of code

Introduction

It is a usual requirement to highlight a table row based on specific conditions. ISD has a CCW (Highlight a table row based on a condition) designed exactly for that purpose. However, using the CCW is a little tedious. First, you need to make the row "runat = server" in the designer. Then, run through the wizard, which inserts more than 20 lines of code into code-behind. (Even after comments removed, there are still about 10 lines of code.)

This article will show you a much simpler way to highlight a table row. After initial setup, only 1 line of code is needed. I don't think you can get it any simpler.

Initial Setup

Step 1: Add jQuery support

In the master page's prologue, add the following line (line 3):

    <asp:ScriptReference  Path="~/SetFocus.js"  />
    <asp:ScriptReference  Path="http://code.jquery.com/jquery-1.4.2.min.js"  />


Step 2: Add SetRowAppearance() method

In BaseApplicationRecordContorl class, insert the following method.
C#
public void SetRowAppearance(string cssName) {
  WebControl ctrl = Controls
    .OfType<WebControl>()
    .Where(c => !(c is Literal) && c.Visible)
    .First();
  string script = string.Format(
    "$('td', $('#{0}').closest('tr')).addClass('{1}');",
    ctrl.ClientID,
    cssName);
  ScriptManager.RegisterStartupScript(this, GetType(), ClientID, script, true);
}
VB
Public Sub SetRowAppearance(cssName As String)
    Dim ctrl As WebControl = Controls.OfType(Of WebControl)().Where(Function(c) Not (TypeOf c Is Literal) AndAlso c.Visible).First()
    Dim script As String = String.Format("$('td', $('#{0}').closest('tr')).addClass('{1}');", ctrl.ClientID, cssName)
    ScriptManager.RegisterStartupScript(Me, [GetType](), ClientID, script, True)
End Sub

Step 3: Add highlighted css class(es)

In your project App_Theme's Style.css, add as many css classes as you like. For example,
td .highlighted { 
  background-color: #FF99FF;
}
Note:
These steps are required only once for a project. They can also be setup in ISD's project template. Then the functionality will be available automatically in new projects.

Highlight a row

Here is the one-liner to highlight a row. Please note that the example is called from within a TableControlRow class.
C#
if (SomeCondition)
  this.SetRowAppearance("highlighted");
VB
If SomeCondition Then
  Me.SetRowAppearance("highlighted")
End If
Note:
Having a closer look at SetRowAppearance() method, you will notice that it needs a non-Literal WebControl as a "seed" to locate the row at client side. If your table row contains any ImageButtons, CheckBoxes, DropDownLists, etc, the method will work just fine. In case your row contains only Literals, switch one of them to Label.

1 comment:

GC said...

Hi Jing:

Great posts.

I am getting a Collections error for the

Could you please specify the full qualified collection name. I am using the latest version of ISD.