onrowcommand net ejemplos boton asp c# asp.net gridview

c# - ejemplos - ASP.NET GridView RowIndex As CommandArgument



gridview asp net c# ejemplos (8)

¿Cómo se puede acceder y visualizar el índice de fila de un elemento de vista de cuadrícula como el argumento de comando en un botón de columna de campo de botón?

<gridview> <Columns> <asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument=" ? ? ? " /> .....


Aquí está la sugerencia de Microsoft para este http://msdn.microsoft.com/en-us/library/bb907626.aspx#Y800

En la vista grid, agregue un botón de comando y conviértalo en una plantilla, luego dele un nombre de comando en este caso " AddToCart " y también agregue 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>

Luego, para crear en el evento RowCommand de gridview, identifique cuándo se activa el comando "AddToCart" y haga lo que quiera desde allí.

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. } }

** Un error que estaba cometiendo es que quería agregar las acciones en mi botón de plantilla en lugar de hacerlo directamente en el evento RowCommand.


Aquí hay una manera muy simple:

<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument=''<%# Container.DataItemIndex %>'' />


Creo que esto funcionará

<gridview> <Columns> <asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" /> </Columns> </gridview>


Normalmente vinculo estos datos usando el evento RowDatabound con GridView:

protected void FormatGridView(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { ((Button)e.Row.Cells(0).FindControl("btnSpecial")).CommandArgument = e.Row.RowIndex.ToString(); } }


MSDN dice que:

La clase ButtonField completa automáticamente la propiedad CommandArgument con el valor de índice apropiado. Para otros botones de comando, debe establecer manualmente la propiedad CommandArgument del botón de comando. Por ejemplo, puede establecer CommandArgument en <% # Container.DataItemIndex%> cuando el control GridView no tiene habilitada la búsqueda.

Por lo tanto, no debería necesitar configurarlo manualmente. Un comando de fila con GridViewCommandEventArgs lo haría accesible; p.ej

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


<asp:LinkButton ID="LnkBtn" runat="server" Text="Text" RowIndex=''<%# Container.DisplayIndex %>'' CommandArgument=''<%# Eval("??") %>'' OnClick="LnkBtn_Click" />

dentro de tu controlador de eventos:

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


<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>

Esta es la manera tradicional y la última versión de asp.net framework que tiene datos fuertemente tipados y no es necesario usar una cadena como "EMPID"


void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { Button b = (Button)e.CommandSource; b.CommandArgument = ((GridViewRow)sender).RowIndex.ToString(); }