简体   繁体   中英

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.

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

<%@ 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);
            }
        }
    }
}

You should implement the get property:

public RadioButton radiobtn
{
    get
    {
        return RadioButton1;
    }
}

You Page Page_Load runs before the control's Page_Load.

This page shows the order of events:

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

You could access the control in LoadComplete or PreRender, but not on Page_Load

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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