Well, there's always the good old
Control ctrl = null;
switch (type)
{
case "Textbox":
ctrl = new TextBox();
break;
case ...
case ...
case ...
}
if (ctrl != null)
{
plc.Controls.Add(ctrl);
}
but that doesn't sound fun, does it?
You can load types like this:
Type t = Type.GetType("Textbox")
if (t != null)
{
Control c = (Control)Activator.CreateInstance(t);
}
there are 2 problems with this. (a) types stored in the GAC (which all
the
built-in ones are), require the fully quantified STRONG name. So you'd
need
to have "System.Web.UI.WebControls.TextBox, System.Web,
Version=1.0.5000.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Don't fret, if you go to c:\windows\assembly and view the properties of
System.Web you'll get everything you need (the above information is
correct
actually
)
The other problem is that this will give you Control object, so you can't
do
Control c =
(Control)Activator.CreateInstance("System.Web.UI.WebControls.TextBox,
System.Web, Version=1.0.5000.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a");
c.MaxLength = x.Attributes["maxLength"].value;
since control doesn't define MaxLength.
and you can't declare it a textbox, 'cuz if you knew it was gonna be a
textbox we wouldn't have this mess to begin with
I guess what I'd do is copy all the attributes of you xml element which
aren't "id", "type" or any other standard WEBControl property and copy
them
into the control's attribute property:
Type t = Type.GetType("Textbox")
if (t != null)
{
WebControl c = (WebControl)Activator.CreateInstance(t);
foreach (XmlAttribute attribute in element)
{
if (attribute.Name != "type" && attribute.Name != "id")
{
c.Attributes.Add(attribute.Name, attribute.Value);
}
}
}
anyways, all this code is off the top of my head, but hope it helps..
Karl
--
MY ASP.Net tutorials
http://www.openmymind.net/
I have an xml file which looks similar to this:
<data>
Please enter the value:
<dynamicControl id="myDC", type="Textbox", MaxLength="100"/>
</data>
I am trying to devise a way to have a web page load this file in it's
Load
event and render the text and controls at run-time, so that I can
dynamicall
change the content that a user sees and the controls that a user can
use
by
altering the xml file.
Does anyone know how to do this? How do I dynamically create a control
in
my code based on string parameter values?
TIA,