如何获取文本框文本以成为公共C#表单

问题描述 投票:0回答:2

出于某种原因,当我将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
        }
c# textbox public
2个回答
2
投票

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.