ASP.NET Gridview Selected Index Changed not firing

时间秒杀一切 提交于 2021-02-11 15:02:31

问题


This has been asked quite a few times, but still.

In GridView is defined event OnSelectedIndexChanged. My expectation is, that if I click on a row in gridview, the event will be fired. I managed to do the same with image buttons, but I want the entire row to be clickable.

<asp:GridView runat="server" ID="gameGrid" PageSize="20" PagerSettings-Mode="NextPreviousFirstLast"
    OnRowDataBound="GameGrid_RowDataBound" OnPageIndexChanging="GameGrid_PageIndexChanging"
    AutoGenerateColumns="false" CssClass="table table-hover table-striped" AllowPaging="True"
    AllowSorting="True" ShowHeaderWhenEmpty="True" OnSelectedIndexChanged="gameGrid_SelectedIndexChanged">
    <Columns>
        <asp:BoundField HeaderText="Game Id" DataField="ID_Game" SortExpression="ID_Game" />
        <asp:BoundField HeaderText="Player" DataField="Email" SortExpression="Email" />
        <asp:BoundField HeaderText="Finshed" SortExpression="Finished" />
        <asp:BoundField HeaderText="Started At" SortExpression="CreateDate" />
        <asp:BoundField HeaderText="Last Updated At" SortExpression="LastUpdate" />
    </Columns>
</asp:GridView>

I was assuming that if I define an EventHandler in CodeBehind, it will be fired.

protected void gameGrid_SelectedIndexChanged(object sender, EventArgs e)
{
    int i = 0;
}

Why is this event not firing?

I would like to redirect the user on a different page with an ID parameter in URL. Should I do something different?


回答1:


First, set the AutoGenerateSelectButton property to true in the GridView. This will generate a LinkButton. Now in the RowDataBound event do the following.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the row is a datarow
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //find the select button in the row (in this case the first control in the first cell)
        LinkButton lb = e.Row.Cells[0].Controls[0] as LinkButton;

        //hide the button, but it still needs to be on the page
        lb.Attributes.Add("style", "display:none");

        //add the click event to the gridview row
        e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackClientHyperlink((GridView)sender, "Select$" + e.Row.RowIndex));
    }
}

You could add the OnClick event to the row without showing the SelectButton, but then you would to turn off EnableEventValidation as seen here How to create a gridview row clickable?



来源:https://stackoverflow.com/questions/53781635/asp-net-gridview-selected-index-changed-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!