2016-08-02 47 views
0

我的問題是:在GridView中定義爲CommandField的Edit按鈕的ID是什麼?我希望能夠使用代碼隱藏中的FindControl方法來引用此按鈕,但是,由於我不知道編輯按鈕的ID,所以我不能。我必須通過索引來引用它。使用FindControl在GridView中獲取對編輯按鈕的引用

這是我想要做的細節:

我有一個編輯按鈕和刪除按鈕的ASP.NET 4.5.1 GridView控件。它們的定義如下:

<asp:CommandField ShowEditButton="true" UpdateText="Save" ShowDeleteButton="false" ValidationGroup="vgParcelComments" /> 
 
<asp:TemplateField> 
 
    <ItemTemplate> 
 
    <asp:LinkButton ID="btnDeleteParcelComment" runat="server" OnClientClick="return confirm('Are you sure that you want to delete this comment?');" CommandName="Delete" CssClass="removeParcelComment">Delete</asp:LinkButton> 
 
    </ItemTemplate> 
 
</asp:TemplateField>

在RowDataBound事件此GridView控件在我的代碼隱藏頁,我可以用下面的代碼行操縱的刪除按鈕e.Row.FindControl("btnDeleteParcelComment").Visible = False 'The delete button

這隱藏了刪除按鈕。但是,對於Edit按鈕,我無法確定它的ID是什麼,所以我不能使用FindControl函數來訪問它。我可以做的最好的是通過索引引用它,就像這樣:

e.Row.Cells(4).Visible = False 'The edit button

我試着用下面的語句編輯按鈕的ID查找:

Dim itsId As String = e.Row.Cells(4).ID

但是什麼也沒有總是在這條線執行時返回。

德。

回答

2

你可以看看其中有EditCommandName細胞的LinkBut​​ton的的控件集合:

Dim editButton As LinkButton = Nothing 
For Each cell As DataControlFieldCell In e.Row.Cells 
    For Each ctl As Control In cell.Controls 
     If TypeOf ctl Is LinkButton Then 
      Dim commandButton As LinkButton = CType(ctl, LinkButton) 
      If commandButton.CommandName = "Edit" Then 
       editButton = commandButton 
       Exit For 
      End If 
     End If 
    Next 
Next 
+0

德,@ConnorsFan。我在上面的代碼中遇到了一些問題。首先,在ctl變量中返回的對象的類型是一個DataControlLinkBut​​ton。我無法將此類型轉換爲Button。所以我無法檢查CommandName屬性。然而,基於這個代碼示例的靈感,我在一段時間裏迷惑了它,最後想出了這個,我將使用: –

+0

'Dim editButton As LinkBut​​ton = Nothing; For i As Integer = 0 To e.Row.Controls.Count - 1; Dim cell As DataControlFieldCell = e.Row.Cells(i); If TypeOf cell.ContainingField Is CommandField Then; 對於每個項目在cell.Controls; 如果TypeOf項是LinkBut​​ton那麼; editButton = CType(item,LinkBut​​ton); 如果editButton.Text =「編輯」那麼; 退出For; End If; End If; 接下來; 退出For; End If; 接下來; 如果editButton IsNot Nothing那麼; editButton.Visible = False'編輯按鈕; End If;' –

相關問題