Add text highlighting in ASP.NET 2.0 GridView
2 04 2007I built an ASP.NET 2.0 web application [for the company I work for] that streamlined the deployment process to our production environment. It processed, tracked, archived, and notified automatically on each step of the deployment process.
So with that in mind, I’ll be showing you how to add text highlighting in a GridView; for example, a Date & Time column (i.e., red=overdue, green=still OK), which, at work, presented to the the technical group if a deployment was late or not. =0)
Here’s a screenshot:
Fig. 1.1 – Text highlighting in ASP.NET 2.0 GridView
Adding this feature is quite easy. The first thing you’ll need to do is add a RowDataBound event in the GridView code:
<asp:GridView OnRowDataBound="GridView_RowDataBound">
The second thing is add an ASP label within an ASP template field, like so:
<asp:TemplateField HeaderText="Date & Time" SortExpression="TargetDateTime"> <ItemTemplate> <asp:Label ID="lblTargetDateTime" runat="server" Text='<%# Eval("TargetDateTime") %>' /> </ItemTemplate> </asp:TemplateField>
Pretty simple so far, ‘ey? Now, to the last bread-and-butter step, the code-behind file:
using System.Drawing; private void GridView_RowDataBound(object sender, GridViewRowEventArgs e) { // Find control to add text highlighting if (e.Row.RowType == DataControlRowType.DataRow) { // Create Label datatype then cast and assign control Label dateTimeType = (Label)e.Row.FindControl("lblTargetDateTime"); // Instantiate new DateTime object DateTime dateTime = new DateTime(); dateTime = Convert.ToDateTime(dateTimeType.Text); // Set coloring based on date and time if (DateTime.Compare(dateTime, DateTime.Today) >= 0) dateTimeType.BackColor = Color.LawnGreen; else dateTimeType.BackColor = Color.Red; } }
That’s it! Using text highlighting in your GridView not only makes it look “pretty,” but also emphasizes a record’s importance based on colors.