Question:

I’m trying to pass a value to a user control by setting a property. I’m using code behind. How do I pass a value to the user control?

Answer:

In code behind you have to create an instance of the user control, the same way you would for any server control. You map an instance of the user control’s class the user control instance in the Web Form.

[MyUserControl.ascx User Control]

<%@ Control language=”c#” Inherits=”DotNetJunkies.Samples.A001.MyUserControl01″ %>The value of MyProperty is: <asp:Label runat=”server” id=”MyLabel” />

[MyUserControl.ascx.cs Code Behind]

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;namespace DotNetJunkies.Samples.A001
{
  public class MyUserControl01 : UserControl
  {
    public Label MyLabel;

    public String MyProperty
    {
      set
      {
        MyLabel.Text = value;
      }
      get
      {
        return MyLabel.Text;
      }
    }
  }
}

[UserControlProperty.aspx Web Form]

<%@ Page language=”c#” Inherits=”DotNetJunkies.Samples.A001.UserControlProperty” %>
<%@ Register TagPrefix=”dnj” TagName=”MyUserControl01″ Src=”MyUserControl01.ascx” %>
<html>
<body>
  <form runat=”server”>
    <dnj:MyUserControl01 runat=”server” id=”MyUserControl01A” />
  </form>
</body>
</html>

[UserControlProperty.aspx.cs Code Behind]

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;namespace DotNetJunkies.Samples.A001
{
  public class UserControlProperty : Page
  {
    //Map an instance of the class to the user control in the Web Form
    protected
 DotNetJunkies.Samples.A001.MyUserControl01 MyUserControl01A;

    protected void Page_Load ( Object sender, EventArgs e )
    {
      MyUserControl01A.MyProperty = “This is the property value. “;

      //You could also create an instance of the control using FindControl
      Control _myUC = Page.FindControl ( “MyUserControl01A” );
      //Cast the control as an instance of the MyUserControl01 type and 
      //set the MyProperty property

      ( (MyUserControl01)_myUC ).MyProperty += “This is another value.”;
    }
  }
}