0

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

2 Answers2

1

You should implement the get property:

public RadioButton radiobtn
{
    get
    {
        return RadioButton1;
    }
}
VDWWD
  • 35,079
  • 22
  • 62
  • 79
Stefano Losi
  • 719
  • 7
  • 18
  • @VDWWD sure they were present but empty,..so you could get only what you had set. In my case, instead, you get the reference of 'RadioButton1', which is the radio button defined in the user control. – Stefano Losi Jul 15 '17 at 23:39
0

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

Garr Godfrey
  • 8,257
  • 2
  • 25
  • 23