Troy Mitchel
Troy Mitchel

Reputation: 1810

Add Row Click Event to Asp.Net GridView Rows

Is there a way to add a RowClick Event to Gridview Rows without adding a button to each one? I want to be able to click anywhere in the row and raise the SelectedIndexChanged event.

I tried the following but I need to add pages enableEventValidation="true" and I really don't want to do that.

Private Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    Try
        Select Case e.Row.RowType
            Case DataControlRowType.DataRow
                e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" & e.Row.RowIndex))
        End Select
    Catch ex As Exception

    End Try
End Sub

The RowCommands wont work either because you have to have a button.

Upvotes: 0

Views: 16350

Answers (1)

Gromer
Gromer

Reputation: 9931

You did step 1 of 2. First part was registering the onclick in the RowDataBound. Now you need to handle the SelectedIndexChanged event. I'm not a VB.Net guy, so I'm not 100% sure on how to wire it up. The event handler will look like this, though:

Private Sub GridView1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles GridView1.SelectedIndexChanged
    ' Do stuff here.
End Sub

Also, change your onclick wire up code to use Page.ClientScript.GetPostBackEventReference instead of Page.ClientScript.GetPostBackClientHyperlink.

Here is some example markup:

<asp:GridView ID="GridView1"
    runat="server"
    Width="665px"
    OnSelectedIndexChanged="GridView1_SelectedIndexChanged">

    <HeaderStyle BackColor="#0033CC" />

    <Columns>
        <asp:CommandField ShowSelectButton="True" />
    </Columns>

</asp:GridView>

Upvotes: 2

Related Questions