方法1:直接通過控件名稱查找(推薦)
for (int i = 1; i <= 50; i++)
{
// 構(gòu)造控件名稱
string controlName = "txtRoll" + i;
// 在窗體控件集合中查找(包含所有子容器)
Control[] foundControls = this.Controls.Find(controlName, true);
// 如果找到且是文本框,則清空內(nèi)容
if (foundControls.Length > 0 && foundControls[0] is TextBox)
{
(foundControls[0] as TextBox).Text = string.Empty;
}
}
方法2:預(yù)先存儲(chǔ)控件到數(shù)組(高效,適合頻繁操作)
// 在窗體類中聲明文本框數(shù)組
private TextBox[] txtRolls;
// 在Form_Load中初始化數(shù)組
private void Form1_Load(object sender, EventArgs e)
{
txtRolls = new TextBox[50];
for (int i = 1; i <= 50; i++)
{
txtRolls[i-1] = this.Controls.Find("txtRoll" + i, true)[0] as TextBox;
}
}
// 清空所有文本框
private void ClearTextBoxes()
{
foreach (var txt in txtRolls)
{
txt.Text = string.Empty;
}
}
關(guān)鍵說明:
Controls.Find()
參數(shù):
錯(cuò)誤處理:實(shí)際項(xiàng)目中建議添加異常處理
性能:
設(shè)計(jì)建議:
// 可在設(shè)計(jì)器代碼中初始化(替代手動(dòng)創(chuàng)建50次)
private void InitializeRollTextboxes()
{
for (int i = 1; i <= 50; i++)
{
var txt = new TextBox { Name = "txtRoll" + i };
// 設(shè)置位置等屬性...
this.Controls.Add(txt);
}
}
注意事項(xiàng):
確保控件名稱嚴(yán)格匹配(無拼寫錯(cuò)誤)
如果文本框嵌套在容器中,必須使用searchAllChildren: true
大型項(xiàng)目建議使用MVVM模式或數(shù)據(jù)綁定替代直接操作控件
根據(jù)實(shí)際需求選擇方法,對(duì)于50個(gè)控件量級(jí),兩種方法性能差異可忽略不計(jì)。
批量快速讀取控件值方法如下:
string tmpName = "";
int tmpRoll = 0;
for (int i = 1; i <= 9; i++)
{
// 構(gòu)造控件名稱
string controlName0 = "txtName" + i;
string controlName1 = "txtRoll" + i;
// 在窗體控件集合中查找(包含所有子容器)
Control[] foundControls0 = this.Controls.Find(controlName0, true);
// 如果找到且是文本框,則獲取內(nèi)容
if (foundControls0.Length > 0 && foundControls0[0] is TextBox)
{
tmpName=foundControls0[0].Text;
}
// 在窗體控件集合中查找(包含所有子容器)
Control[] foundControls1 = this.Controls.Find(controlName1, true);
// 如果找到且是數(shù)字框,則獲取內(nèi)容
if (foundControls1.Length > 0 && foundControls1[0] is NumericUpDown)
{
tmpRoll = Convert.ToInt32(foundControls1[0].Text);
}
}