Search code examples
asp.netvb.net

Gridview DataKeyNames


Is there a way to include the DataKeyname "Number" onto a response.redirect in a gridview selectedindexchanged so that i can pass it to the next page? I'm currently using this code to pass data and the gridview is currently setup to display the number in the row. I want to hide the column for "number" and use the datakeyname instead. Thanks!

Response.Redirect("RoundingEntry.aspx?Room=" & GridView1.SelectedRow.Cells(1).Text & "&Name=" & GridView1.SelectedRow.Cells(2).Text & "&Number=" & GridView1.SelectedRow.Cells(3).Text & "&Member=" & DDMember.SelectedValue & "&Unit=" & DDUnit.SelectedValue)

Solution

  • Since you're in the SelectedIndexChanged event, you can use the GridView.SelectedIndex property to get the correct data key out of the GridView.DataKeys collection.

    Might I also suggest cleaning that up, so that it's not all one long line of code?

    Sub CustomersGridView_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim room As String = GridView1.SelectedRow.Cells(1).Text
        Dim name As String = GridView1.SelectedRow.Cells(2).Text
        ' This is the one I've changed, to grab the DataKey of the selected row
        Dim number As String = GridView1.DataKeys(GridView1.SelectedIndex).Value.ToString()
        Dim member As String = DDMember.SelectedValue.ToString()
        Dim unit As String = DDUnit.SelectedValue.ToString()
        
        Response.Redirect("RoundingEntry.aspx?Room=" & room & _
                                            "&Name=" & name & _
                                            "&Number=" & number & _
                                            "&Member=" & member & _
                                            "&Unit=" & unit)
    End Sub