[英]Why a control inside usercontrol is not accessible in .aspx page?
我創建了一個帶有單選按鈕的用戶控件。 我還創建了一個單選按鈕類型的公共屬性,並將其分配給該單選按鈕,以便可以在后面的aspx頁面代碼中對其進行訪問。
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);
}
}
}
}
您應該實現get屬性:
public RadioButton radiobtn
{
get
{
return RadioButton1;
}
}
您的Page PageLoad運行在控件的Page_Load之前。
此頁面顯示事件的順序:
https://msdn.microsoft.com/zh-CN/library/ms178472.aspx
您可以在LoadComplete或PreRender中訪問控件,但不能在Page_Load中訪問
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.