我有一个Gridview,其中通过templatefield添加了ImageButtons到列中。我已经将一个函数附加到了“OnClick”事件上。
进入这个函数后,我如何获取被点击的按钮所在行的索引。似乎我只有页面上的鼠标坐标。
我有一个Gridview,其中通过templatefield添加了ImageButtons到列中。我已经将一个函数附加到了“OnClick”事件上。
进入这个函数后,我如何获取被点击的按钮所在行的索引。似乎我只有页面上的鼠标坐标。
不必循环遍历行,您可以使用此方法
<asp:ImageButton runat="server" id="ibtn1" ... RowIndex='<%# Container.DisplayIndex %>'
OnClick="button_click"/>
...
protected void button_click(object sender, EventArgs e){
ImageButton ibtn1 = sender as ImageButton;
int rowIndex = Convert.ToInt32(ibtn1.Attributes["RowIndex"]);
//Use this rowIndex in your code
}
将发送者转换为ImageButton,然后将图像按钮的NamingContainer转换为行:
VB:
将发送者转换为ImageButton,然后将图像按钮的NamingContainer转换为行:Dim btn as ImageButton = CType(sender, ImageButton)
Dim row as GridViewRow = CType(btn.NamingContainer, GridViewRow)
C#:
ImageButton btn = (ImageButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
这是一个非常好的技巧。 我还有另一个技巧。 你可以尝试一下...
protected void userGridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow rowSelect = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int rowindex = rowSelect.RowIndex;
}
}
我认同bdukes的观点,最简单的方法是使用CommandArgument。将数据的唯一ID编号绑定到该属性中,然后处理_RowCommand事件。
例如:
<asp:TemplateField >
<HeaderStyle Width="20" />
<ItemTemplate>
<asp:ImageButton ImageUrl="images/icons/iCal.png" CommandArgument='<%# Eval("Event_ID") %>' ToolTip="iCal" runat="server" Height="18" Width="18" />
</ItemTemplate>
</asp:TemplateField>
Protected Sub gv_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand
e.CommandArgument 'use this value in whatever way you like
End Sub