vb.net - 如何解决无法在 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”
奇怪的是,当我从另一个表单调用该过程时,错误不会出现!
解决方案
要获取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
推荐阅读
- java - java.lang.InstantiationException 第二次
- python-3.4 - Python - 从文件中读取整数并在操作后将其替换为同一文件
- python - 如何在 python 中抑制 PDFMiner 的布局分析
- linux - 在从不同进程访问 fifo 时,某些东西会阻塞线程
- javascript - 如何使用 Kendo 在钻取图表中创建返回按钮
- acumatica - 2017R2 中的现代 UI 站点地图
- c# - 使用 MVVM 自动更新 WPF 中的 Combobox 内容
- c++ - Valgrind 工作缓慢
- dart - 如何检查当前路线是哪条?
- ios - SiriKit 错误:此应用程序不支持捐赠意图