[英]How can I get a textbox text to be public C# forms
For some reason when I put the int size and the board array int the public class it gives me 2 errors: the first one is:由于某种原因,当我将 int 大小和板数组 int public class 它给了我2个错误:第一个是:
a field initializer cannot reference the non-static field, method, or property 'Form1.textBox1'字段初始值设定项不能引用非静态字段、方法或属性“Form1.textBox1”
and the second one:第二个:
a field initializer cannot reference the non-static field, method, or property 'Form1.size'字段初始值设定项不能引用非静态字段、方法或属性“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
}
Textbox1.Text is not initialized when Form1 is creating, so just put this in your Form Load event:创建 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];
}
}
}
As pointed out you were initially attempting to initialise your size value before the text box had even been created.正如所指出的,您最初试图在创建文本框之前初始化您的大小值。 As you are reliant on user input to give you TextBox1.Text, I would suggest that you perform your Button[,] array initialization on your TextBox1 text entry event, even if you specify a default value for instance creation eg board = new Button(1,1) in the form constructor;由于您依赖用户输入来为您提供 TextBox1.Text,因此我建议您在 TextBox1 文本输入事件上执行 Button[,] 数组初始化,即使您为实例创建指定了默认值,例如 board = new Button( 1,1) 在表单构造函数中;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.