C# – Instantiate User Control with Custom Attributes

ccontrols

My User Control has the following properties:

private String _requestIP;
public String RequestIP
{
     get { return _requestIP; }
     set { _requestIP = value; }
}

When adding a instance of the Control to an aspx page at design time it's easy to assign the attributes which can be utilized in the codebehind file…

<uc:Item ID="Testing" runat="server" RequestIP="127.0.0.1" />

However, if I try to create the control at runtime in the aspx.cs file, how am I able to assign values to these attributes?

Control ItemX = (Control)Page.LoadControl("/controls/item.ascx");

There is no ItemX.Attributes.Add() method which I would expect to be there, and no ItemX.RequestIP property to set.

Is there a way to set this dynamically in the aspx page using <%= Users_IP_Address %> tags or some other method?

Best Answer

Well, you just need to cast it to the appropriate type (whatever the class name of your user control is).

Related Topic