2014-03-29 50 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是请求 - 响应系统,你不能从服务器访问客户端控件。

如果控件未在服务器上运行,则在客户端收到它到浏览器后无法更改它。