ASP.NET Gridview Selected Index Changed not firing



这个问题已经被问了很多次,但仍然存在。

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

首先,在GridView中将AutoGenerateSelectButton属性设置为true。这将生成一个LinkButton。现在,在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,如图所示。如何创建可单击的网格视图行?

相关内容

最新更新