-1

How to access a textBox in form1 when I click a button from form2?

I want to write a specific text in textBox in form1 after I click a button from form2 and it closes itself.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
BJJ
  • 21
  • 1
    Totally unclear what you are asking. Provide some code which explains it. – VP. Jul 14 '15 at 14:26
  • possible duplicate of [Best way to access a control on another form in Windows Forms?](http://stackoverflow.com/questions/8566/best-way-to-access-a-control-on-another-form-in-windows-forms) – Bernd Linde Jul 14 '15 at 14:26
  • possible duplicate of [Passing values between two windows forms](http://stackoverflow.com/questions/3227016/passing-values-between-two-windows-forms) – Equalsk Jul 14 '15 at 14:28

1 Answers1

1

As I guessed you can solve your issue as

Form1.cs

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        LaunchForm2();
    }
    private void LaunchForm2()
    {
        using (var form2 = new Form2())
        {
            form2.OnTextEnteredHandler += Form2_OnTextEnteredHandler;
            form2.ShowDialog();
        }
    }

    private void Form2_OnTextEnteredHandler(string text)
    {
        //This event will be fire when you click on button on form2
        textBox1.Text = text;
    }
}

Form2.cs

public partial class Form2 : Form
{
    public delegate void TextEnteredHandler(string text);
    public event TextEnteredHandler OnTextEnteredHandler;
    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (OnTextEnteredHandler != null)
        {
            OnTextEnteredHandler(textBox1.Text);
            Close();
        }
    }
}

You need to be add textbox in form 2 as well, put text into it from form 2 then click button as shown in code.

NASSER
  • 5,900
  • 7
  • 38
  • 57