-2

I have a TextBox (let's call it textBox1) inside Form1. When the user presses "New" to clear the screen, after accepting that their work will be lost (from within Form2), how do I make textBox1 clear? I can't access it directly from the second form and I can't think of a feasible way to do this.

Thanks in advance for the help!

Renerrix
  • 17
  • 4
  • 1
    Pass it to the other form. Use google for these types of simple questions. You will find many questions like this. – deathismyfriend Jun 14 '15 at 04:27
  • just make the text box public, by default they are private, go to textbox properties and edit modifier property to public – bto.rdz Jun 14 '15 at 04:40
  • @bto.rdz you also will need to store the current instance of form. Moreover, it is not correct. Next time, you want to use the same dialog in an another window, are you going to make another form instead of reusing the same? – Yeldar Kurmangaliyev Jun 14 '15 at 04:56

1 Answers1

1

Add a public flag of success in a Form2 and check it afterwards. Or you can use built-in functionality of ShowDialog and DialogResult. It is more proper in terms of OOP and logic than changing the value of Form1 from a Form2.

If you change the value of hardcoded form then you will be unable to reuse this form again.

With this approach you can reuse this form again in any place. Using simple custom variable:

public class Form2 : Form
{
    public bool Result { get; set; }

    public void ButtonYes_Click(object sender, EventArgs e)
    {
        Result = true;
        this.Close();
    }

    public void ButtonNo_Click(object sender, EventArgs e)
    {
        Result = false;
        this.Close();
    }
}

public class Form1 : Form 
{
    public void Button1_Click(object sender, EventArgs e)
    {
        using (Form2 form = new Form2())
        {
             form.ShowDialog();
             if (form.Result) TextBox1.Text = String.Empty;   
        }
    }
}

Using DialogResult or ShowDialog:

public class Form2 : Form
{
    public void ButtonYes_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.Yes;
        this.Close();
    }

    public void ButtonNo_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.No;
        this.Close();
    }
}

public class Form1 : Form 
{
    public void Button1_Click(object sender, EventArgs e)
    {
        using (Form2 form = new Form2())
        {
            var result = form.ShowDialog();
            if (result == DialogResult.Yes) TextBox1.Text = String.Empty;   
        }
    }
}

It also a good idea to use using as form is not disposed after ShowDialog.
It makes disposing deterministic. This way you can ensure it is disposed right after you stopped using it.

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101