Question

I want to add usercontrols to my page based on a XML:

<?xml version="1.0" encoding="utf-8" ?>
<Fields>
<Group name="Main" text="Innhold">
<Field type="TextBox" name="Name" text="Navn"></Field>
</Group>
</Fields>

The usercontrol looks like this TextBox.ascx:

<div class="fieldWrapper">
<asp:Label runat="server"><%=Label %></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" />
</div>

I do a LoadControl based on the type attribute in the xml. Like: LoadControl(type + ".ascx"):

var fields = from x in element.Elements("Field") select new
{
type = x.Attribute("type").Value,
name = x.Attribute("name").Value,
text = x.Attribute("text").Value,
                                    };
foreach (var field in fields)
{
var control = LoadControl("~/UserControls/FieldControls/" + field.type + ".ascx");
pnl.Controls.Add(control);
}
FieldsHolder.Controls.Add(pnl);

I want to pass the text attribute from the xml to the Label in TextBox.ascx. Like so: ctrl.Label = field.text I know if i cast the control to the correct type I can do that, but i dont know the type. Can i use reflection for this some way?

Was it helpful?

Solution

I assume all your UserControls share the same properties like 'Label'. I would have created an interface like below

public interface IUserControl
{
    string Label { get; set; }
}

Here is the implementation of UserControl

CODE

public partial class TextBox : System.Web.UI.UserControl, IUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private string _label;
    public string Label
    {
        get { return _label; }
        set { _label = value; }
    }
}

You can now load the control and set property like below

foreach (var field in fields)
{
   var control = LoadControl("~/UserControls/FieldControls/" + field.type + ".ascx");
   (control as IUserControl).Label = field.text;
   pnl.Controls.Add(control);
}

I hope it helps you achieve what you wanted..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top