2.19. Allowing Selection Anywhere Within a GridView

Problem

You are implementing a GridView that requires selection of a row, but you do not want to have a Select button in every row of your GridView. What you really want is to allow the user to click anywhere within a row, like in a classic Windows application.

Solution

To every row in the GridView, add a hidden Select button along with an onclick event that performs the same action as if the hidden Select button were clicked:

  1. Add a hidden ButtonField to the GridView.

  2. Set the ButtonType attribute to Link so a hidden hyperlinked Select button is rendered in every row.

  3. In the RowDataBound event, add an onclick event to the GridView row that performs the same action as clicking the hidden Select button.

The approach produces output like that shown in Figure 2-21. Examples 2-51, 2-52 through 2-53 show the .aspx and code-behind files for the application that produces this result.

Output of GridView allowing selection anywhere

Figure 2-21. Output of GridView allowing selection anywhere

Discussion

To allow selection of a row of data by clicking on it, you create a GridView in the usual fashion but add a hidden ButtonField. The ButtonType attribute is set to Link, and the CommandName attribute is set to Select. This causes the GridView to be rendered with a hidden hyperlinked Select button in every row.

	<Columns>
		<asp:ButtonField ButtonType="Link"
							Visible="False"
							CommandName="Select" /> … ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.