0

Please help me: How can I solve this "Object reference not set to an instance of an object" error when using Reflection. I'm a creating this "programme" to teach languages. Each Topic is in a separate form because it has many activities. I have a form which shows a list of activities. When pressing a button called "Empezar" the selected topic (form) should be shown: I'm trying to call one of these forms from a string which contains its name. I think the variable is already declared as a form. I also think the function helps the variable refering to a form, but after debugging I realized the error is here. The name of the form is correct, too. So what do you think the problem is?

Private Sub Btn_EMPEZAR_Click(ByVal sender As System.Object, ByVal e As 
System.EventArgs) Handles Btn_EMPEZAR.Click

  Dim strCreatedFromButton As String = "Frm_The_Greetings" 
  Dim frm As New Form

  frm = DirectCast(CreateObjectInstance(strCreatedFromButton), Form)

  frm.Show() 

End Sub


Public Function CreateObjectInstance(ByVal objectName As String) As Object

  Dim obj As Object

  Try

    If objectName.LastIndexOf(".") = -1 Then
      objectName = [Assembly].GetEntryAssembly.GetName.Name & "." & objectName
    End If

    obj = [Assembly].GetEntryAssembly.CreateInstance(objectName) 'The 'problem is here. 
'But I don't know how to correct this 
'because I copied the code 
'from another web page because 
'I'm just trying to learn by myself :/ 
'Why Obj Variable is still equal to "Nothing" after this line? :/

  Catch ex As Exception
  obj = Nothing

  End Try
  Return obj

End Function
Cœur
  • 32,421
  • 21
  • 173
  • 232
  • You solve it the same way as you do if reflection is not involved. You step through the relevant code in the debugger and determine why the reference is null (Nothing) and fix it. – TnTinMn Feb 28 '18 at 00:46
  • I couldn't realize what the problem was. I read for many hours but I think the problem was I didn't understand how to use [Assembly].GetEntryAssembly.CreateInstance(objectName). It wasn't laziness. I only slept 2 hours last night trying to get a solution. Maybe I was doing something wrong in the parameters section, but well... I will just never know. I had to completely change the approach from getting Strings to Types. Then I used: Dim frm As New Form. 'Then I wrote: frm = DirectCast(Activator.CreateInstance(TypeGotFrom), Form). Finally: frm.Show() – Sergio Frías Feb 28 '18 at 14:32

0 Answers0