You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过循环遍历表单中指定TextBox控件并将其值乘2

用循环批量处理指定TextBox控件的方案

核心思路是先把需要处理的控件编号(3、6、8、9)存入一个集合,遍历这个集合时通过控件名称定位到目标TextBox,再完成数值翻倍操作。以下是几种常见开发场景的实现代码:

场景1:VBA(Access/Excel表单)

通过窗体的Controls集合按名称获取控件,同时增加类型和数值有效性判断:

Dim targetNums As Variant
Dim num As Variant
Dim txtBox As Control

targetNums = Array(3, 6, 8, 9) ' 要处理的控件编号

For Each num In targetNums
    Set txtBox = Me.Controls("txt" & num)
    ' 确保是TextBox控件且内容为有效数值
    If TypeOf txtBox Is TextBox And IsNumeric(txtBox.Value) Then
        txtBox.Value = txtBox.Value * 2
    End If
Next num

场景2:C# WinForms

使用Controls.Find方法查找控件,第二个参数设为true可递归查找子容器内的控件:

int[] targetNums = { 3, 6, 8, 9 };

foreach (int num in targetNums)
{
    string controlName = $"txt{num}";
    TextBox txtBox = this.Controls.Find(controlName, true).FirstOrDefault() as TextBox;
    
    if (txtBox != null && double.TryParse(txtBox.Text, out double value))
    {
        txtBox.Text = (value * 2).ToString();
    }
}

场景3:VB.NET WinForms

逻辑与VBA类似,结合Controls.Find实现批量处理:

Dim targetNums() As Integer = {3, 6, 8, 9}

For Each num As Integer In targetNums
    Dim controlName As String = $"txt{num}"
    Dim txtBox As TextBox = Me.Controls.Find(controlName, True).FirstOrDefault()
    
    If txtBox IsNot Nothing AndAlso Double.TryParse(txtBox.Text, Dim value As Double) Then
        txtBox.Text = (value * 2).ToString()
    End If
Next

后续如需调整处理的控件,只需修改targetNums集合内的编号即可,无需改动循环逻辑,维护性更强。

内容的提问来源于stack exchange,提问作者k1dr0ck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 18:35:49