0

I am trying to make it so I can select a row from my asp:GridView element by clicking anywhere on the row using JQuery.

Currently, my code looks like:

asp:GridView

<asp:GridView Width="100%" ID="gvQuickPhrases" CssClass="quickphrases-table" AutoGenerateColumns="false" runat="server" DataKeyNames="ID" AutoGenerateSelectButton="true" OnSelectedIndexChanged="gvQuickPhrases_SelectedIndexChanged">
    <Columns>
        <asp:BoundField DataField="Text" HeaderText="Quick Phrases" />
    </Columns>
    <AlternatingRowStyle CssClass="qp-table-alternate-row" />
    <HeaderStyle CssClass="qp-table-header-style" />
    <PagerSettings Visible="False" />
    <RowStyle CssClass="qp-table-row-style" />
    <SelectedRowStyle CssClass="qp-selected-table-row-style" />
</asp:GridView>

JavaScript:

$('tr.qp-table-alternate-row').click(function () {
    $('tr.qp-table-row-style').removeClass('qp-selected-table-row-style');
    $('tr.qp-table-alternate-row').removeClass('qp-selected-table-row-style');
    $(this).addClass('qp-selected-table-row-style');
});
$('tr.qp-table-row-style').click(function () {
    $('tr.qp-table-alternate-row').removeClass('qp-selected-table-row-style');
    $('tr.qp-table-row-style').removeClass('qp-selected-table-row-style');
    $(this).addClass('qp-selected-table-row-style');
});

Behind:

protected void gvQuickPhrases_SelectedIndexChanged(object sender, EventArgs e)
{
    var qf = AdminDatabroker.GetQuickPhrase(Convert.ToInt32(gvQuickPhrases.SelectedDataKey.Value));

    txtPhrase.Value = qf.Text;
    lblHeadingPhrase.Text = "Edit Phrase";
    hQuickPhraseID.Value = qf.ID.ToString();
    hQuickPhraseSelectedText.Value = qf.Text;

    btnTrash.Enabled = true;
    btnEdit.Enabled = true;
}

Now this works in terms of applying the selected row styles, however, the row is not actually selected. For example, if I then go to edit the row, it behaves as if nothing is actually selected.

1 Answer 1

2

Adding a class to a GridView row does not trigger an SelectedIndexChanged because that requires a PostBack. If you want the entire row to be clickable, the easiest way is to copy the href from the Select button to the tr

<script type="text/javascript">
    $('#<%= gvQuickPhrases.ClientID %> a').each(function () {
        $(this).closest('tr').attr('onclick', $(this).prop('href'));
    });
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Exactly what I was looking for.

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.