VB.NET中如何通过拼接控件名称与变量值结合With语句修改TextBox控件属性?
解决VB.NET中With语句访问TextBox专属属性的问题
这个问题的核心原因很清晰:Controls("txt" & Number)返回的是Control基类对象,而非TextBox类型。Control类只包含所有控件通用的属性(比如ForeColor、BorderStyle),但像ReadOnly这种TextBox专属的属性,无法直接通过Control对象访问——这就是你看到部分属性生效、部分失效的根本原因。
下面给你两种可靠的解决方案:
方案1:直接类型转换后使用With语句
先把Controls返回的Control对象转换成TextBox类型,再用With语句操作:
' 用DirectCast做类型转换,效率更高(已知目标控件是TextBox时推荐) Dim targetTextBox As TextBox = DirectCast(Me.Controls("txt" & Number), TextBox) With targetTextBox .ForeColor = Color.White .ReadOnly = True .BorderStyle = BorderStyle.None End With
或者用CType(更灵活,支持隐式转换场景):
Dim targetTextBox As TextBox = CType(Me.Controls("txt" & Number), TextBox) With targetTextBox .ForeColor = Color.White .ReadOnly = True .BorderStyle = BorderStyle.None End With
方案2:添加类型检查,避免运行时错误
如果不确定"txt" & Number对应的控件是否存在,或者是否确实是TextBox类型,可以先做判断,防止空引用或类型转换异常:
Dim targetControl As Control = Me.Controls("txt" & Number) ' 先检查控件存在且是TextBox类型 If targetControl IsNot Nothing AndAlso TypeOf targetControl Is TextBox Then Dim targetTextBox As TextBox = CType(targetControl, TextBox) With targetTextBox .ForeColor = Color.White .ReadOnly = True .BorderStyle = BorderStyle.None End With End If
额外提醒
- 确保
Number变量的值准确对应控件名称的后缀(比如0、10这类目标控件的编号),否则Controls("txt" & Number)会返回Nothing,触发空引用错误。 - 如果目标TextBox放在Panel、GroupBox这类容器控件内,不能直接用
Me.Controls,要改成对应容器的Controls集合,比如Panel1.Controls("txt" & Number)。
内容的提问来源于stack exchange,提问作者aandre4321
相关产品推荐
相关产品推荐

