I have a Mdiparent form containing a button and some child forms. How is it possible to change backcolor of all textboxes in all child forms when clicking the button in parent form?
Asked
Active
Viewed 2,265 times
-1
-
Make all text boxes public in child form and access it by calling the child form from parent. – Irshad Dec 02 '15 at 11:59
-
I should call every text boxes seprately? – Behnam Dec 02 '15 at 12:00
-
Write a method in child form and call it. Then no need to set `public` modifier for textboxes. – Irshad Dec 02 '15 at 12:04
-
Could you please write required button_click event code. Or any nessessary code in child forms? – Behnam Dec 02 '15 at 12:08
2 Answers
2
i know answer is already given.. but i would go with event and delegates.. multicast delegate is best choice is here so here is my solution.
namespace winMultiCastDelegate
{
public partial class Form1 : Form
{
public delegate void ChangeBackColorDelegate(Color backgroundColor);
//just avoid null check instanciate it with fake delegate.
public event ChangeBackColorDelegate ChangeBackColor = delegate { };
public Form1()
{
InitializeComponent();
//instanciate child form for N time.. just to simulate
for (int i = 0; i < 3; i++)
{
var childForm = new ChildForm();
//subscribe parent event
this.ChangeBackColor += childForm.ChangeColor;
//show every form
childForm.Show();
}
}
private void button1_Click(object sender, EventArgs e)
{
ChangeBackColor.Invoke(Color.Black);
}
}
/// <summary>
/// child form class having text box inside
/// </summary>
public class ChildForm : Form
{
private TextBox textBox;
public ChildForm()
{
textBox = new TextBox();
textBox.Width = 200;
this.Controls.Add(textBox);
}
public void ChangeColor(Color color)
{
textBox.BackColor = color;
}
}
}

sm.abdullah
- 1,777
- 1
- 17
- 34
1
This the ChilForm
;
public ChilForm()
{
InitializeComponent();
}
public void ChangeTextboxColor()
{
textBox1.BackColor = Color.Yellow;
}
And this is Parent
;
ChilForm frm = new ChilForm();
public Parent()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Shows the child
frm.Show();
}
private void button2_Click(object sender, EventArgs e)
{
//Changes color
frm.ChangeTextboxColor();
}

Irshad
- 3,071
- 5
- 30
- 51
-
1Although this will work it would require you to instantiate all child forms and call their methods independently. An alternative to this would be to use the observable pattern or at very least use events. – Stephen Brickner Dec 02 '15 at 12:17