2009-03-26 6 views
12

Ho una vista a griglia e ho bisogno di fare un evento in caso di clic su una riga.Creazione di un'intera riga selezionabile in una vista a griglia

Esiste un evento GridView esistente che è necessario associare per rendere questo possibile?

+0

controllare questa domanda http://stackoverflow.com/questions/6250545/how-to-implement-full-row-selecting-in-gridview-without-select-button – Nalaka526

+0

Eventuali duplicati di [Come implementare selezione di righe complete in GridView senza selezionare il pulsante?] (https: // StackOverflow.it/questions/6250545/how-to-implement-full-row-select-in-gridview-senza-select-button) – AsifAli72090

risposta

0

Nessun evento esistente per gestire un clic di riga completo. La cosa migliore è avere qualche javascript (magari tramite ASP.NET Ajax) per rilevare il clic e lanciare l'evento da solo. In alternativa dovresti creare un pulsante o una casella di controllo che l'utente seleziona.

0

È necessario gestire l'evento "SelectedIndexChanged", è quindi possibile interrogare la griglia per .SelectedRow. Alternativley utilizzare l'evento "SelectedIndexChanging" che definisce "e.NewSelectedIndex"

+0

Ma quegli eventi si attivano solo quando GridView viene associato, no? non quando un utente fa clic su una riga –

0

Partenza this article da Teemu, in cui si spiega circa clic su una riga GridView e gettare l'evento RowClicked.

Ecco un estratto del codice:

Protected Overrides Sub RaisePostBackEvent(ByVal eventArgument As String) 
      If eventArgument.StartsWith("rc") Then 
       Dim index As Integer = Int32.Parse(eventArgument.Substring(2)) 
       Dim args As New GridViewRowClickedEventArgs(Me.Rows(index)) 
       OnRowClicked(args) 
      Else 
       MyBase.RaisePostBackEvent(eventArgument) 
      End If 

     End Sub 

Public Class GridViewRowClickedEventArgs 
     Inherits EventArgs 

     Private _row As GridViewRow 
     Public Sub New(ByVal row As GridViewRow) 
      _row = row 
     End Sub 
     Public ReadOnly Property Row() As GridViewRow 
      Get 
       Return _row 
      End Get 
     End Property 
    End Class 

Btw, è in VB non C# però.

1

Alcuni programmi javascript saranno necessari per fare in modo che ciò accada.

Fondamentalmente si dovrà gestire l'evento click per la riga (alcuni browser la riga non ha un evento click quindi potrebbe essere necessario gestire l'evento click del tds ... tempo di investire in un ajax framework!)

Da javascript dovrai quindi attivare un postback con l'indice di riga come parametro. Vedi encosia (un ottimo sito per ASP.Net - implementazioni ajax) su come farlo. Ecco un link a un articolo del genere

16

Ecco qualcosa che ho preparato in precedenza:


public class RowClickableGridView : GridView 
    { 
     public Style HoverRowStyle 
     { 
      get { return ViewState["HoverRowStyle"] as Style; } 
      set { ViewState["HoverRowStyle"] = value; } 
     } 

     public bool EnableRowClickSelection 
     { 
      get { return ViewState["EnableRowClickSelection"] as bool? ?? true; } 
      set { ViewState["EnableRowClickSelection"] = value; } 
     } 

     public string RowClickCommand 
     { 
      get { return ViewState["RowClickCommand"] as string ?? "Select"; } 
      set { ViewState["RowClickCommand"] = value; } 
     } 

     public string RowToolTip 
     { 
      get 
      { 
       if (!RowToolTipSet) return string.Format("Click to {0} row", RowClickCommand.ToLowerInvariant()); 
       return ViewState["RowToolTip"] as string; 
      } 
      set 
      { 
       ViewState["RowToolTip"] = value; 
       RowToolTipSet = true; 
      } 
     } 

     private bool RowToolTipSet 
     { 
      get { return ViewState["RowToolTipSet"] as bool? ?? false; } 
      set { ViewState["RowToolTipSet"] = value; } 
     } 

     protected override void OnPreRender(EventArgs e) 
     { 
      base.OnPreRender(e); 
      foreach (GridViewRow row in Rows) 
      { 
       if (row.RowType != DataControlRowType.DataRow) continue; 

       if (EnableRowClickSelection && row.RowIndex != SelectedIndex && row.RowIndex != EditIndex) 
       { 
        if (string.IsNullOrEmpty(row.ToolTip)) row.ToolTip = RowToolTip; 
        row.Style[HtmlTextWriterStyle.Cursor] = "pointer"; 

        PostBackOptions postBackOptions = new PostBackOptions(this, 
                      string.Format("{0}${1}", 
                         RowClickCommand, 
                         row.RowIndex)); 
        postBackOptions.PerformValidation = true; 
        row.Attributes["onclick"] = Page.ClientScript.GetPostBackEventReference(postBackOptions); 


        foreach (TableCell cell in row.Cells) 
        { 
         foreach (Control control in cell.Controls) 
         { 
          const string clientClick = "event.cancelBubble = true;{0}"; 
          WebControl webControl = control as WebControl; 
          if (webControl == null) continue; 
          webControl.Style[HtmlTextWriterStyle.Cursor] = "Auto"; 
          Button button = webControl as Button; 
          if (button != null) 
          { 
           button.OnClientClick = string.Format(clientClick, button.OnClientClick); 
           continue; 
          } 
          ImageButton imageButton = webControl as ImageButton; 
          if (imageButton != null) 
          { 
           imageButton.OnClientClick = string.Format(clientClick, imageButton.OnClientClick); 
           continue; 
          } 
          LinkButton linkButton = webControl as LinkButton; 
          if (linkButton != null) 
          { 
           linkButton.OnClientClick = string.Format(clientClick, linkButton.OnClientClick); 
           continue; 
          } 
          webControl.Attributes["onclick"] = string.Format(clientClick, string.Empty); 
         } 
        } 
       } 

       if (HoverRowStyle == null) continue; 
       if (row.RowIndex != SelectedIndex && row.RowIndex != EditIndex) 
       { 
        row.Attributes["onmouseover"] = string.Format("this.className='{0}';", HoverRowStyle.CssClass); 
        row.Attributes["onmouseout"] = string.Format("this.className='{0}';", 
                   row.RowIndex%2 == 0 
                    ? RowStyle.CssClass 
                    : AlternatingRowStyle.CssClass); 
       } 
       else 
       { 
        row.Attributes.Remove("onmouseover"); 
        row.Attributes.Remove("onmouseout"); 
       } 
      } 
     } 

     protected override void Render(HtmlTextWriter writer) 
     { 
      base.Render(writer); 
      foreach (GridViewRow row in Rows) 
      { 
       if (row.RowType == DataControlRowType.DataRow) 
       { 
        Page.ClientScript.RegisterForEventValidation(row.ClientID); 
       } 
      } 
     } 
    } 
 

È quindi gancio nel eventi di comando fila standard di ...

+1

Appena provato, funziona bene! –

+1

+1 ha funzionato anche per me! Grazie. – Eddie

+0

@MPritch: Potresti aiutarmi a usare questa lezione per favore? –

0

questo può essere fatto facilmente con l'aggiunta di un dummy LinkButton senza testo per GridView e qualche codice nel RowDataBound. Il LinkButton è necessario sulla pagina per evitare l'errore Invalid postback or callback argument. Anche l'impostazione della visibilità su false causerà questo errore.

Il LinkButton ha anche un CommandArgument con il numero di riga corrente e un evento OnCommand per gestire il clic effettivo.

<asp:TemplateField> 
    <ItemTemplate> 
     <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Container.DataItemIndex %>' OnCommand="LinkButton1_Command"></asp:LinkButton> 
    </ItemTemplate> 
</asp:TemplateField> 

Il metodo OnRowDataBound

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    //check if the row is a datarow 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     //find the linkbutton with findcontrol and cast it back to one 
     LinkButton lb = e.Row.FindControl("LinkButton1") as LinkButton; 

     //create the correct postback event with the UniqueID property of the linkbutton 
     string href = "javascript:__doPostBack('" + lb.UniqueID + "','')"; 

     //add the onclick event with the correct href to the row 
     e.Row.Attributes.Add("onclick", href); 

     //to make it visible to the user that the row can be clicked 
     e.Row.Attributes.Add("style", "cursor:pointer;"); 
    } 
} 

E il metodo di comando dove è possibile ottenere il CommandArgument dal LinkButton e fare ogni sorta di cose pulite con esso.

protected void LinkButton1_Command(object sender, CommandEventArgs e) 
{ 
    //the row index of the clicked row from the grid if needed 
    int rowIndex = Convert.ToInt32(e.CommandArgument); 

    //do stuff 
}