Isaac Byrne
Isaac Byrne

Reputation: 613

Selecting asp:GridView Row with Jquery

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.

Upvotes: 0

Views: 1103

Answers (1)

VDWWD
VDWWD

Reputation: 35514

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>

Upvotes: 2

Related Questions