我在gridview中有多个按钮。如何确定选择了哪一个特定按钮?我怎样才能捕获行索引??
我用过
protected void crtButton_Click(Object sender, EventArgs e)
{
string componentText;
GridViewRow row = GridView1.SelectedRow;
String componentName = row.Cells[1].text;
}
我尝试通过以下代码
在gridview .aspx文件中生成按钮 <asp:TemplateField HeaderText="Add to Cart">
<ItemTemplate> <asp:Button ID="crtButton" runat="server" Text="Add to Cart" OnClick="crtButton_Click"/>
</ItemTemplate>
</asp:TemplateField>
但似乎没有产生结果。任何人都可以帮助我。
感谢您的期待
答案 0 :(得分:2)
以下是如何获取所点击按钮的行索引:
protected void crtButton_Click(Object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
GridViewRow row = (GridViewRow)clickedButton.Parent.Parent;
int rowIndex = row.RowIndex;
}
然而,这不是最好的方法,因为你必须知道按钮的级别。最好的方法是将OnCommand与CommandArgument结合使用。
<ItemTemplate>
<asp:Button ID="crtButton" runat="server" Text="Add to Cart" OnCommand="crtButton_Command" CommandArgument=<%# Eval("ItemID") %> />
</ItemTemplate>
protected void crtButton_Command(Object sender, CommandEventArgs e)
{
int itemID = Convert.ToInt32(e.CommandArgument);
}
答案 1 :(得分:0)
您可以将发件人转换为Button,然后查看按钮的属性:
protected void crtButton_Click(Object sender, EventArgs e)
{
Button Clicked = sender as Button;