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

How do I get a value from a Textbox, put it in a string, and when i click 2 buttons, it shows (kinda like a global?) C#

我想将 TextBox 中的值转换为字符串,然后在单击按钮时将其用作字符串。我不想将它放在我的 Button click 中,因为我也必须在其他按钮上使用它。 类似于:

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