【问题标题】:How can I get a textbox text to be public C# forms如何让文本框文本成为公共 C# 表单
【发布时间】:2020-02-29 14:16:40
【问题描述】:

由于某种原因,当我将 int 大小和板数组 int 放入公共类时,它给了我 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
        }

【问题讨论】:

  • 为什么表单一初始化就解析文本框的文本?用户甚至没有机会在文本框中输入任何内容!
  • 当我把它放在其他地方时,这个错误仍然发生“字段初始化程序无法引用非静态字段、方法或属性'Form1.size'”

标签: c# textbox public


【解决方案1】:

创建 Form1 时 Textbox1.Text 未初始化,因此只需将其放入您的 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];
           }
        }

}

【讨论】:

  • 当我把它放在那里时,这个错误仍然发生“字段初始化程序无法引用非静态字段、方法或属性'Form1.size'
  • 不是弹出错误只是第三行的2“size”下面有一条红线
  • 第 4 行包括括号
  • @NatiReitblat 有什么问题?
【解决方案2】:

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

【讨论】:

  • nvm 我想通了 tnx
猜你喜欢
  • 1970-01-01
  • 2015-09-23
  • 2021-05-09
  • 2020-04-13
  • 2014-09-22
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多