我目前有一个表格,我动态创建了一个文本框,按钮等的2D数组。我刚发现我的程序的其他部分无法访问我创建的文本框?我有办法做到吗?
我的代码类似于:
public Form1()
{
int column = 4;
System.Windows.Forms.TextBox[,] textbox = new System.Windows.Forms.TextBox[column, row];
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
textbox[i, j] = new System.Windows.Forms.TextBox();
textbox[i, j].Size = new Size(80, 20);
textbox[i, j].Name = "textbox_" + i + "_" + j;
textbox[i, j].Location = new System.Drawing.Point((i * 80) + 20, (j * 20) + 30);
textbox[i, j].Visible = true;
Controls.Add(textbox[i, j]);
}
}
/////fill the textboxes with data//////
}
我无法访问方法外的文本框,我该怎么办?你能提供一些有效的编码吗?我对c#还是比较新的,非常感谢你
答案 0 :(得分:0)
您可以添加类级别属性,就像
一样public class Form1
{
public System.Windows.Forms.TextBox[,] textbox { get; set; }
public Form1()
{
int column = 4;
textbox = new System.Windows.Forms.TextBox[column, row];
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
textbox[i, j] = new System.Windows.Forms.TextBox();
textbox[i, j].Size = new Size(80, 20);
textbox[i, j].Name = "textbox_" + i + "_" + j;
textbox[i, j].Location = new System.Drawing.Point((i * 80) + 20, (j * 20) + 30);
textbox[i, j].Visible = true;
Controls.Add(textbox[i, j]);
}
}
}
}
然后你可以简单地做
Form1 myForm = GetMyForm();
System.Windows.Forms.TextBox[,] theTextboxArray = myForm.textbox;
答案 1 :(得分:0)
当然,您无法使用textbox_i_j
访问它们,其中i&amp; j是具有智能感知的数字,因为它不受支持,但你可以像这样得到它们
TextBox GetTB(string name)
{
return ( Controls.FindControl(name) as TextBox );
}
答案 2 :(得分:0)
Declare int column = 4;
System.Windows.Forms.TextBox[,] textbox = new System.Windows.Forms.TextBox[column, row];
Form1构造函数之外。您的代码应如下所示:
int column = 4;
System.Windows.Forms.TextBox[,] textbox;
public Form1()
{
textbox = new System.Windows.Forms.TextBox[column, row];
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
textbox[i, j] = new System.Windows.Forms.TextBox();
textbox[i, j].Size = new Size(80, 20);
textbox[i, j].Name = "textbox_" + i + "_" + j;
textbox[i, j].Location = new System.Drawing.Point((i * 80) + 20, (j * 20) + 30);
textbox[i, j].Visible = true;
Controls.Add(textbox[i, j]);
}
}
/////fill the textboxes with data//////
}
答案 3 :(得分:0)
我在网上搜索答案,而我等待一些聪明人回答我的问题。我使用字典来检索文本框,如下所示:
Get a Windows Forms control by name in C#
//声明
Dictionary <String, System.Windows.Forms.TextBox> dictionaryTextBox = new Dictionary<string, System.Windows.Forms.TextBox>();
//创建数组
System.Windows.Forms.TextBox[,] textbox = new System.Windows.Forms.TextBox[column, row];
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
textbox[i, j] = new System.Windows.Forms.TextBox();
textbox[i, j].Size = new Size(80, 20);
textbox[i, j].Name = "textbox_" + i + "_" + j;
textbox[i, j].Location = new System.Drawing.Point((i * 80) + 20, (j * 20) + 30);
textbox[i, j].Visible = true;
Controls.Add(textbox[i, j]);
//new added
dictionaryTextBox.Add (textbox[i, j].Name, textbox[i, j]);
}
}
//检索
System.Windows.Forms.TextBox retrieve = dictionaryTextBox["textbox_3_3"];
retrieve.Text = "apple";