如何使文本框文本成为公共C#表单

由于某种原因,当我将int大小和board数组放入public类时,它给了我2条错误: 第一个是:

  

字段初始化程序无法引用非静态字段,方法或属性'Form1.textBox1'

和第二个:

  

字段初始化器无法引用非静态字段,方法或属性'Form1.size'

public partial class Form1 : Form
    {
        int size = int.Parse(Textbox1.Text)
        Button[,] board = new Button[size,size];
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender,EventArgs e)
        {
            random code that needs the board array
        }
        private void Form1_Click(object sender,EventArgs e)
        {
           other random code that need the board array
        }
heartear15 回答:如何使文本框文本成为公共C#表单

Textbox1.Text在创建Form1时未初始化,因此只需将其放入您的Form Load事件中即可:

public partial class Form1 : Form
{
        int size = 0;
        Button[,] board;
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender,EventArgs e)
        {
           // random code that needs the board array
        }
        private void Form1_Click(object sender,EventArgs e)
        {
          // other random code that need the board array
        }
        private void Form1_Load(object sender,EventArgs e)
        {
           if (!string.IsNullOrEmpty(Textbox1.Text))
           {
            size = int.Parse(Textbox1.Text);
            board = new Button[size,size];
           }
        }

}
,

如前所述,您最初试图在创建文本框之前初始化大小值。 由于您依赖用户输入来提供TextBox1.Text,因此即使您为实例创建指定了默认值,例如,建议您对TextBox1文本输入事件执行Button [,]数组初始化。 board =表单构造函数中的新Button(1,1);

本文链接:https://www.f2er.com/3167901.html

大家都在问