ASP.NET Gridview所选索引已更改未触发

时间:2018-12-14 14:30:33

标签: asp.net events gridview

这个问题已经问了好几次了,但仍然如此。

在GridView中定义事件OnSelectedIndexChanged。我的期望是,如果我在gridview中单击一行,则将触发该事件。我设法对图像按钮做了同样的操作,但是我希望整行都可以单击。

<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>

我假设如果我在CodeBehind中定义一个EventHandler,它将被触发。

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

为什么此事件不触发?

我想使用URL中的ID参数将用户重定向到其他页面上。我应该做些不同的事情吗?

1 个答案:

答案 0 :(得分:0)

首先,在GridView中将AutoGenerateSelectButton属性设置为true。这将生成一个LinkBut​​ton。现在,在RowDataBound事件中执行以下操作。

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));
    }
}

您可以在不显示SelectButton的情况下将OnClick事件添加到该行,但是随后您将关闭EnableEventValidation,如此处How to create a gridview row clickable?

相关问题