ASP.NET GridView RowIndex作为CommandArgument

mir*_*zus 55 c# asp.net gridview

如何在buttonfield列按钮中访问并显示gridview项的行索引作为命令参数?

<gridview>
<Columns>
   <asp:ButtonField  ButtonType="Button" 
        CommandName="Edit" Text="Edit" Visible="True" 
        CommandArgument=" ? ? ? " />
.....
Run Code Online (Sandbox Code Playgroud)

Geo*_*rge 95

这是一个非常简单的方法:

<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" 
                 CommandArgument='<%# Container.DataItemIndex %>' />
Run Code Online (Sandbox Code Playgroud)

  • 我收到错误"System.Web.UI.WebControls.ButtonField没有DataBinding事件." 当我试着 但CommandArgument会自动设置为rowindex(请参阅Rich的答案). (4认同)
  • 对于GridView,其DataItemIndex AND NOT ItemIndex.ItemIndex用于Repeater (3认同)

Ric*_*ich 34

MSDN说:

ButtonField类使用适当的索引值自动填充CommandArgument属性.对于其他命令按钮,您必须手动设置命令按钮的CommandArgument属性.例如,当GridView控件未启用分页时,您可以将CommandArgument设置为<%#Container.DataItemIndex%>.

所以你不需要手动设置它.然后使用GridViewCommandEventArgs的行命令可以访问它; 例如

protected void Whatever_RowCommand( object sender, GridViewCommandEventArgs e )
{
    int rowIndex = Convert.ToInt32( e.CommandArgument );
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 是的.这是我生命中的5个小时,因为我没有先读过这篇文章. (3认同)

小智 12

这是微软的建议 http://msdn.microsoft.com/en-us/library/bb907626.aspx#Y800

在gridview上添加一个命令按钮并将其转换为模板,然后在这种情况下给它一个命令名" AddToCart ",并添加CommandArgument "<%#((GridViewRow)Container).RowIndex%>"

<asp:TemplateField>
  <ItemTemplate>
    <asp:Button ID="AddButton" runat="server" 
      CommandName="AddToCart" 
      CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
      Text="Add to Cart" />
  </ItemTemplate> 
</asp:TemplateField>
Run Code Online (Sandbox Code Playgroud)

然后在GridView的RowCommand事件上创建,识别何时触发"AddToCart"命令,并从那里做任何你想做的事情

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "AddToCart")
  {
    // Retrieve the row index stored in the 
    // CommandArgument property.
    int index = Convert.ToInt32(e.CommandArgument);

    // Retrieve the row that contains the button 
    // from the Rows collection.
    GridViewRow row = GridView1.Rows[index];

    // Add code here to add the item to the shopping cart.
  }
}
Run Code Online (Sandbox Code Playgroud)

**我犯的一个错误是我想在我的模板按钮上添加操作,而不是直接在RowCommand事件上执行操作.


Chr*_*rds 5

我认为这会奏效.

<gridview>
<Columns>

            <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
        </Columns>
</gridview>
Run Code Online (Sandbox Code Playgroud)

  • @balexandre,当ASP.NET标记内没有双引号时,没有必要使用单引号 (3认同)