Hadi Hafidzi
Hadi Hafidzi

Reputation: 13

C# - How to allow one user control to change the label in other user control within a windows form?

I have a windows form named MainForm.cs and two user controls which are UserControlRed.cs and UserControlBlue.cs respectively. An object of UserControlRed that is ucr is created and added into panel1 in MainForm by using panel1.Controls.Add(ucr); in default constructor of MainForm.

Then I have the UI like this: MainForm

enter image description here

Note: instance of UserControlBlue that is ucb is created using the click button event in UserControlRed. Code as follows:

private void CreateUCBbtn_Click(object sender, EventArgs e)
{
     MainForm f1 = new MainForm();
     f1 = (MainForm)this.Parent.Parent;
     f1.AddUCBlueIntoPanel2();
}

Now, what I want to do is after user click the 'Change UCB Label' button, the label in UserControlBlue will change accordingly to what has been entered in textbox in UserControlRed. So, I have two questions here:

  1. Regarding my Note above, is it safe to do it like this?
  2. What is the best way for me to pass the value in the textbox from UserControlRed into the label in UserControlBlue?

Another note: I'm still new in OOP and especially C# and winforms. Maybe anyone can suggest me a good site to familiar with?

Upvotes: 1

Views: 3217

Answers (2)

Michael Schnerring
Michael Schnerring

Reputation: 3661

For the sake of the single responsibility principle, this'd be smelly code. The parent of both should know the logic of how to fill its panels. The red and blue panel should only know how to trigger certain actions on its parent, but the actual implementation is stored in the logic of the parent.

As it is right now, the red panel implements logic which does not depend on the red panel itsself.

private void CreateUCBbtn_Click(object sender, EventArgs e)
{
     var textBoxContent = this.MyTextBox.Text;
     var parent = this.Parent as MainForm;
     parent.AddBlueIntoPanel2(textBoxContent);
}

Upvotes: 0

xpda
xpda

Reputation: 15813

You can add a public method (function) in UserControlBlue that accepts a string as a parameter and assigns it to the label's text. Then you can call that method from the "Change UCB Label" button click handler.

It should be safe to do this.

Upvotes: 2

Related Questions