如何将TextBox控件名设为变量并循环操作TextBox1至TextBox20
Fixing Your TextBox Loop Issue
First, let's break down the problems in your current code:
- You’re using variable
Ybut never assigning it a value (it defaults to 0), and you should be using your loop variableIinstead to target TextBox1 through TextBox20. Xis just a string holding the control name, not the actual TextBox control itself. You can’t access a.Valueproperty on a string—you need to reference the real control on your form.
Here’s the corrected code that will clear the text of TextBox1 to TextBox20, depending on your environment:
For VB.NET (WinForms)
Dim I As Integer For I = 1 To 20 ' Find the TextBox control by its name Dim targetTextBox As TextBox = Me.Controls.Find($"TextBox{I}", True).FirstOrDefault() ' Only modify the control if it exists (avoids runtime errors) If targetTextBox IsNot Nothing Then targetTextBox.Text = "" ' TextBoxes use .Text for their content in VB.NET End If Next I
Key Details:
Me.Controls.Find($"TextBox{I}", True)searches your form’s controls (including child controls, thanks to theTrueflag) for the matching TextBox name..FirstOrDefault()safely returns the control if found, orNothingif it doesn’t exist—this prevents crashes if a TextBox is missing from your form.
For VBA (Excel/Access)
If you’re working in VBA, the syntax is a bit simpler since TextBoxes use .Value directly:
Dim I As Integer For I = 1 To 20 ' Skip errors if the control doesn't exist On Error Resume Next Me.Controls("TextBox" & I).Value = "" On Error GoTo 0 Next I
内容的提问来源于stack exchange,提问作者temesgen-g
相关产品推荐
相关产品推荐

