ASP.NET Gridview所选索引已更改,无法触发 [英] ASP.NET Gridview Selected Index Changed not firing
问题描述
这个问题已经问了好几次了,但仍然如此.
This has been asked quite a few times, but still.
在GridView中定义事件OnSelectedIndexChanged.我的期望是,如果我在gridview中单击一行,则会触发该事件.我设法对图像按钮进行了相同的操作,但是我希望整个行都可以单击.
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>
我假设如果我在CodeBehind中定义一个EventHandler,它将被触发.
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;
}
为什么此事件不触发?
我想使用URL中的ID参数将用户重定向到其他页面上.我应该做些不同的事情吗?
I would like to redirect the user on a different page with an ID parameter in URL. Should I do something different?
推荐答案
首先,在GridView中将 AutoGenerateSelectButton
属性设置为true.这将生成一个LinkButton.现在,在 RowDataBound
事件中执行以下操作.
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));
}
}
您可以在不显示 SelectButton
的情况下将OnClick事件添加到该行,但是随后您将关闭 EnableEventValidation
,如此处
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?
这篇关于ASP.NET Gridview所选索引已更改,无法触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!