2017-07-15 45 views
0

我已经创建了一个用户控件,里面有一个单选按钮。我还创建了一个单选按钮类型的公共属性,并为它指定了单选按钮,因此可以在后面的aspx页面代码中进行访问。为什么在.aspx页面中无法访问usercontrol内的控件?

public partial class WebUserControl : System.Web.UI.UserControl 
{ 
    public RadioButton radiobtn { get; set; } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     initiateControls(); 
    } 
    private void initiateControls() 
    { 
     radiobtn = RadioButton1; 
    } 
} 

我现在已经拖用户控制到.aspx页面中,并试图访问用户控件中一个单选按钮,而是抛出“空引用异常”。

的.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %> 





<%@ Register src="UserControls/WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %> 





<!DOCTYPE html> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 

     <uc1:WebUserControl ID="WebUserControl1" runat="server" /> 

    </div> 
    </form> 
</body> 
</html> 

的.cs

public partial class test : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      try 
      { 


       WebUserControl1.radiobtn.Visible = false; 
      } 
      catch (Exception ex) 
      { 

       Response.Write(ex.Message); 
      } 
     } 
    } 
} 
+0

我猜你的''Page_Load'你的** .aspx.cs **在你的UserControl被初始化之前调用。 – Alisson

+0

请参阅[Gary.S答案](https://stackoverflow.com/questions/8160319/all-controls-are-null-within-usercontrol?rq=1)。 – Alisson

回答

1

你应该实现获取属性:

public RadioButton radiobtn 
{ 
    get 
    { 
     return RadioButton1; 
    } 
} 
+0

两者已经存在:'get;设置;' – VDWWD

+0

@VDWWD确定它们存在但是空的,所以你只能得到你设定的。在我的情况下,相反,您会得到'RadioButton1'的引用,这是用户控件中定义的单选按钮。 –

+0

你说得对,我的错。 – VDWWD

相关问题