Monday, October 27, 2008

ASP GridView - Setting a column to behave like the "Select" Command Field

(Or how to replace the CommandField text within a gridview)

When using an ASP.GridView, one uses the "Select" command-field to provide the functionality for selecting any record displayed in the GridView.

But what if you don't want to dedicate a column to just say the word "Select" and instead you would like to use one of the database fields as the select link. As an example my GridView displayed a list of people. Instead of having a Select link, I wanted people to be able to click on the person's name and have the record be selected based on that click. It would be cleaner and would save some real-estate.

One would think that it would be possible to set the Text property to EVAL(uate) to a DB field. Well that doesn't work! And you will need a work around. The easiest way to do this that I have found is to use a TemplateField with a LinkButton field within it.

Here is the example code for the ASPX file:

<asp:TemplateField HeaderText="My first header">
        <asp:LinkButton id="MyLinkButton1" runat="server" Text='<%# Eval("DB_FIELD_NAME") %>' CommandName="Select"></asp:LinkButton> 

The above code will create a link using the text from your database source's field "DB_FIELD_NAME". When you click on the link it will behave just like the normal "Select" button because the attribute "CommandName" has been set to Select.

Now all you need to do is create the "SelectedIndexChanged" method in your code behind file and hook your GridView's SelectedIndexChanged event to this method.


The CommandName property is available on all controls that have been derived from WebControls.Button class. (Which include: a command button - Button control, a hyperlink-style button - LinkButton control, and a graphical button -ImageButton control). In my example I have used the LinkButton Control. You could change the look of your column by using any of the other 2 controls.

The CommandName property is very versatile and can be made to do other actions by setting it's text to "Select", "Edit", "Sort", etc. In addition you can handle a custom action by hooking to the "OnCommand" event. Finally - these button controls have a "CommandArgument" property, the value of which is passed along to the OnCommand event's method via the "CommandEventArgs" argument.


Unknown said...

How do you "hook your GridView's SelectedIndexChanged event to this method." Would be nice if you would have finished.

Unknown said...

"hook your GridView's SelectedIndexChanged event to this method." Would have been nice if you would have finished. I dont know how to do this.