【C#】如何根据Winform窗体中的控件名称批量快速获取并清除其中的文本内容?
				
									
					
					
						|  | 
							admin 2025年7月28日 10:4
								本文热度 1307 | 
					
				 
				 :【C#】如何根据Winform窗体中的控件名称批量快速获取并清除其中的文本内容?
:【C#】如何根据Winform窗体中的控件名称批量快速获取并清除其中的文本内容?
我的C# Winform程序中有50个文本控件:txtRoll1、txtRoll2、txtRoll3、、、、、一直到txtRoll50,我需要一次性清空这50个控件值:txtRoll1.Text="";txtRoll2.Text="";、、、,有没有简单的方法,例如用for(int tmpNum=1;tmpNum<51;tmpNum++){}的方式迅速完成这个任务?
 
在C# WinForms中,可以使用循环结合Controls.Find()方法动态查找控件来实现。以下是两种推荐方法:
方法1:直接通过控件名称查找(推荐)
for (int i = 1; i <= 50; i++)
{
    // 构造控件名称
    string controlName = "txtRoll" + i;
    
    // 在窗体控件集合中查找(包含所有子容器)
    Control[] foundControls = this.Controls.Find(controlName, true);
    
    // 如果找到且是文本框,则清空内容
    if (foundControls.Length > 0 && foundControls[0] is TextBox)
    {
        (foundControls[0] as TextBox).Text = string.Empty;
    }
}
方法2:预先存储控件到数组(高效,适合频繁操作)
// 在窗体类中声明文本框数组
private TextBox[] txtRolls;
// 在Form_Load中初始化数组
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;
    }
}
关键说明:
Controls.Find()参数:
错误处理:实际项目中建议添加异常处理
性能:
设计建议:
// 可在设计器代码中初始化(替代手动创建50次)
private void InitializeRollTextboxes()
{
    for (int i = 1; i <= 50; i++)
    {
        var txt = new TextBox { Name = "txtRoll" + i };
        // 设置位置等属性...
        this.Controls.Add(txt);
    }
}
注意事项:
根据实际需求选择方法,对于50个控件量级,两种方法性能差异可忽略不计。
批量快速读取控件值方法如下:
string tmpName = "";
int tmpRoll = 0;
for (int i = 1; i <= 9; i++)
{
    // 构造控件名称
    string controlName0 = "txtName" + i;
    string controlName1 = "txtRoll" + i;
    // 在窗体控件集合中查找(包含所有子容器)
    Control[] foundControls0 = this.Controls.Find(controlName0, true);
    // 如果找到且是文本框,则获取内容
    if (foundControls0.Length > 0 && foundControls0[0] is TextBox)
    {
        tmpName=foundControls0[0].Text;
    }
    // 在窗体控件集合中查找(包含所有子容器)
    Control[] foundControls1 = this.Controls.Find(controlName1, true);
    // 如果找到且是数字框,则获取内容
    if (foundControls1.Length > 0 && foundControls1[0] is NumericUpDown)
    {
        tmpRoll = Convert.ToInt32(foundControls1[0].Text);
    }
}
该文章在 2025/7/28 15:16:26 编辑过