elie mardelly elie mardelly - 2 months ago 13
C# Question

how to pass string or value from usercontrol to main form in C#

I created a usercontrol that contains many buttons and in the main form I have a textbox.
I add the usercontrol to the main form and I want to click any button on the usercontrol and have the textbox in the main form shows the button text.
The question is how to pass the string of the button in usercontrol to the textbox in the main form? This is what I'm trying to do

public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();

}
public string a ;




private void button1_Click(object sender, EventArgs e)
{
a = button1.Text;
}

private void button2_Click(object sender, EventArgs e)
{
a = button2.Text;
}

private void button3_Click(object sender, EventArgs e)
{
a = button3.Text;


}


and the main form code is :

private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = usrCtrl.a;
// usrCtrl come from : Usercontrol1 usrCtrl = new Usercontrol1();
}


and it shows nothing in the textbox.

Answer

refer to this answer, you need to create a property changed event.

UserControl.cs class;

public partial class UserControl1 : UserControl
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public UserControl1()
        {
            InitializeComponent();
        }

        private string stringA;

        public string a
        {
            get { return stringA; }
            set
            {
                if (value != stringA)
                {
                    stringA = value;
                    if (PropertyChanged!= null)
                    {
                       PropertyChanged(this, new PropertyChangedEventArgs(a));
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            a = button1.Text;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            a = button2.Text;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            a = button3.Text;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            a = button4.Text;
        }
    }

On Form's Load we need to define the event,

 private void Form1_Load(object sender, EventArgs e)
        {
            cntr.PropertyChanged += Cntr_PropertyChanged; // press tab + tab after += and it will generate the following method automatically.
        }

Here is Event;

 private void Cntr_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            textBox1.Text = cntr.a.ToString(); //cntr is the instance of UserControl1

        }

Hope helps,