首页 > 解决方案 > 如何解决无法在 VB.Net 中转换类型为“System.Windows.Forms.Form”的对象

问题描述

我有以下子程序:

Public Sub MyCodes_Users_Salahiyat()
    MyPubVar_Dt_Op_Salahiyat = New DataTable()
    MyPubVar_Dt_Op_Salahiyat.Columns.Add("Op_ID", Type.GetType("System.String"))
    MyPubVar_Dt_Op_Salahiyat.Columns.Add("FrmName", Type.GetType("System.String"))
    MyPubVar_Dt_Op_Salahiyat.Columns.Add("CmdName", Type.GetType("System.String"))
    MyPubVar_Dt_Op_Salahiyat.Columns.Add("FrmCaption", Type.GetType("System.String"))
    MyPubVar_Dt_Op_Salahiyat.Columns.Add("CmdCaption", Type.GetType("System.String"))

    Dim FormType As Type = Me.GetType().BaseType
    Dim xForms As List(Of Form) =
        (From t In [GetType]().Assembly.GetTypes()
         Where t.IsSubclassOf(FormType) = True Select DirectCast(Activator.CreateInstance(t), Form)).ToList()
    For Each xFrm In xForms
        Dim xCtrl As Control = xFrm.GetNextControl(xFrm, True)
        Dim xid As Integer
        Do Until xCtrl Is Nothing

            If xCtrl Is Nothing Then
                GoTo Line1
            Else
                If xCtrl.GetType = GetType(Button) Then
                    xid = xid + 1
                    MyPubVar_Dt_Op_Salahiyat.Rows.Add(xid, xFrm.Name, xCtrl.Name, xFrm.Text, xCtrl.Text)
                End If
            End If
Line1:
                xCtrl = xFrm.GetNextControl(xCtrl, True)
            Loop
        Next
End Sub

但是当我调用该程序时,出现以下错误:

无法将“CementAccSys.My.MyApplication”类型的对象转换为“System.Windows.Forms.Form”

奇怪的是,当我从另一个表单调用该过程时,错误不会出现!

标签: vb.net

解决方案


要获取Form正在运行的项目的Button控件以及每个项目的控件:

Public Sub MyCodes_Users_Salahiyat()
    MyPubVar_....

    For Each f In Assembly.GetExecutingAssembly().GetTypes().
                Where(Function(t) GetType(Form).IsAssignableFrom(t))

        ' Create a Form and dispose of it when it is no longer needed...
        Using ins = DirectCast(Activator.CreateInstance(f), Form)
            ' You have a Form here, do what you need to do...
            Console.WriteLine($"{ins.Name}, {ins.Text}")

            For Each btn In GetAllControls(ins).OfType(Of Button)
                ' You have a button here belongs to the current Form...
                Console.WriteLine($"{btn.Name}, {btn.Text}")
            Next
        End Using
    Next
End Sub

' A recursive method to get all the controls...
Private Function GetAllControls(parent As Control) As IEnumerable(Of Control)
    Dim cs = parent.Controls.OfType(Of Control)
    Return cs.SelectMany(Function(c) GetAllControls(c)).Concat(cs)
End Function

推荐阅读