2009-03-26 9 views
12

J'ai un gridview et je dois faire un feu d'événement quand une rangée est cliquée.Rendre une ligne entière cliquable dans une vue en grille

Y a-t-il un événement GridView existant auquel je dois me lier pour que cela se produise?

+0

Cocher cette question http://stackoverflow.com/questions/6250545/how-to-implement-full-row-selecting-in-gridview-without-select-button – Nalaka526

+0

double possible de [Comment mettre en œuvre sélection de ligne complète dans GridView sans bouton de sélection?] (https: // stackoverflow.com/questions/6250545/how-to-implement-full-row-selection-in-gridview-without-select-button) – AsifAli72090

Répondre

0

Aucun événement existant ne peut gérer un clic de ligne entier. Votre meilleur pari est d'avoir du javascript (peut-être via ASP.NET Ajax) détecter le clic et déclencher l'événement vous-même. Sinon, vous devez créer un bouton ou une case à cocher que l'utilisateur sélectionne.

0

Vous devez gérer l'événement "SelectedIndexChanged", vous pouvez ensuite interroger la grille pour le .SelectedRow. Alternativley utiliser l'événement "SelectedIndexChanging" qui définit "e.NewSelectedIndex"

+0

Mais que les événements ne se déclenchent que lorsque GridView est en cours de liaison, non? pas quand un utilisateur clique sur une ligne –

0

Découvrez this article par Teemu, dans lequel il explique comment cliquer sur une ligne dans Gridview et lancer l'événement RowClicked.

Voici un extrait du code:

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, il est en VB pas C# bien.

1

Une programmation javascript sera nécessaire pour que cela se produise.

Fondamentalement, vous allez devoir gérer l'événement click pour la ligne (dans certains navigateurs, la ligne n'a pas d'événement click, vous devrez peut-être gérer l'événement click du tds ... le temps d'investir dans un ajax framework!)

Vous aurez alors à partir de javascript de déclencher une publication avec l'index des lignes en paramètre. Voir encosia (un excellent site pour ASP.Net - implémentations ajax) sur la façon de faire cela. Voici un link un article le long de ces lignes

16

Voici quelque chose que je préparais plus tôt:


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); 
       } 
      } 
     } 
    } 
 

Vous accrochez ensuite dans les événements de commande de ligne standards ...

+1

Juste essayé ceci - fonctionne bien! –

+1

+1 A travaillé pour moi aussi! Merci. – Eddie

+0

@MPritch: Pourriez-vous m'aider à utiliser cette classe s'il vous plaît? –

0

Cela peut se faire facilement en ajoutant un mannequin LinkButton sans texte à la GridView et du code dans le RowDataBound. Le LinkButton est nécessaire sur la page pour éviter l'erreur Invalid postback or callback argument. Définir la visibilité à false provoquera également cette erreur. Le LinkButton a également un CommandArgument avec le numéro de ligne actuel et un événement OnCommand pour gérer le clic réel.

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

La méthode 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;"); 
    } 
} 

et la méthode de commande où vous pouvez obtenir le CommandArgument de la LinkButton et faire toutes sortes de choses intéressantes avec elle.

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 
} 
Questions connexes