user2014987
user2014987

Reputation: 23

C# - How to Transfer Information Between User Control

im doing an application where user enter a value inside the text box then he press a button, both in the same user control. Then the result from the text box will show at the label of other user control. Both of the user control is in the same windows form.

Thanks!

Image of user interface

enter image description here

Upvotes: 2

Views: 4578

Answers (2)

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

try this:

public class FirstUserControl:UserControl
{
    Public event EventHandler MyEvent;

    //Public property in your first usercontrol
    public string MyText
    {
        get{return this.textbox1.Text;} //textbox1 is the name of your textbox
    }

    private void MyButton_Clicked(/* args */)
    {
        if (MyEvent!=null)
        {
            MyEvent(null, null);
        }
    }
    //other codes
}


public class SecondUserControl:UserControl
{
    //Public property in your first usercontrol
    public string MyText
    {
        set{this.label1.Text = value;} //label1 is the name of your label
    }

    //other codes
}

then in your MainForm:

public class MainForm:Forms
{
    //Add two instance of the UserControls

    public MainForm()
    {
        this.firstUserControl.MyEvent += MainWindow_myevent;
    }

    void MainWindow_myevent(object sender, EventArgs e)
    {
        this.secondUserControl.MyText = this.firstUserControl.MyText;
    }

    //other codes
}

Upvotes: 1

lc.
lc.

Reputation: 116498

The most common way to do this is use an event. This is how I would do it:

First define an EventArgs:

public class MyEventArgs : EventArgs
{
    public string Text { get; private set; }

    public MyEventArgs(string Text)
    {
        this.Text = Text;
    }
}

Then in your UserControl (the one with the button):

public partial class MyUserControl
{
    public event EventHandler<MyEventArgs> ButtonClicked;

    public MyUserControl()
    {
        //...

        button1.Click += (o, e) => OnButtonClicked(new MyEventArgs(textBox1.Text));
    }

    protected virtual void OnButtonClicked(MyEventArgs args)
    {
        var hand = ButtonClicked;
        if(hand != null) ButtonClicked(this, args);
    }
}

Then subscribe to your MyUserControl.ButtonClicked event in the form and call a method in the second control.


Note if the behavior of the button and the text in the textbox are actually not related, you can use a property to get the text entered and an empty EventArgs for your event instead.

P.S. The names MyEventArgs, MyUserControl, and ButtonClicked are just for demonstration purposes. I encourage you to use more descriptive/relevant naming in your code.

Upvotes: 3

Related Questions