C# 如何从文本框中获取值,将其放入字符串中,当我单击两个按钮时,它会显示(有点像一个全局的?)C

C# 如何从文本框中获取值,将其放入字符串中,当我单击两个按钮时,它会显示(有点像一个全局的?)C,c#,textbox,C#,Textbox,我想将文本框中的值转换为字符串,然后在单击按钮时将其用作字符串。我不想让它在我的按钮点击,因为我必须使用它对其他按钮以及。 比如: public partial class Form1 : Form { public Form1() { InitializeComponent(); } string ab = textBox1.Text; private void button1_Click(object sender, EventArgs

我想将文本框中的值转换为字符串,然后在单击按钮时将其用作字符串。我不想让它在我的按钮点击,因为我必须使用它对其他按钮以及。 比如:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    string ab = textBox1.Text;
    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(ab);
    }       

}
编辑1:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string ab = textBox1.Text;
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(ab);
        }     
        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show(ab+" Hello");
        }

可以使用私有方法来实现这一点

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

    // Will return string on textBox1 uppon calling
     private string ab(){
       return textBox1.Text;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(ab());
    }     
    private void button2_Click(object sender, EventArgs e)
    {
        MessageBox.Show(ab()+" Hello");
    }
}

您需要相同的按钮单击事件才能与多个按钮一起使用?您是否尝试过创建ab属性或创建返回文本的方法?。。