Click here to Skip to main content
15,879,535 members
Articles / Web Development / ASP.NET
Article

Using JavaScript and CSS to Enhance Your ASP.NET DataGrid

Rate me:
Please Sign up or sign in to vote.
4.09/5 (7 votes)
4 Jan 2006CPOL5 min read 88.3K   203   38   4
Demonstrates how to apply JavaScript functionality and CSS effects to an ASP.NET DataGrid.

Introduction

This article will show you how to implement client-side JavaScript functionality and Cascading Style Sheets using an ASP.NET DataGrid.

Background

Visual Studio .NET has provided programmers with a powerful control in the ASP.NET DataGrid. At first, after having used the Windows Forms DataGrid for some time, I wasn't duly impressed with the web version. However, after using it for some time, the ASP.NET DataGrid has proven to be an extremely effective presentation tool. In this article, I'll show you how to add even more functionality to your ASP.NET DataGrid.

Using the code

For those of you browsing for an example of using AJAX in your code, this isn't it. I will post (in the near future) an article about implementing AJAX into your DataGrids. This article covers only the inner working of how to add JavaScript functionality to events in your ASP.NET DataGrid.

Setting up the project

I'm going to show you a really simple way of doing this, since, like many programmers, I'm lazy. I'll show you how to add all sorts of cool UI functionality to a DataGrid using an event (on the C# side) and about three functions (on the JavaScript side). If you want to get the full benefit from this article, you should have a little bit of background knowledge using Cascading Style Sheets (CSS), since that will be the basis of a lot of the UI effects we're after.

Go ahead and create a new ASP.NET Web Application, and call it JavaScriptDatagrid. Create the required folders as shown in the solution diagram below. You'll notice that I created two folders: /css and /scripts. You'll only need the /css folder with a CSS file in it for this example. The /scripts folder will come with the downloaded solution, and contains all of the JavaScript that is used in the solution, in case you're like me, and you don't like having all those functions sitting in the head of your HTML document.

Sample Image - JSDG1.gif

Designing the page

The CSS

In my solution, I just added a simple HTML table, and dragged an ASP.NET DataGrid control onto it, and added a PushButton column. I provide a method in the code for doing a generic population of the grid (just so we have some sample data to play with) which I won't include here. You'll need to add the following CSS classes to your blank style sheet:

HTML
.button_down
{
    color: Red;
    border: inset 2px;
}

.button_up
{
    color: Black;
    border: outset 2px;
}

.alt_row_highlight
{
    background-color: Yellow;
}

.alt_row_nohighlight
{
    background-color: White;
}

.row_highlight
{
    background-color: Cyan;
}

.row_nohighlight
{
    background-color: White;
}

The JavaScript

Once you have that set up, you'll want to add the following four JavaScript functions to the HTML view of your page (or your externally called JavaScript file):

This function will create a client-side JavaScript confirm dialog:

JavaScript
function showConfirm()
{
    var answer = confirm ("You can use this to confirm an action, " + 
                 "such as a deletion or an update. It's important " + 
                 "to note that if you click Cancel, the page will not post back.")
    if (answer)
        return true;
    else
        return false;
}

This function pops up a simple JavaScript alert box:

JavaScript
function showAlert(strText)
{
    alert("You entered: [" + strText + "] It will be added " + 
          "to the textbox on this page when you click OK.");
}

This function opens a JavaScript prompt to allow a user to enter data:

JavaScript
function promptUser()
{
    var answer = prompt("Enter some data to display in the label:","")
    showAlert(answer);
    document.getElementById('txtInfo').value = answer;
}

This function will change the CSS class on an object:

JavaScript
function classChange(styleChange,item) 
{
    item.className = styleChange;
}

Implementation

Now that we have the JavaScript functions on the page, it's time to start implementing the functionality into our DataGrid. Create an ItemCreated event for your DataGrid. Since my DataGrid is called dgJSTest, I'll provide the following function below:

C#
private void dgJSTest_ItemCreated(object sender, 
        System.Web.UI.WebControls.DataGridItemEventArgs e)
{
    switch (e.Item.ItemType)
    {
        case ListItemType.AlternatingItem:
        {
            Button btn = (Button)e.Item.Cells[0].Controls[0];
            //Apply a click event to show a javascript prompt

            btn.Attributes.Add("onclick", "promptUser();");
            btn.Text = "Prompt";
            btn.Width = 100;
            //Apply button mouseovers

            btn.Attributes.Add("onmouseover", "classChange('button_down',this);");
            btn.Attributes.Add("onmouseout", "classChange('button_up',this);");
            //Apply row mouseovers

            e.Item.Attributes.Add("onmouseover", "classChange('alt_row_highlight',this);");
            e.Item.Attributes.Add("onmouseout", "classChange('alt_row_nohighlight',this);");
            break;
        }
        case ListItemType.Item:
        {
            Button btn = (Button)e.Item.Cells[0].Controls[0];
            //Apply a click event to show a confirm dialog

            btn.Attributes.Add("onclick", "return showConfirm('Are you sure' + 
                               ' you want to click this button?');");
            btn.Text = "Confirm";
            btn.Width = 100;
            //Apply mouseovers

            btn.Attributes.Add("onmouseover", "classChange('button_down',this);");
            btn.Attributes.Add("onmouseout", "classChange('button_up',this);");
            //Apply row mouseovers

            e.Item.Attributes.Add("onmouseover", "classChange('row_highlight',this);");
            e.Item.Attributes.Add("onmouseout", "classChange('row_nohighlight',this);");
            break;
        }
    }
}

We are doing a few things in this single function. First, when the ItemCreated delegate fires, we ascertain the item type. ItemType comes from the ListItemType enumeration, and they're pretty easy to figure out. In this example, I use Item and AlternatingItem to illustrate the effect. Our first step is to locate the button (column) we've added to the DataGrid. Once we cast this control as a type Button (you can utilize just about any control added to a DataGrid in the same way), we'll apply our functionality to the OnClick, OnMouseOver, and OnMouseOut events. You'll see we also set some properties of the button at runtime. Our main functionality comes from the Attributes.Add() method of each object. It allows us to add a JavaScript event handler to each control at runtime. From there, all we are doing is calling our JavaScript functions. That really is all there is to it! I've attached a screenshot below (there are some points of interest below the screenshot):

Image 2

Points of interest

In the example, I've also demonstrated how you can add the result from a JavaScript prompt to a textbox control on a page. This is also effectively done using hidden inputs. You can easily have the resulting response from a JavaScript prompt output to a hidden input, where the input is set to runat=server, and access the value of that input in your C# code-behind. Minimizing postbacks makes the user's experience to your website a lot more pleasant.

An item of interest is the background-image element in your style sheet. You can provide some very cool effects to your mouse-overs using the following CSS:

HTML
.row_highlight
{
    background-image: url(../img/bg_in.gif);
    background-repeat: repeat-x;
}

.row_nohighlight
{
    background-image: url(../img/bg_out.gif);
    background-repeat: repeat-x;
}

Sample Image - bg_out.gif Sample Image - bg_out.gif

You can utilize the images above (or create your own) for a very cool mouse-over effect on your DataGrid. If you decide to use the images, you'll want to ensure the height of your DataGrid's rows don't exceed the height of the image (20px. in this case), or else you get a sloppy effect.

And, last but not least, I've also included a sample JavaScript function with the download that shows you how to apply the row highlighting effect without using any C# code-behind. This is for any of you out there who might want to use this functionality in a standard HTML page (yes, it works with a standard HTML table, since that's pretty much how a DataGrid renders, with a few differences).

License

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


Written By
Software Developer (Senior) CentralReach
United States United States
I have worked professionally in IT since 2004, and as a software architect since 2008, specializing in user interface design and experience, something I am still extremely passionate about. In 2013 I moved into management, and since then I've held positions as Director of Product Development, Director of Engineering, and Practice Director.

Comments and Discussions

 
GeneralDatagrid issue Pin
karanji18-Dec-06 23:31
karanji18-Dec-06 23:31 
GeneralRe: Datagrid issue Pin
DreamInHex19-Dec-06 4:27
DreamInHex19-Dec-06 4:27 
Questiondownload link? Pin
NeverHeardOfMe4-Jan-06 5:22
NeverHeardOfMe4-Jan-06 5:22 
AnswerRe: download link? Pin
DreamInHex4-Jan-06 8:44
DreamInHex4-Jan-06 8:44 

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.