By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,899 Members | 1,230 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,899 IT Pros & Developers. It's quick & easy.

Is it possible to convert an Object Type into another?

P: 29
Hi
I'm trying to do this:

Expand|Select|Wrap|Line Numbers
  1. Dim MyForm As New Object
  2.  
  3.    or
  4.  
  5. Dim MyForm As System.Windows.Forms.Form
  6.  
  7. Select Case Form.Activeform.Name
  8.   Case My.Forms.Form1.Name
  9.      MyForm = My.Forms.Form1
  10.   Case My Forms.Form2.Name
  11.      MyForm = My.Forms.Form2
  12. End Select
  13.  
The problem comes because MyForm is still an Object or Form type.
So I need to convert MyForm Type whether into Form1 or Form2, in order to be access to properties and methods of one of those class.

I tried with Ctype, DirectCast, TryCast, Convert.ChangeType... etc., and MyForm always keep its Object or Form Type.

Doing a unboxing neither works to me. For instance:

CType(MyForm, Form2).property.xxxx.focus()

That works but not to what I really need. I want to convert MyForm or whatever it was into a Form1 or Fomr2 Class.

Thanks.
Apr 30 '15 #1
Share this Question
Share on Google+
1 Reply


Seth Schrock
Expert 2.5K+
P: 2,939
I'm not sure what you are looking for, but I think that you are wanting to be able to reference a form based on its string name and have access to all its controls, properties and methods. If this is the case, then you would need to paste this function into your class:
Expand|Select|Wrap|Line Numbers
  1. 'from http://vbcity.com/forums/t/32930.aspx
  2. Function GetFormByName(ByVal FormName As String) As Form
  3.     'first try: in case the full namespace has been provided (as it should ;-) )
  4.     Dim T As Type = Type.GetType(FormName, False)
  5.     'if not found prepend default namespace
  6.     If T Is Nothing Then
  7.         Dim Fullname As String = Application.ProductName & "." & FormName
  8.         T = Type.GetType(Fullname, True, True)
  9.     End If
  10.     Return CType(Activator.CreateInstance(T), Form)
  11. End Function
You would then use your Form.Activeform.Name as the argument when calling this function.
May 5 '15 #2

Post your reply

Sign in to post your reply or Sign up for a free account.