-1

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?

Behnam
  • 1,039
  • 2
  • 14
  • 39

2 Answers2

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
  • 1
    Although 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