Pass data between different UserControls

2

I have the following schema mounted in Visual Studio (C # .net)

The idea is to be able to bring the data from the Textbox to the UserControl2. I have tried instantiating UserControl1 and changing the level of protection of the Textbox to public, from the object I can access the Textbox.Text but it brings it to me empty.

private void button1_Click(object sender, EventArgs e)
{
    Config Example = new Config();
    MessageBox.Show(Example.textBox1.Text);
}

How could I pass the data?

    
asked by Omar 02.08.2018 в 19:26
source

1 answer

1

Maybe the problem you have is that instances the UserControl but you do not allow time for the user to interact with it and when you ask for the value of the text, it is empty.

The way I saw to solve your problem is creating a property in the UserControl that carries the textbox called EditText through which you can access the text of the textbox, as well as change it , anyway if you will then work specifically with other properties of textbox you can change the access to it as you did above. Then in the other UserControl create an event called ClickBtn with which I can assign an operation when the button is pressed. Here is the code:

UserControl1 (The one in the textbox)

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

    public string EditText
    {
        get { return textBox1.Text; }
        set { textBox1.Text = value; }
    }
}

UserControl2 (The one with the button)

public partial class UserControl2 : UserControl
{
    public UserControl2()
    {
        InitializeComponent();
        ClickBtn += UserControl2_ClickBtn;
    }

    private void UserControl2_ClickBtn(object sender, EventArgs e)
    {

    }

    public event EventHandler ClickBtn;

    private void button1_Click(object sender, EventArgs e)
    {
        ClickBtn.Invoke(sender, e);
    }
}

In the form of my app I have this code

private void userControl21_ClickBtn(object sender, EventArgs e)
{
    MessageBox.Show(userControl1.EditText);
}

Here is an image of how it works:

    
answered by 02.08.2018 / 20:21
source