Click here to Skip to main content
Click here to Skip to main content

Using JavaScript To Select GridView Rows

By , 22 May 2007
 
Prize winner in Competition "Best ASP.NET article of Apr 2007"

Contents

Introduction

If you have ever used the ASP.NET GridView control (I have only just started learning ASP.NET, so please forgive me, if I get some of the names of things slightly wrong), you will know that the user is able to select rows within the grid. While this is a great feature of the GridView control, you would normally have to select a row using a CommandField or a hyperlink column with a CommandName="Select" property included. This, I think just looks a bit naff.

Surely, there is a better way. Well luckily there is, we can simply use client side JavaScript to do the row selection. That is what this article is all about. The code is minimal, and very easy to understand, but I think it is useful code, and I also think it is something that anyone that works with the GridView control should know.

Sample Table Used

I am actually using Microsoft SQL Server 2005, with the attached DEMO app. You will need to change the Web.Config file to point to your own SQL Server installation. For the GridView data I have chosen to use the master database, dbo.spt_values table, that comes with SQL Server 2005

The master table structure, and the query that the demo app uses are as follows:

How It Works

It's very easy actually, all we do is use a <asp:SqlDataSource/> web control to bind to the master database (remember you'll need to change the connection section in the web.config to point at your own database). The GridView data is obtained using a simple select statement SELECT TOP 5 * FROM dbo.spt_values table, and then have the GridView control use this <asp:SqlDataSource/>. Then we include a <asp:CommandField ShowSelectButton="True" Visible="False" /> field which we set to be invisible.

One more point to note is that the Page must have the following directive set in order to allow the JavaScript postback mechanism that is described below.

So in the page declarations section, ensure the following is set EnableEventValidation="false"

So that's the ASPX file (web form), but we also need to write some code in the code behind and use a little bit of JavaScript. So the code behind (C# for the attached demo) looks like :

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class grid : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// Check the item being bound is actually a DataRow, if it is,     
    /// wire up the required html events and attach the relevant JavaScripts
    /// </summary>
    /// <param name="sender">GridView1</param>
    /// <param name="e">The event args for the RowDataBound event</param>
    protected void GridView1_RowDataBound(object sender, 
                    GridViewRowEventArgs e)
    {
        //check the item being bound is actually a DataRow, if it is, 
        //wire up the required html events and attach the relevant JavaScripts
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = 
                "javascript:setMouseOverColor(this);";
            e.Row.Attributes["onmouseout"] = 
                "javascript:setMouseOutColor(this);";
            e.Row.Attributes["onclick"] = 
            ClientScript.GetPostBackClientHyperlink
                (this.GridView1, "Select$" + e.Row.RowIndex);
        }
    }

    /// <summary>
    /// Show the 1st cell value in the web pages TextBox to show the user
    /// it is actually selecting rows at client side
    /// </summary>
    /// <param name="sender"> GridView1</param>
    /// <param name="e">The event args for the SelectedIndexChanged event
    ///    </param>
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        TextBox1.Text = GridView1.SelectedRow.Cells[1].Text;
    }
}

This works by attaching 2 JavaScripts to the current GridView row.

  • One for onmouseover which simply sets the current row to be highlighted a certain color. I chose Yellow, but you can change that.
  • One for onmouseout which simply resets the current row to be the original color

There is also a clever line as given below:

e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink
                (this.GridView1, "Select$" + e.Row.RowIndex);

This cunningly creates a client hyperlink which posts back the current ASPX web form, using the Select$0 to select row 0 say.

The ASPX pages JavaScript is as follows:

<script language="javascript" type="text/javascript">
var oldgridSelectedColor;

function setMouseOverColor(element)
{
    oldgridSelectedColor = element.style.backgroundColor;
    element.style.backgroundColor='yellow';
    element.style.cursor='hand';
    element.style.textDecoration='underline';
}

function setMouseOutColor(element)
{
    element.style.backgroundColor=oldgridSelectedColor;
    element.style.textDecoration='none';
}
</script>

And that's it. So what we get is now a nice GridView control, that we select rows with using JavaScript, and it looks like a table, rather than a table plus some nasty SELECT button, or a hyperlink column (that is only being used as a row selection method anyway).

That's it

And that as they say is that. Simple wasn't it. Probably my most simple article yet. But I think it's a useful one, I have always wondered how my online bank did produced such a nice grid.

So What Do You Think ?

I would just like to ask, if you liked the article please vote for it, and leave some comments, as it lets me know if the article was at the right level or not, and whether it contained what people need to know.

Conclusion

Well that's it actually. Although the code is very simple, I'm sure you'll agree this JavaScript selection method sure looks better than having a button column, or a hyperlink column to do the row selection. And it's more intuitive, I think. The users simply point and click the row they want, job done.

History

  • v1.0 - 22/05/07

License

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

About the Author

Sacha Barber
Software Developer (Senior)
United Kingdom United Kingdom
Member
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)
 
- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence
 
Both of these at Sussex University UK.
 
Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Generalthanks - very easy and useful!memberRobbSadler20 Nov '07 - 5:36 
I appreciate you taking the time to put this up. I knew basically what I wanted to do, and figured it was doable in this way, but as always lacked the time, and thus was hoping someone would have posted something.
 
And you did.
 
And - it was very easy - I had it integrated into my apsx page in minutes.
 
Thanks again!
 
Robb
GeneralRe: thanks - very easy and useful!memberSacha Barber20 Nov '07 - 6:34 
Yeah I think it makes grid look much better.
 
Thanks
 
Sacha Barber
A Modern Geek - I cook, I clean, I drink, I Program. Modern or what?
 
My Blog : sachabarber.net

Generalredirectionmemberxiaota21 Oct '07 - 2:16 
Hi,
After clicking, is that possible to redirect to another web page? (such as an HyperLinkField & to recover the Id of the selected row with the Request.QueryString)
 
best regards
 
bruno
GeneralRe: redirectionmemberSacha Barber21 Oct '07 - 11:07 
I would say this may not be possible, as this uses the javascript SELECT that is found in the microsoft .axd file that does the select using javascript. However the selected index could be put in the session, and im sure you could get it to redirect somehow.
 
BUt you have to look into the javascript that microsoft use, in the page rendering there is reference to an .AXD file. Have a look at that file by puttin the name of the .axd file into browser and do search for the select thing that is doing the select on the grid.
 
There is a selected index changed so you could hook into that and use the selected index in session, do redirect and grab it out of session on another page. Im hoping this event is still fired if using the javascript to do selection.
 
Anyway there are some ideas. Thats all I could say really.
 
Sacha Barber
A Modern Geek - I cook, I clean, I drink, I Program. Modern or what?
 
My Blog : sachabarber.net

Questionweb.config recompile errormemberMundo20927 Sep '07 - 23:03 
Nice article Sacha. But when I try to run the code, having altered web.config to reflect my SQL Server 2005 installation I keep getting the following compile error:
'<', hexadecimal value 0x3C, is an invalid attribute character. Line 4, position 68.
 
It's as if VS is ignoring my change of the Data Source attribute. In my case I'm simply changing it to localhost. This sounds like a simple mistake somewhere on my behalf, and appreciate it's probably nothing to do with your code, but I can't figure it out. Any ideas?
AnswerRe: web.config recompile errormemberSacha Barber27 Sep '07 - 23:17 
Without the actual web config, its hard to say.
 
Sorry to say it may be down to you.
 
Send me the Web.Config ill see if I can spot it
 
sachabarber@hotmail.com
 

 

 
Sacha Barber
A Modern Geek - I cook, I clean, I drink, I Program. Modern or what?
 
My Blog : sachabarber.net

GeneralRe: web.config recompile errormemberMundo20927 Sep '07 - 23:35 
It's exactly the same web.config as your downloadable code with the line
  <add name="masterConnectionString" connectionString="Data Source=<YOUR_SQLSERVER_NAME_HERE>;Initial Catalog=master;Integrated Security=True" providerName="System.Data.SqlClient" />
replaced with the following line
  <add name="masterConnectionString" connectionString="Data Source=localhost;Initial Catalog=master;Integrated Security=True" providerName="System.Data.SqlClient" />
i.e. the only difference is the amending of the DataSource attribute. The full error message is:
'<', hexadecimal value 0x3C, is an invalid attribute character. Line 4, position 68. (C:\Documents and Settings\myloginname\My Documents\My Code Project Downloads\JavaRowSelect\ClientSideGridViewRowSelection\web.config line 4)		
Which is suggesting to me that it thinks the '<YOUR_SQLSERVER_NAME_HERE>' bit is still there, but it *isn't*. I've tried deleting everything, re-downloading, restarting VS and starting again, but to no avail.
GeneralRe: web.config recompile errormemberSacha Barber28 Sep '07 - 0:25 
Mmmmm thats messed up.
 
Are you sure uou have SQL Server installed locally.
 

 
Maybe is also a caching thing. Perhaps?
 
Dont know what to tell you. These are thing I would try.
 
1. delete the line Sacha Barber
A Modern Geek - I cook, I clean, I drink, I Program. Modern or what?
 
My Blog : sachabarber.net
GeneralRe: web.config recompile errormemberMundo20928 Sep '07 - 1:39 
OK thanks for your suggestions. I've managed to get it working by stopping VS's webserver and reloading the project. I think VS must have got its knickers in a twist. Sorry to have distracted you from something more fruitful. I still like the article and have used the GetPostBackClientHyperlink() method elsewhere to get a client side javascript function to fire followed by a server side postback, which is cool. I used it to disable a Submit button and while doing my postback. So many thanks, Sacha.
GeneralRe: web.config recompile errormemberSacha Barber28 Sep '07 - 2:24 
no problem
 

 
Sacha Barber
A Modern Geek - I cook, I clean, I drink, I Program. Modern or what?
 
My Blog : sachabarber.net

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 22 May 2007
Article Copyright 2007 by Sacha Barber
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid