Ottenere l'indice di riga da un pulsante ImageButton in GridView
-
19-08-2019 - |
Domanda
Ho una Gridview con ImageButtons aggiunti a una colonna tramite un campo template. Ho collegato una funzione a " OnClick " evento.
Una volta in questa funzione, come posso ottenere l'indice della riga che ha il pulsante che è stato cliccato. Sembra che tutto ciò che ho siano le coordinate del mouse sulla pagina.
Soluzione
Invece di scorrere tra le righe puoi usare questo
<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
}
Altri suggerimenti
Trasmetti il ??mittente a un ImageButton quindi lancia il NamingContainer del pulsante immagine in una riga:
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;
Sarebbe d'accordo con bdukes sul fatto che l'opzione più semplice sia usare CommandArgument. Associa il numero ID univoco dei tuoi dati a quella proprietà, quindi gestisci l'evento _RowCommand.
Ad esempio:
<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
Il modo più semplice che ho trovato è usare Comando sull'evento Fai clic sull'evento e invia l'ID elemento come argomento del comando.
Puoi anche passare in rassegna le righe in GridView e confrontare ImageButton nella riga con l'argomento mittente
nell'evento Click.
Questo è un ottimo trucco. Ho anche un altro trucco. Puoi provarlo ...
protected void userGridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow rowSelect = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int rowindex = rowSelect.RowIndex;
}
}
È anche un buon metodo.