ASP.NET GridView RowIndex As CommandArgument

前端 未结 9 1610
天涯浪人
天涯浪人 2020-11-30 23:40

How can you access and display the row index of a gridview item as the command argument in a buttonfield column button?



            


        
相关标签:
9条回答
  • 2020-12-01 00:25
    void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        Button b = (Button)e.CommandSource;
        b.CommandArgument = ((GridViewRow)sender).RowIndex.ToString();
    }
    
    0 讨论(0)
  • 2020-12-01 00:27
    <asp:TemplateField HeaderText="" ItemStyle-Width="20%" HeaderStyle-HorizontalAlign="Center">
                        <ItemTemplate>
                            <asp:LinkButton runat="server" ID="lnkAdd" Text="Add" CommandName="Add" CommandArgument='<%# Eval("EmpID"))%>' />
                        </ItemTemplate>
                    </asp:TemplateField>
    

    This is the traditional way and latest version of asp.net framework having strongly typed data and you don't need to use as string like "EMPID"

    0 讨论(0)
  • 2020-12-01 00:28

    MSDN says that:

    The ButtonField class automatically populates the CommandArgument property with the appropriate index value. For other command buttons, you must manually set the CommandArgument property of the command button. For example, you can set the CommandArgument to <%# Container.DataItemIndex %> when the GridView control has no paging enabled.

    So you shouldn't need to set it manually. A row command with GridViewCommandEventArgs would then make it accessible; e.g.

    protected void Whatever_RowCommand( object sender, GridViewCommandEventArgs e )
    {
        int rowIndex = Convert.ToInt32( e.CommandArgument );
        ...
    }
    
    0 讨论(0)
  • 2020-12-01 00:31
    <asp:LinkButton ID="LnkBtn" runat="server" Text="Text" RowIndex='<%# Container.DisplayIndex %>' CommandArgument='<%# Eval("??") %>' OnClick="LnkBtn_Click" />
    

    inside your event handler :

    Protected Sub LnkBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
      dim rowIndex as integer = sender.Attributes("RowIndex")
      'Here you can use also the command argument for any other value.
    End Sub
    
    0 讨论(0)
  • 2020-12-01 00:31

    with paging you need to do some calculation

    int index = Convert.ToInt32(e.CommandArgument) % GridView1.PageSize;
    
    0 讨论(0)
  • 2020-12-01 00:36

    Here is a very simple way:

    <asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" 
                     CommandArgument='<%# Container.DataItemIndex %>' />
    
    0 讨论(0)
提交回复
热议问题