0

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?

espvar
  • 1,045
  • 5
  • 16
  • 28

1 Answers1

1

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..

Tariqulazam
  • 4,535
  • 1
  • 34
  • 42
  • I tried this but i still cannot reach the Label property. Created an interface with the labelproperty. implemented the interface in TextBox.ascx. wrote the control loading "as IFieldControl". (control as IFieldControl).Label gives "Cannot resolve symbol 'Label'" – espvar Oct 22 '12 at 21:21
  • Is it compiling properly? Please note 'IFieldControl' is already a part of the framework in .NET 4.0. Please make sure you are using the correct namespace for IFieldControl. I would suggest to rename the Interface to IuserControl and try again. – Tariqulazam Oct 22 '12 at 21:24
  • I just figured that to. I changed the name and voila. It works. Thang you! – espvar Oct 22 '12 at 21:27