Home > Software design >  Me.controls.Item on a VB.net Form is returning System.nullReferenceException 'object reference
Me.controls.Item on a VB.net Form is returning System.nullReferenceException 'object reference

Time:12-14

I've created a vb net form that uses an array list to load data into various controls. (ultimately this is to interface with the Autodesk Inventor API, but I'm not failing the API part)

My first form(1) works correctly. I needed to break my form into multiple forms due to too much information. In Visual Studio 2022 I copied my Form1, pasted it and renamed it to Form2 then changed the references to Form1 located in Form2.designer.vb. To switch between Forms, I created a 'MainMenu' form to call either Form1 or Form2

By all manner of double checking, my method of calling my Form1 or Form2 are a copy paste (other than form names)

On my new form2, I cannot access any controls using the Me.Controls.Item method. I use a button to run the population of my textbox controls, so they exist.

works: Me.textbox1.text = "some string" Me.text = "form name string"

doesn't work: Me.Controls.Item("textbox1").text = "any string"

In debug, mousing over the error line I get: Me = {Projectname.Form1...} Me.Controls = {System.Windows.Forms.Form.ControlCollection} Me.Controls.Item("textbox1") = Nothing In the Autos window, I can see my textbox1 in Me.Controls > Owner > textbox1 (and my 'some string' value) I can also see my control in the Locals Me > textbox1

I guess I did something wrong when Copy/Pasting my Form1 to Form2 I created a new Form3 and copy pasted the controls and the Code from my Form2 and I have the same issue. I have crated a new Form4 and created a new control (textbox) without a copy paste and things seem to work on that form, so far.

I'm sure somebody could fix this in seconds, but I'm tapped out. My Form2 (i could have sworn it worked before) has a lot of time into formatting multiple layers of tablelayoutpanels and would really like to not re-create my form2 from scratch.

CodePudding user response:

If Me.Controls.Item("textbox1") is Nothing then there is no control whose Name property is "textbox1" and whose direct Parent is the form. As you can see, there are two conditions that could cause that to be the case. The control you want does not have its Name property set to "textbox1" and/or its direct Parent is some other control, e.g. a Panel.

Personally, I would scrap that form and create a new one the conventional way. Obviously you have done something wrong so who knows how far-reaching the issue(s) is?

  • Related