简体   繁体   English

为什么无法在.aspx页中访问usercontrol中的控件?

[英]Why a control inside usercontrol is not accessible in .aspx page?

I have created a user control with a radio button inside it. 我创建了一个带有单选按钮的用户控件。 I have also created a public property of type radio button and assigned it that radio button so can be accessed in aspx pages code behind. 我还创建了一个单选按钮类型的公共属性,并将其分配给该单选按钮,以便可以在后面的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;
    }
}

now I have dragged that user control into .aspx page and tried accessing a radio button inside user control but is throws 'null reference exception'. 现在,我已将该用户控件拖到.aspx页中,并尝试访问该用户控件内的单选按钮,但抛出“空引用异常”。

.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 .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);
            }
        }
    }
}

You should implement the get property: 您应该实现get属性:

public RadioButton radiobtn
{
    get
    {
        return RadioButton1;
    }
}

You Page Page_Load runs before the control's Page_Load. 您的Page PageLoad运行在控件的Page_Load之前。

This page shows the order of events: 此页面显示事件的顺序:

https://msdn.microsoft.com/en-us/library/ms178472.aspx https://msdn.microsoft.com/zh-CN/library/ms178472.aspx

You could access the control in LoadComplete or PreRender, but not on Page_Load 您可以在LoadComplete或PreRender中访问控件,但不能在Page_Load中访问

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM