Using GridView to Save and Retrieve Data with AJAX - Selecting Data from the GridView
(Page 3 of 4 )
Often you need to select a row from the grid and extract data from that row. This is easy to do using the SelectedIndexChanged event of the GridView.
To see how this works, drag a Label control from the Standard section of the Toolbox onto the Design view, below the grid but within the UpdatePanel control. Change the Text property of this Label to Name. Then drag a TextBox control next to the Label. Change its ID property to txtName and set its ReadOnly property to True. You now have a place to display the name of the selected item from the grid.
Click on the Smart Tag of the GridView and check the “Enable Selection” checkbox. This will cause a Select button to display in the first column of the grid, next to the Edit and Delete buttons already there, as shown in Figure 4-22.

Figure 4-22. Clicking Enable Selection in the Smart Tag causes Select buttons to appear in a GridView.
Now all you need to do is set up the event handler to respond to the Select buttons. Double-click on the Select button in the first row of the grid. This will open up the code-behind file with the skeleton of the SelectedIndexChanged already created for you, ready to accept your custom code. Enter the highlighted code from the following snippet:
Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System.EventArgs)
If GridView1.SelectedRow.RowType = DataControlRowType.DataRow Then
Dim cellName As TableCell = GridView1.SelectedRow.Cells(2) ' Name column
txtName.Text = cellName.Text
End If
End Sub
This code first tests to determine if the selected row is a DataRow (as opposed to a HeaderRow or a FooterRow). If it is a DataRow, it creates a variable of type TableCell, which is assigned to the third cell in the selected row (because of zero-based indexing, the third item will have an index value of 2). Then the Text property of the TextBox is set equal to the Text property of that cell.
Run the app and click on one of the Select buttons. The name from the selected row appears in the TextBox.
Next: Passing Parameters to the SELECT Query >>
More ASP.NET Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of Learning ASP.NET 2.0 with AJAX: A Practical Hands-on Guide, written by Jesse Liberty, Dan Hurwitz and Brian MacDonald (O'Reilly, 2007; ISBN: 0596513976). Check it out today at your favorite bookstore. Buy this book now.
|
|