如何在 C# 中定义文本框数组
本文关键字:文本 数组 定义 | 更新日期: 2023-09-27 18:35:36
嗨,当我在Windows应用程序表单上创建文本框时,我无法将其命名为box[0],box[1]等。我想这样做的目的是因为我想在循环中使用它们。
其实我发现TextBox[] array = { firstTextBox, secondTextBox };
也有效!
创建它们后如何列出它们? 在表单初始化函数中,您可以执行以下操作:
List<TextBox> myTextboxList = new List<TextBox>();
myTextBoxList.Add(TextBox1);
myTextBoxList.Add(TextBox2);
mytextBoxList.Add(TextBox3);
现在,您可以使用如下所示的"myTextboxList"进行迭代:
Foreach (TextBox singleItem in myTextboxList) {
// Do something to your textboxes here, for example:
singleItem.Text = "Type in Entry Here";
}
您可以在运行时创建文本框并将它们放在数组中...
如果要在设计时执行此操作,则必须对整个this.Controls
数组执行一些控制筛选逻辑,以便仅访问所需的文本框。请考虑if (currControl is TextBox)
表单中的所有文本框是否都是数组中所需的文本框。
设计时的另一个选项是将所有需要的文本框放在一个面板上,该面板将成为其父级,然后循环访问面板的子项(控件)并将它们强制转换为 TextBox。
运行时解决方案如下所示:
var arr = new TextBox[10];
for (var i = 0; i < 10; i++)
{
var tbox = new TextBox();
// tbox.Text = i.ToString();
// Other properties sets for tbox
this.Controls.Add(tbox);
arr[i] = tbox;
}
我个人不会为此使用数组。 我会使用某种形式的通用集合,如 List。
List<TextBox> textBoxList = new List<TextBox>();
//Example insert method
public void InsertTextBox(TextBox tb)
{
textBoxList.Add(tb);
}
//Example contains method
public bool CheckIfTextBoxExists(TextBox tb)
{
if (textBoxList.Contains(tb))
return true;
else
return false;
}
您不一定必须使用 Contains 方法,您也可以使用 Any(),甚至可能找到另一种方式 - 这一切都取决于您在做什么。 我只是认为在这种情况下使用泛型集合比简单的数组具有更大的灵活性。
对于C#
,只需使用它来创建文本框数组
public Text [] "YourName" = new Text ["how long you want the array"];
然后将文本框分别添加到数组中。
使用 C# 的文本框数组
// Declaring array of TextBox
private System.Windows.Forms.TextBox[] txtArray;
private void AddControls(int cNumber)
{
// assign number of controls
txtArray = new System.Windows.Forms.TextBox[cNumber + 1];
for (int i = 0; i < cNumber + 1; i++)
{
// Initialize one variable
txtArray[i] = new System.Windows.Forms.TextBox();
}
}
TextBox[] t = new TextBox[10];
for(int i=0;i<required;i++)
{
t[i]=new TextBox();
this.Controls.Add(t[]);
}