Wednesday, October 3, 2007

Open window from ASP.NET GridView control select event

Opening a new window from the select event of an ASP.NET GridView control can be a real life saver when needing to display the results of a row selection in a new user window.
With a little code behind and some javascript no problemo.......

Using the GridView SelectedIndexChanged event

Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged

End Sub

As part of the ASP.NET GridView you have access to the Gridview.SelectRow property. Not to be confused with a DataRow the GridViewRow returned is just a collection of the cells in the table made up for that particular row. No columns or searchs based on field name or anything like that :(

This is particularly helpful if you want to grab things to pass to the new window as part of the querystring like ID's or other unique identifiers.

So now we can add some code to grab some of the values.
Remember that these are integer based cell call 0-n~

Back to the task at hand

Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged

Dim selectedRow as GridViewRow = GridView1.SelectedRow

Dim myID as string = selectedRow.Cells(1).Text

Response.Write("<script language=""javascript"">window.open('default.aspx?recno=" + myID + "');</script>")

End Sub

Notice that we are getting the value of the 2nd cell (selectedRow.Cells(1) from a zero based array) and passing a javascript line that is wrote on the close of the page. This will allow pass values between pages in your ASP.NET application fired from the Select event of a GridView.

This will know fire a new window with the arguement "recno" in the request string.

Aint ASP.NET grand?

-CJ

No comments: