我有一個通過templatefield添加到列的GridView和ImageButtons。我已將一個函數附加到「OnClick」事件。從GridView中的ImageButton點擊獲取行索引
一旦進入此功能,我怎樣才能得到已點擊按鈕的行的索引。看來,我擁有的只是鼠標在頁面上的座標。
我有一個通過templatefield添加到列的GridView和ImageButtons。我已將一個函數附加到「OnClick」事件。從GridView中的ImageButton點擊獲取行索引
一旦進入此功能,我怎樣才能得到已點擊按鈕的行的索引。看來,我擁有的只是鼠標在頁面上的座標。
而不是通過行循環的,你可以使用這個
<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:
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;
會同意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
這是很好的伎倆。 我還有另一招。 你可以試試...
protected void userGridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow rowSelect = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int rowindex = rowSelect.RowIndex;
}
}
這也是一個不錯的方法。
甜 - 這是更高效 - 我會整合它。 – Jeffrey 2009-01-21 19:32:23