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

VB中将Control转换为TextBox失败,求代码修改方案

VB.NET中Control转TextBox的问题修正

你的代码核心问题是逻辑判断完全颠倒:
TryCast(ctrl, TextBox)成功时,txtbox才是有效的TextBox实例;而你当前的判断是当转换失败(txtbox Is Nothing)时才往数组赋值,这自然无法得到正确的TextBox对象。

修正方案1(使用TypeOf+DirectCast)

先判断控件类型,再进行强转换,适合明确知道目标类型的场景:

Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim index As Integer = 1
    For Each ctrl As Control In TableLayoutPanel1.Controls
        ' 仅处理TextBox类型控件,且索引未超过数组上限
        If TypeOf ctrl Is TextBox AndAlso index <= 81 Then
            Dim txtbox As TextBox = DirectCast(ctrl, TextBox)
            sudokuArray(index) = txtbox
            index += 1
        End If
    Next
End Sub

修正方案2(使用TryCast)

安全转换,转换失败时返回Nothing,适合不确定控件类型的场景:

Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim index As Integer = 1
    For Each ctrl As Control In TableLayoutPanel1.Controls
        Dim txtbox As TextBox = TryCast(ctrl, TextBox)
        ' 仅保留转换成功的TextBox实例,且索引未超限
        If txtbox IsNot Nothing AndAlso index <= 81 Then
            sudokuArray(index) = txtbox
            index += 1
        End If
    Next
End Sub

额外注意事项

  • 确认sudokuArray的索引范围:如果数组是0起始的标准数组,需要把index初始值改为0,同时调整判断条件为index < 81
  • 如果TableLayoutPanel嵌套了其他容器(比如Panel),需要递归遍历所有子控件才能拿到全部TextBox

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 16:55:57