简体   繁体   中英

how to solve Unable to cast object of type 'System.Windows.Forms.Form in VB.Net

I have the following subroutine:

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

but when I call the procedure I got the following error:

Unable to cast object of type 'CementAccSys.My.MyApplication' to type 'System.Windows.Forms.Form

the strange thing that when I call that procedure from another form, the error doesn't appear!!

To get the Form controls of the running project and the Button controls of each:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM