【问题标题】:ASP.NET Gridview Selected Index Changed not firingASP.NET Gridview 选定索引更改未触发
【发布时间】:2018-12-14 14:30:32
【问题描述】:

这已经被问过很多次了,但仍然如此。

在 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 参数将用户重定向到不同的页面。我应该做一些不同的事情吗?

【问题讨论】:

    标签: asp.net events gridview


    【解决方案1】:

    首先,在 GridView 中将 AutoGenerateSelectButton 属性设置为 true。这将生成一个链接按钮。现在在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?

    【讨论】:

    • 在我看来,我找到了一个更优雅的解决方案(RowDataBound 事件)。 e.Row.Attributes.Add("ondblclick", String.Format("window.location='Play.aspx?GID={0}&amp;UID={1}'", v_GameOverview.ID_Game, v_GameOverview.Email));
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多