I was developing a WindowsForm application in C#, with 2 forms. Regardless of what they both did specifically I needed to access values in form2
and send them to form1
and vice versa. For this to happen I found someone talking about constructor overload and it worked for me as I explain in the code.
Form1:
namespace miniDldMngr
{
public partial class Main : Form
{
miniDldMngr.SettingsForm settingsForm; //Instantiate settingsForm
private void settingsToolStripButton_Click(object sender, EventArgs e)
{
settingsForm = new miniDldMngr.SettingsForm(this); //Create handle for Form1
settingsForm.ShowDialog(); //Form properties were changed to act like a dialog
}
Form2:
namespace miniDldMngr
{
public partial class SettingsForm : Form
{
private Main HandleToForm1; //local variable to store handle to Form1
public SettingsForm()
{
InitializeComponent();
}
public SettingsForm(Main frm1Handle) //overloaded constructor with handle to Form1
{
InitializeComponent();
HandleToForm1 = frm1Handle;
txtIni.Text = HandleToForm1.comboLoad.Text; //here's how i access controls on form1 for example, as long as modifiers are public
}
I came across this answer on Stack Overflow and user codesparkle commented:
It's neither scalable nor OOP-like.
Which lead me to believe that it might not have been the best choice to solve my initial issue. (S)He further added:
One approach is to create an event in the class that knows the information which needs to be shown. The form can then register one of its methods as an event handler. Once the information becomes available, the class notifies the Form by calling that handler with an argument containing the displayable information. The beauty of this approach is that the class is decoupled (not dependent on) the implementation of Form. The MVC and MVVM design patterns are other robust ways of doing it.
Now I'm left with some questions:
- What are the implications of the procedure I used?
- Why isn't it an object-oriented approach?
- What would be the best practice to send information back and forth between classes/forms?
- How would you go about creating the event mentioned by codesparkle?
- I don't know anything about MVC or MVVM design patterns, so some links to a structured explanation would be appreciated.
Please consider that I'm very new to programming and I won't understand you if you talk like I know what I am doing. Code examples work wonders with me, since I can test them.
I thought it could take a turn to an existential debate which wouldn't be apropriate for SO
Also not appropriate for Programmers :) But the question looks fine to me, I really don't see it turning any kind of ugly.First of all I would like you all to know I am an absolute beginner so I might say some things that make no sense, but that's why I am asking, please bare with me.
sentence from your question. You don't have to ask people to be nice, they have to be. If you get an non-constructive comment, flag it. We are all beginners in some way or another.