0

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.

1

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

7 Comments

You are correct, however I get error about enabling page events which could compromise security.
@tszoro, check my edit, I noticed you were using a different Page.ClientScript method than I was in my code.
After editing the code I get Server Error Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/>. But it does hit the page load.
To fix the rest of it I looped the GridView rows and added gr.Attributes.Add("onclick",Page.ClientScript.GetPostBackEventReference(GridView1, "Select$" & gr.RowIndex, True)) to each gridview row in the Protected Overrides Sub Render(writer As System.Web.UI.HtmlTextWriter) event and all works now. thanks
Note: As an alternative for this you can also write a __doPostBack event in Javascript and get the params and eventtarget on Postback. function GridViewPostBack(row_idx) { __doPostBack(row_idx, "GridView1RowClick"); }
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.