1
votes

I have two forms Form1 and Form2.
on Form1 button click , I want to open form2 in which yes and no buttons are there in the form2.
When user click on button yes, form1 textbox should display the value in form1's textbox. What i have done is as follows:
On Form1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Alert AlertObj = new Alert();
        string a=AlertObj.Text.Length.ToString();
        string val=Alert.buttonVal();
        AlertObj.Show();

        if (val == "Yes")
            textBox1.Text = val;
        else
            textBox1.Text = "No";

    }
}

on Form 2

 public partial class Alert : Form
{
    public Alert()
    {
        InitializeComponent();
    }
    public static string result = string.Empty;

    private void button1_Click(object sender, EventArgs e)
    {
        result = "Yes";
        Form1 obj = new Form1();

        this.Close();
    }
    public static string buttonVal()
    {

        return result;
    }
}
2
Why not use MessageBox with Yes and No buttons??Shaharyar
actually i am learner and i want to work with multiple forms...what if i have multiple buttons in form2 and i want other then yes or noManish Jain
then see @Alireza's answer. It'll help youShaharyar

2 Answers

1
votes

There are simpler ways to do this. But as you asked:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Alert AlertObj = new Alert();

        if (AlertObj.ShowDialog() == DialogResult.Yes)
            textBox1.Text = AlertObj.ResultText ;
        else
            textBox1.Text = "No";

    }
}


 public partial class Alert : Form
{
    public Alert()
    {
        InitializeComponent();
    }

    public string ResultText {get; set;}

    private void button1_Click(object sender, EventArgs e)
    {
        ResultTest = "Yes";
        DialogResult = DialogResult.Yes;    
    }
}
0
votes

You can do it, by using overloaded constructor, passing it Reference of Form1 TextBox

Form 1 Code:

    private void button1_Click(object sender, EventArgs e)
    {
        Alert AlertObj = new Alert(Ref textBox1);
        AlertObj.ShowDailog();
    }

Form2 Code:

    public partial class Alert : Form
    {
        TextBox txt;
        public Alert()
        {
            InitializeComponent();
        }

        public Alert(Ref TextBox txt1)
        {
            InitializeComponent();
            txt=txt1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            txt.Text ="Yes";
            this.Close();
        }
    }