如何将Form2按钮单击值传递给窗体1

时间:2014-11-16 09:07:49

标签: c#

我有两种形式Form1和Form2 在Form1按钮上单击,我想打开form2,其中form2中没有按钮 当用户单击按钮yes时,form1文本框应显示form1文本框中的值。 我所做的如下:
在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";

    }
}
表格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 个答案:

答案 0 :(得分:1)

有更简单的方法可以做到这一点。但正如你问的那样:

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;    
    }
}

答案 1 :(得分:0)

您可以使用overloaded constructor传递Reference Form1 TextBox

表单1代码:

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

Form2代码:

    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();
        }
    }