Contents

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.

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:

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 :

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

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.

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.