[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 270
  • Last Modified:

creating controls dynamically

I'm trying to create a control from a string in a database:

Dim asm As [Assembly] =
Reflection.Assembly.LoadFrom("C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Web.dll")

Dim typ As Type = asm.GetType("System.Web.UI.WebControls.TextBox", True,
True)

Dim o As Object = Activator.CreateInstance(typ)

Me.Controls.Add(CType(o, Control))

I get "Specified cast is not valid." with the line of code directly above.
How do I/ Can I cast a type to a control?

0
paulscalf
Asked:
paulscalf
  • 2
  • 2
1 Solution
 
hismightinessCommented:
I may have not paid enough attention but should this be change to?:

Me.Controls.Add(CType(o, TextBox))

OR

Me.Controls.Add(CType(o, System.Web.UI.WebControls.TextBox))
0
 
paulscalfAuthor Commented:
"System.Web.UI.WebControls.TextBox" is a string being passed into the function therefore, neither of these will work. We are creating a data driven app. I'd like to pass in the name of a control, again as a string, e.g."System.Web.UI.WebControls.TextBox", and be able to create a control to add to the form or webform... Thanks.
0
 
Jeff CertainCommented:
The issue is that you are returning a string, and passing it to get the type of an object... which will return string for your case.

Try this approach.

private function getTypeFromName(typeName as string) as type
select case typeName
case  "System.Web.UI.WebControls.TextBox"
  return GetType(textbox)
end select
end function

Then, use this code...

Dim typ As Type = asm.GetType(getTypeFromName(typeName), True,
True)

Dim o As Object = Activator.CreateInstance(typ)

Me.Controls.Add(CType(o, Control))
0
 
paulscalfAuthor Commented:
I can't use a case. I would have to add to cases to the getTypeFromName function for each control I wanted to create. How do I/ Can I from only a string, "System.Web.UI.WebControls.TextBox" create a control and add it to a form or webform?
0
 
Jeff CertainCommented:
I've had to do this in the past and couldn't find any way other than using a select statement to return the proper type. Although .Net supports the Type.ToString, there doesn't seem to be any way to do the reverse.
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now