2014-03-29 47 views
0

我越來越對下一行代碼異常「未設置爲一個對象的實例對象引用」:可見對FindControl已不工作 - asp.net

((HyperLink)Page.FindControl(id)).Visible = false; 

可以採取什麼問題嗎?

這裏是從我的代碼示例:

的.aspx:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="FriendsList.aspx.cs" Inherits="Private_User_Social_FriendsList" %> 
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server"> 
</asp:Content> 
<div class="FriendsProposal" runat="server"> 
<div class="FriendsProposal_Header">FriendsP</div> 
<div id="FriendsProposalPH" class="FriendsProposalPH" runat="server"></div> 

.aspx.cs:

public partial class Private_User_Social_FriendsList : System.Web.UI.Page 
{ 
    DBservices DBS = new DBservices(); 
    protected void Page_Load(object sender, EventArgs e) 
     List<Friends> ListFriendsProposal = DBS.getFriendsProposal(User.Identity.Name.ToString()); 
     foreach (Friends FRIndex in ListFriendsProposal) 
     { 
      string _FriendsOutput = FR_output(FRIndex); 

      HyperLink tempHL = new HyperLink(); 
      tempHL.Text = _FriendsOutput; 
      tempHL.CssClass = "HyperLinkFriends"; 
      tempHL.ID = FRIndex.UdName; 

      FriendsProposalPH.Controls.Add(new LiteralControl("<div style='height:32px' runat='server' >")); 
      FriendsProposalPH.Controls.Add(tempHL); 

       Button tempApprove = new Button(); 
       tempApprove.Text = "Approve"; 
       tempApprove.Click += new EventHandler(cmdUpdate_Click); 
       tempApprove.ID = FRIndex.UdName + "1"; 

       FriendsProposalPH.Controls.Add(tempApprove); 
       FriendsProposalPH.Controls.Add(new LiteralControl("</div>")); 
     } 
    } 

     private void cmdUpdate_Click(object sender, EventArgs e) 
     { 
      Button btn = (Button)sender; 
      string _tempID = btn.ID; 
      string id = _tempID.Substring(0, _tempID.LastIndexOf('1')); 
      DBS.ApproveFriend(User.Identity.Name.ToString(), id); 
      btn.Visible = false; 
      ((HyperLink)Page.FindControl(id)).Visible = false; 
     } 
+1

是Page.FindControl (編號)找到控制?看起來它正在返回null ... –

+0

是的,我檢查並確認了Id的存在。 – Wolf

+0

僅僅因爲id存在,它並不意味着FindControl()可以找到它。它是否在母版頁中? –

回答

0

由於您將命名容器(這是一個佔位符控制,我假設),而不是Page命名容器的超鏈接添加到該命名容器,您應該調用該命名容器上的搜索方法,而不是頁面本身(此方法只在當前命名容器內搜索)。

您所提供的超鏈接的代碼來看總是添加旁邊的按鈕,這樣也許最簡單的方法來訪問正確的命名容器,找到隱藏的超級鏈接控制是這樣的:

btn.NamingContainer.FindControl(id).Visible = false; 
+0

工程太棒了!謝謝! – Wolf

0

你控制你正在嘗試t o發現必須具有runat="server"屬性或者您收到的確切相同的異常被拋出。

不要忘記,asp.net是請求 - 響應系統,你不能從服務器訪問客戶端控件。

如果控件未在服務器上運行,則在客戶端收到它到瀏覽器後無法更改它。