❔ How can I access items from another form in a different form?
How can I access items from another form in a different form?
7 Replies
They have to be public members to be accessible from the instance of the form. You can change that in the Properties window. This changes the definition of the member and is not a property in the control itself. You can also pass data through the constructor when one form creates another one.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/accessibility-levels Channing the accessibility through the Properties window will change how the member for the control is generated in Designer.cs
How can I access it programmatically? Like this?
Form1.pictureBox1.Hide();
Assuming Form1 is an instance, yes; but I wouldn’t handle the case that way; winforms won’t know that you’ve taken a cross form dependency so if you need to delete the picture box, rename ( that might work ), change control type, etc will break your application because of tight coupling. You can make the coupling moderately looser by implementing some sort of method on form1. So then you’d have something like form1.HidePictureElements();
HidePictureElements would handle the toggling of picturebox1 giving you more freedom to change what that means for form1.
You still have some connection between form1 and some other form; but it’ll be a larger scope to solve that problem, where form1 and form2 don’t know about each other
You might create a Singleton class called UxCoordinator for instance that has methods to raise events, and forms can take a dependency on UxCoordinator and subscribe to events then form1 and form2 know nothing about each other
Keep the data outside of the forms.
At that point just abandon winforms and use something with something approaching proper data bindings
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.