Click here to Skip to main content
11,644,286 members (68,950 online)
Click here to Skip to main content

Using JavaScript To Select GridView Rows

, 22 May 2007 CPOL 322.2K 4.5K 160
Rate this:
Please Sign up or sign in to vote.
Using JavaScript To Select GridView Rows

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)
    {

    }

    /// <span class="code-SummaryComment"><summary></span>
    /// Check the item being bound is actually a DataRow, if it is,     
    /// wire up the required html events and attach the relevant JavaScripts
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><param name="sender">GridView1</param></span>
    /// <span class="code-SummaryComment"><param name="e">The event args for the RowDataBound event</param></span>
    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);
        }
    }

    /// <span class="code-SummaryComment"><summary></span>
    /// Show the 1st cell value in the web pages TextBox to show the user
    /// it is actually selecting rows at client side
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><param name="sender"> GridView1</param></span>
    /// <span class="code-SummaryComment"><param name="e">The event args for the SelectedIndexChanged event</span>
    ///    <span class="code-SummaryComment"></param></span>
    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)

Share

About the Author

Sacha Barber
Software Developer (Senior)
United Kingdom United Kingdom
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 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • 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

You may also be interested in...

Comments and Discussions

 
GeneralNot happy with select Pin
esb779-Nov-14 13:26
memberesb779-Nov-14 13:26 
GeneralMy vote of 5 Pin
Orcun Iyigun13-May-13 10:12
member Orcun Iyigun13-May-13 10:12 
QuestionMy Vote is 5 Pin
anglo007218-Nov-12 22:46
memberanglo007218-Nov-12 22:46 
AnswerRe: My Vote is 5 Pin
Herbisaurus15-Aug-13 2:45
memberHerbisaurus15-Aug-13 2:45 
GeneralMy vote of 2 Pin
enkhtuvshin_b12-Sep-12 19:45
memberenkhtuvshin_b12-Sep-12 19:45 
Questionusing Up down arrow keys to select the Gridview asp.net 3.5 Pin
KhanFaiz21-Jun-12 18:25
memberKhanFaiz21-Jun-12 18:25 
GeneralMy vote of 5 Pin
nebulaqueen5-Apr-12 5:22
membernebulaqueen5-Apr-12 5:22 
Questionrow highlighted Pin
Mike_0411-Feb-12 21:35
memberMike_0411-Feb-12 21:35 
Question__doPostBack Pin
pdusp31-Jan-12 23:09
memberpdusp31-Jan-12 23:09 
GeneralMy vote of 5 Pin
Ernesto Tejeda15-Oct-11 16:05
memberErnesto Tejeda15-Oct-11 16:05 
GeneralMy vote of 5 Pin
anurag129011-Oct-11 1:14
memberanurag129011-Oct-11 1:14 
QuestionLess risky code Pin
nebojsa1623-Sep-11 7:45
membernebojsa1623-Sep-11 7:45 
GeneralMy vote of 2 Pin
Ramesh_495925-Jun-11 22:42
memberRamesh_495925-Jun-11 22:42 
Questiongood but with sequrity Risk Pin
Ramesh_495925-Jun-11 22:41
memberRamesh_495925-Jun-11 22:41 
AnswerRe: good but with sequrity Risk Pin
nebojsa1623-Sep-11 7:40
membernebojsa1623-Sep-11 7:40 
QuestionError Message Pin
neilderama21-Jun-11 15:41
memberneilderama21-Jun-11 15:41 
AnswerRe: Error Message Pin
Herbisaurus15-Aug-13 2:46
memberHerbisaurus15-Aug-13 2:46 
GeneralMy vote of 5 Pin
ahsan sarfraz6-Dec-10 18:56
memberahsan sarfraz6-Dec-10 18:56 
GeneralMy vote of 5 Pin
jasonHall30-Nov-10 17:07
memberjasonHall30-Nov-10 17:07 
QuestionGreat! Pin
bertvaes22-Nov-10 2:28
memberbertvaes22-Nov-10 2:28 
Generalgreat article Pin
kamalRafi8-Oct-10 21:58
memberkamalRafi8-Oct-10 21:58 
GeneralMy vote of 5 Pin
Jason Sheridan15-Sep-10 3:52
memberJason Sheridan15-Sep-10 3:52 
GeneralNice Pin
digsourse16-Dec-09 21:28
memberdigsourse16-Dec-09 21:28 
GeneralThanks Pin
Nitin Sawant4-Aug-09 0:58
memberNitin Sawant4-Aug-09 0:58 
GeneralEnableEventValidation="false" Pin
worko26-Apr-09 2:45
memberworko26-Apr-09 2:45 
GeneralVery Nice Pin
aabruzzese12-Jan-09 4:25
memberaabruzzese12-Jan-09 4:25 
GeneralRe: Very Nice Pin
Sacha Barber12-Jan-09 6:24
mvpSacha Barber12-Jan-09 6:24 
GeneralGood work & Suggestion Pin
Moon Chung9-Jan-09 7:02
memberMoon Chung9-Jan-09 7:02 
GeneralMy vote of 1 Pin
GUI Developer21-Dec-08 6:48
memberGUI Developer21-Dec-08 6:48 
GeneralRe: My vote of 1 Pin
Sacha Barber12-Jan-09 6:25
mvpSacha Barber12-Jan-09 6:25 
GeneralGridViw Pin
ed.suriv4-Dec-08 9:36
membered.suriv4-Dec-08 9:36 
GeneralRe: GridViw Pin
Sacha Barber4-Dec-08 21:48
mvpSacha Barber4-Dec-08 21:48 
GeneralGreat article Pin
damu198320-Sep-08 0:06
memberdamu198320-Sep-08 0:06 
GeneralRe: Great article Pin
Sacha Barber20-Sep-08 2:16
mvpSacha Barber20-Sep-08 2:16 
GeneralAmazing Pin
simer_project2-Sep-08 21:25
membersimer_project2-Sep-08 21:25 
GeneralRe: Amazing Pin
Sacha Barber18-Sep-08 1:13
mvpSacha Barber18-Sep-08 1:13 
Generalone word : THANKS ! Pin
Brad Woody22-Aug-08 3:21
memberBrad Woody22-Aug-08 3:21 
GeneralRe: one word : THANKS ! Pin
Sacha Barber22-Aug-08 4:12
mvpSacha Barber22-Aug-08 4:12 
GeneralNice article .. very much useful also .. Pin
Rahees8321-Jul-08 22:19
memberRahees8321-Jul-08 22:19 
GeneralRe: Nice article .. very much useful also .. Pin
Sacha Barber22-Jul-08 1:39
mvpSacha Barber22-Jul-08 1:39 
Generalhai Pin
jeffreyk8-Apr-08 23:22
memberjeffreyk8-Apr-08 23:22 
GeneralRe: hai Pin
Sacha Barber9-Apr-08 1:00
mvpSacha Barber9-Apr-08 1:00 
GeneralRe: hai Pin
jolvera18-Jun-09 5:33
memberjolvera18-Jun-09 5:33 
Generalhai Pin
jeffreyk8-Apr-08 22:41
memberjeffreyk8-Apr-08 22:41 
i got this error!!!!!!!!!!


Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.


how to solve this......

plz help me......
GeneralThanx Pin
marx_city8-Apr-08 6:27
membermarx_city8-Apr-08 6:27 
GeneralRe: Thanx Pin
Sacha Barber8-Apr-08 21:37
mvpSacha Barber8-Apr-08 21:37 
GeneralNice !! Pin
C. L. Phillip12-Mar-08 8:32
memberC. L. Phillip12-Mar-08 8:32 
GeneralRe: Nice !! Pin
Sacha Barber12-Mar-08 10:40
mvpSacha Barber12-Mar-08 10:40 
QuestionCell Value ? Pin
murtaza dhari6-Mar-08 1:54
membermurtaza dhari6-Mar-08 1:54 
AnswerRe: Cell Value ? Pin
Sacha Barber6-Mar-08 3:08
mvpSacha Barber6-Mar-08 3:08 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

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