2009-03-26 29 views
12

Tôi có chế độ xem lưới và tôi cần tạo sự kiện khi có hàng được nhấp.Làm cho toàn bộ hàng có thể nhấp vào trong chế độ xem lưới

Có sự kiện GridView hiện tại mà tôi cần phải liên kết để thực hiện điều này không?

+0

Kiểm tra câu hỏi này http://stackoverflow.com/questions/6250545/how-to-implement-full-row-selecting-in-gridview-without-select-button – Nalaka526

+0

trùng lặp có thể xảy ra của [Làm thế nào để thực hiện chọn hàng đầy đủ trong GridView mà không cần chọn nút?] (https: // stackoverflow.com/questions/6250545/how-to-implement-full-row-select-in-gridview-without-select-button) – AsifAli72090

Trả lời

0

Không có sự kiện hiện có nào để xử lý toàn bộ nhấp chuột vào hàng. Đặt cược tốt nhất của bạn là để có một số javascript (có thể thông qua ASP.NET Ajax) phát hiện các nhấp chuột và bắn các sự kiện chính mình. Hoặc bạn sẽ phải tạo một nút hoặc hộp kiểm mà người dùng chọn.

0

Bạn cần xử lý sự kiện "SelectedIndexChanged", sau đó bạn có thể truy vấn lưới cho .SelectedRow. Alternativley sử dụng sự kiện "SelectedIndexChanging" đặt "e.NewSelectedIndex"

+0

Nhưng các sự kiện đó chỉ xảy ra khi GridView bị ràng buộc, phải không? không phải khi người dùng nhấp vào một hàng –

0

Kiểm tra this article bởi Teemu, tại nơi ông giải thích về cách nhấp vào hàng trong Gridview và ném sự kiện RowClicked.

Dưới đây là một đoạn trích của mã:

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, đó là trong VB không C# mặc dù.

1

Một số chương trình javascript sẽ được yêu cầu để thực hiện điều này. Về cơ bản, bạn sẽ phải xử lý sự kiện nhấp chuột cho hàng (là một số trình duyệt hàng không có sự kiện nhấp để bạn có thể phải xử lý sự kiện nhấp của tds ... thời gian để đầu tư vào một khung ajax!)

Sau đó, bạn sẽ từ javascript phải kích hoạt postback với chỉ mục hàng làm tham số. Xem encosia (một trang web tuyệt vời để triển khai ASP.Net - ajax) về cách thực hiện điều đó. Đây là một link một bài báo cùng những dòng

16

Dưới đây là một cái gì đó tôi đã chuẩn bị trước đó:


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

Sau đó bạn móc vào các sự kiện lệnh hàng chuẩn ...

+1

Chỉ cần thử điều này - hoạt động độc đáo! –

+1

+1 Làm việc cho tôi! Cảm ơn. – Eddie

+0

@MPritch: Bạn có thể giúp tôi cách sử dụng lớp này không? –

0

Điều này có thể được thực hiện dễ dàng bằng cách thêm một giả LinkButton không có văn bản cho GridView và một số mã trong RowDataBound. Cần có LinkButton trên trang để tránh lỗi Invalid postback or callback argument. Đặt mức hiển thị thành false cũng sẽ gây ra lỗi này.

LinkButton cũng có CommandArgument với số hàng hiện tại và sự kiện OnCommand để xử lý nhấp chuột thực tế.

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

Phương pháp 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;"); 
    } 
} 

Và phương pháp chỉ huy, nơi bạn có thể nhận được CommandArgument từ LinkButton và làm tất cả các loại vật gọn gàng với nó.

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 
} 
Các vấn đề liên quan