Listbox5 can't find another Form

sddd1

Member
Joined
Jul 22, 2021
Messages
14
Programming Experience
1-3
I have a Form1 inside listbox5,

Form2 Can't Find 'listBox5' The name 'listBox5' does not exist in the current context
 
Solution
The error is self-explanatory. listBox5 is not in a context that Form2 can access. In general, you don't want one form reaching into the privates of another form.
The error is self-explanatory. listBox5 is not in a context that Form2 can access. In general, you don't want one form reaching into the privates of another form.
 
Solution
When you add a control to a form, the designer generates a field by which you can access that control. In VB, that field is Public by default, because VB is intended to be easy for beginners, even if that is at the expense of good programming practice. In C#, that field is private by default, which means that it cannot be accessed outside the form it is declared in. You can change that to public if you want to do things the quick and dirty way, or you can leave it as private and learn to do things the proper way.

If you explain what you're actually trying to achieve, rather than just how you're trying to achieve it, we could provide more specific information how to do it properly. Presumably, the user is entering data on Form2 and you want to add that data to a ListBox on Form1. In that case, what you should be doing is exposing the data via a property or method in Form2 and then Form1 gets the data from there and adds it to its own ListBox, thus alleviating the need to expose the control publicly.

How Form1 knows to get the data depends on the scenario. If Form1 calls ShowDialog on Form2 then it would know to get the data when that method returns. If you're calling Show and need to move data while Form2 is still open then things get a bit more complex and Form1 will need to handle an event raised by Form2.

For more details and examples, I suggest that you check out my blog post here. You might want to skip straight to part 3, which shows how to do things properly. Part 1 is VB-specific and uses default form instances, which can be simulated in C#, and part 2 provides other quick and dirty options. They may be of interest for background but part 3 is what you should actually follow if you want to do things right.
 
Back
Top Bottom