Now that we’ve learned how to display retrieved information from the database in the GridView, we should now look at ways in which we can allow the user to interact with that data in our GridView.
For this lesson, create a new ASP.NET project called “GridViewButtonCommand” and in the Default.aspx, drag and drop the following:
And in Default.aspx.cs write following in the Page_Load() method, with references to a public Car class:
When you run the application, you will see a very generic output of the data that’s bound to GridView1:
If you want to rearrange the columns, or make it interactive, you will have to make some changes to the GridView. In the Default.aspx Design view, click on the arrow beside the GridView and select “Edit Columns…”:
From here we can set the information displayed in each column:
Override the default behavior, letting us set what each column displays instead.
Select a “BoundField.”
Add the BoundField to a list of selected fields.
Edit the HeaderText to display “Make”.
Tell this BoundField to display the Make property from the Car class.
Next, repeating steps (2) to (5), add three more BoundField’s each representing the Model, Year and CarId. And then add a ButtonField with its Text set to “View”:
After clicking “OK” to that, you will see the new representation of the GridView data previewed in the Design view:
Go to the Properties Window for the GridView and in the Events tab (lightning bolt) double-click the empty entry beside “RowCommand” to create an event/method for it in Default.aspx.cs:
In this method, let’s write some code that will grab the row data and then display it to the user when clicking the “View” button:
Grab the CommandArgument, off of the e input parameter, which we then convert to an integer (using one possible conversion method) and then use that as an index to refer to the particular row of data.
Store each cell we want to display in its own temporary variable.
Attempt to parse the value variable into a valid GUID for displaying the carId.
Output that cell data through the resultLabel.
Keep in mind that, while this method works in the scenario, it is a very risky way to grab data off, as we're attempting to access elements from each individual row. Think about it this way: If you ever added to or changed the order of the rows within the grid, the values you are accessing would be incorrect. However, for the purposes of this lesson, this method will suffice.
Lesson 62 - Implementing a Button Command in a GridView