VB.NET用GetType.GetProperties设置WinForm控件属性报错及需求咨询
问题解决方案
1. 原有代码报错原因
- 类型不匹配:
SetValue方法传入的是字符串"Transparent",但BackColor属性实际需要System.Drawing.Color类型的枚举值,类型不一致直接触发运行时异常。 - 控件限制:原生WinForms的TextBox默认不支持透明背景,即使传入
Color.Transparent也会抛出参数无效错误,需要先将TextBox设置为ReadOnly = True、BorderStyle = BorderStyle.None之后才允许设置透明背景。如果不需要透明效果,可以直接替换为其他合法Color值验证逻辑。
2. 更简洁的属性赋值方案(无需反射)
不需要调用反射方法获取属性,直接对控件做类型转换即可访问对应属性,代码可读性和性能更高:
Private Sub Read_csv_file_itextbox_Load_1(sender As Object, e As EventArgs) Handles MyBase.Load For Each c As Control In Me.Controls If TypeOf c Is TextBox Then Dim tb As TextBox = CType(c, TextBox) ' 若需要设置透明背景,先开启以下两个配置 ' tb.ReadOnly = True ' tb.BorderStyle = BorderStyle.None tb.BackColor = Color.LightGray ' 替换为实际需要的颜色值即可 End If Next End Sub
3. 偶数索引TextBox单独处理实现
针对命名规则为TextBox1、TextBox2、TextBox3……的控件,提取索引后筛选偶数执行对应操作的代码如下:
Private Sub Read_csv_file_itextbox_Load_1(sender As Object, e As EventArgs) Handles MyBase.Load Const NAME_PREFIX As String = "TextBox" For Each c As Control In Me.Controls If TypeOf c Is TextBox Then Dim tb As TextBox = CType(c, TextBox) ' 筛选符合命名规则的控件 If tb.Name.StartsWith(NAME_PREFIX) Then ' 提取序号部分并转换为整数 Dim indexStr = tb.Name.Substring(NAME_PREFIX.Length) Dim index As Integer If Integer.TryParse(indexStr, index) Then ' 判断是否为偶数索引,若需要从0开始计数可自行调整判断逻辑 If index Mod 2 = 0 Then ' 此处执行自定义属性设置逻辑 tb.BackColor = Color.LightBlue tb.Font = New Font(tb.Font.FontFamily, 10, FontStyle.Bold) End If End If End If End If Next End Sub
注意:如果TextBox存放在Panel、GroupBox等容器控件内,直接遍历
Me.Controls无法获取嵌套的子控件,需要编写递归方法遍历所有层级的控件。
内容的提问来源于stack exchange,提问作者Sindhu Halesh
相关产品推荐
相关产品推荐

