我已经创建了一个用户控件,里面有一个单选按钮。我还创建了一个单选按钮类型的公共属性,并为它指定了单选按钮,因此可以在后面的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);
}
}
}
}
我猜你的''Page_Load'你的** .aspx.cs **在你的UserControl被初始化之前调用。 – Alisson
请参阅[Gary.S答案](https://stackoverflow.com/questions/8160319/all-controls-are-null-within-usercontrol?rq=1)。 – Alisson