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   
GeneralMy vote of 5member Orcun Iyigun13 May '13 - 10:12 
nice article...5
QuestionMy Vote is 5memberanglo007218 Nov '12 - 22:46 
Thankx for this trick
GeneralMy vote of 2memberenkhtuvshin_b12 Sep '12 - 19:45 
dfsgsdfg
Questionusing Up down arrow keys to select the Gridview asp.net 3.5memberKhanFaiz21 Jun '12 - 18:25 
I am using asp.net 3.5 with C#
 
i have a textbox, in which i type the field's value to find the data from the database and the data is displayed on the gridview below.
 
now i have to click on the gridview row to select a row so that i can use [up arrow] and [down arrow] keys to select rows.
 
I want that when i am finished finding data, i simply press [down arrow] key in the textbox to select the 1st row of the gridview below(similarly like i click the mouse on the row)
 
pls help
thanks
Faiz
GeneralMy vote of 5membernebulaqueen5 Apr '12 - 5:22 
nice this is what im looking for Smile | :)
Questionrow highlightedmemberMike_0411 Feb '12 - 21:35 
Hi
 
Very nice article. I implemented it in a project. Now, in another one I need to do the same at the moment to select a row by a checkbox and after click in a asp button, highlight the row. And it's working however the row is paint just a few seconds and then no more.
I adapted the code in this article to be working with a checkbox inside a grid but as mentioned it's not working as expected.
 
I hope you can help me or give me a clue
Regards!
Question__doPostBackmemberpdusp31 Jan '12 - 23:09 
Hello,
__doPostBack is made not in javavascript but on remote server?
Am I rigth?
Thank you
 
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
 

InformacjaKRD
GeneralMy vote of 5memberErnesto Tejeda15 Oct '11 - 16:05 
Right to the point, well done
GeneralMy vote of 5memberanurag129011 Oct '11 - 1:14 
Excellent article ,exactly what I was looking for .Saved at least a day.
QuestionLess risky codemembernebojsa1623 Sep '11 - 7:45 
Instead that use code bellow.
 
<style type="text/css">
 .hideColumn {display:none;}
</style>
 
<asp:GridView ID="GridView1" .....
 <asp:CommandField ShowSelectButton="True" Visible="True" SelectText="Select" ItemStyle-CssClass="hideColumn" HeaderStyle-CssClass="hideColumn" />
 ...
</asp:GridView>
 

in (vb) code :
Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
          e.Row.Attributes("onclick") = ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex.ToString)
        End If
End Sub
 
no security risk, EnableEventValidation stayed enabled (true).
p.s. sorry for my weak english.
GeneralMy vote of 2memberRamesh_495925 Jun '11 - 22:42 
risk in sequrity
Questiongood but with sequrity RiskmemberRamesh_495925 Jun '11 - 22:41 
As EnableEventValidation=false create probems related to sequrity.
AnswerRe: good but with sequrity Riskmembernebojsa1623 Sep '11 - 7:40 
Instead that use code bellow.
 
<style type="text/css">
 .hideColumn {display:none;}
</style>
 
<asp:GridView ID="GridView1" .....
 <asp:CommandField ShowSelectButton="True" Visible="True" SelectText="Select" ItemStyle-CssClass="hideColumn" HeaderStyle-CssClass="hideColumn" />
 ...
</asp:GridView>
 

in (vb) code :
Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
          e.Row.Attributes("onclick") = ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex.ToString)
        End If
End Sub
 
no security risk, EnableEventValidation stayed enabled (true).
p.s. sorry for my weak english.
QuestionError Messagememberneilderama21 Jun '11 - 15:41 
Hello..
 
I've got an error while trying to use your code. Conversion from string "Select$" to type 'Double' is not valid.
GeneralMy vote of 5memberahsan sarfraz6 Dec '10 - 18:56 
it was very usefull and very simple. Sacha barber is right about the fact that it is his most simple article .. Smile | :)
thaks alot.
GeneralMy vote of 5memberjasonHall30 Nov '10 - 17:07 
Great job! I'm very pleased with the results! So easy to implement and make my GridView perform how it should out of the box! I wish it were just like the DataGridView for Windows apps...
QuestionGreat!memberbertvaes22 Nov '10 - 2:28 
One additional question :
 
What are the security risks when I disable EnableEventValidation ?
 
Thanks! (Great article, easiest approach I have seen yet)
 
regards,
 
B.
Generalgreat articlememberkamalRafi8 Oct '10 - 21:58 
very helpful tank you a lotThumbs Up | :thumbsup:
GeneralMy vote of 5memberJason Sheridan15 Sep '10 - 3:52 
Fantastic, thank you!
GeneralNicememberdigsourse16 Dec '09 - 21:28 
so nice
GeneralThanksmemberNitin Sawant4 Aug '09 - 0:58 
Thanks!
 
Gr8 Article.. Big Grin | :-D
 
===========
NITIN SAWANT
===========

GeneralEnableEventValidation="false"memberworko26 Apr '09 - 2:45 
Isnt the page less secure with EnableEventValidation="false" in header? Can users run javascripts to do things they should not be able to do now?
 
Like adding or deleting columns by javascript postback, even I dont want to make this option available?
 
The fact I dont show button for deleting row could not mean it is not prohibited.
 

Your guide extremely helped me with problem I was having but I think adding exception just to select operation of the gridView would be much better than disabling event validation. If it is possible. Unfortunately I dont know if it is or how to do that. Something with ClientScriptManager maybe?
 

Sam

GeneralVery Nicememberaabruzzese12 Jan '09 - 4:25 
Sacha,
 
You make me feel like I got into computers 25 years too soon ... LOL
 
It is amazing what you can do in this day an age versus what you could back in the late 70's and early 80's.

Smile | :)
GeneralRe: Very NicemvpSacha Barber12 Jan '09 - 6:24 
I agree there is some very cool technology around right now.
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralGood work & SuggestionmemberMoon Chung9 Jan '09 - 7:02 
Thank you for the article. I am using this in my project.
Also I found another article that you can keep EnableEventValidation="true" with these options:
 
<asp:commandfield showselectbutton="True" visible="True" xmlns:asp="#unknown">
ItemStyle-CssClass=HiddenColumn HeaderStyle-CssClass=HiddenColumn />
 
.HiddenColumn{display: none;}
 
Moon
GeneralMy vote of 1memberGUI Developer21 Dec '08 - 6:48 
insufficient explanation
GeneralRe: My vote of 1mvpSacha Barber12 Jan '09 - 6:25 
Thats fine.
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralGridViwmembered.suriv4 Dec '08 - 9:36 
nice article.
GeneralRe: GridViwmvpSacha Barber4 Dec '08 - 21:48 
Thanks
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralGreat articlememberdamu198320 Sep '08 - 0:06 
The Article is great ,as a begineer in asp.net It helped me to easily understand the concepts
GeneralRe: Great articlemvpSacha Barber20 Sep '08 - 2:16 
cool
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralAmazingmembersimer_project2 Sep '08 - 21:25 
Its amazing and interesing Code !!!!
GeneralRe: AmazingmvpSacha Barber18 Sep '08 - 1:13 
Glad you like it
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

Generalone word : THANKS !memberBrad Woody22 Aug '08 - 3:21 
I have seen this concept posted in a few other places, but I could not make any of them work.
 
Your recipe worked first time for me. Thanks for the verbiage which accompanied the code - it made all the difference...
 
Brad
GeneralRe: one word : THANKS !mvpSacha Barber22 Aug '08 - 4:12 
glad it helped
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralNice article .. very much useful also ..memberRahees8321 Jul '08 - 22:19 
Nice one.. easy to understand also ...
GeneralRe: Nice article .. very much useful also ..mvpSacha Barber22 Jul '08 - 1:39 
thanks
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

Generalhaimemberjeffreyk8 Apr '08 - 23:22 
thanks...i got it
GeneralRe: haimvpSacha Barber9 Apr '08 - 1:00 
Oh ok cool.
 
Perhaps post the answer here, so others with same problem can see the fix
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same view, and never argue
 
My Blog : sachabarber.net

GeneralRe: haimemberjolvera18 Jun '09 - 5:33 
I have the same Frown | :( problem than you hai... how do you fix it?
Generalhaimemberjeffreyk8 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......
GeneralThanxmembermarx_city8 Apr '08 - 6:27 
It's working great.
GeneralRe: ThanxmvpSacha Barber8 Apr '08 - 21:37 
you are welcome
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same view, and never argue
 
My Blog : sachabarber.net

GeneralNice !!memberC. L. Phillip12 Mar '08 - 8:32 
Great article. Very useful and practical.
 

Here is another article with somewhat similar content
GeneralRe: Nice !!mvpSacha Barber12 Mar '08 - 10:40 
Thanks man
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same view, and never argue
 
My Blog : sachabarber.net

QuestionCell Value ?membermurtaza dhari6 Mar '08 - 1:54 
Can we get Selected Row Columns Value without PostBacking it (i.e through javascript ) is it possible ?
 
If all the tree become pen and all ocean become ink and many more other ocean become ink even then the ALLAH praise could not be written completely. (AL-Quran)

AnswerRe: Cell Value ?mvpSacha Barber6 Mar '08 - 3:08 
Just use an Ajax library, such as Anthem, or ASP .NET Ajax
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same view, and never argue
 
My Blog : sachabarber.net

GeneralRe: Cell Value ?membermurtaza dhari30 Mar '08 - 20:18 
I have Written an Small article see it for Row Value using javascript without Ajax and postback
http://www.codeproject.com/KB/webforms/DataGrid_Row__Value.aspx"
 
If all the tree become pen and all ocean become ink and many more other ocean become ink even then the ALLAH praise could not be written completely. (AL-Quran)

GeneralThx a lotmemberdimitris.dpant21 Nov '07 - 8:23 
Thank you for this very helpful post.
GeneralRe: Thx a lotmemberSacha Barber21 Nov '07 - 8:30 
you are welcome
 
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
Web03 | 2.6.130516.1 | Last Updated 22 May 2007
Article Copyright 2007 by Sacha Barber
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid