[英]How do I resolve "Unable to cast object of type 'ASP.addtoroster_aspx' to type 'System.Web.UI.WebControls.GridViewRow' error?
[英]How do I dynamically get an object type and cast to it?
如何获得 object 类型以便我可以直接转换为它? 这是我想执行的理想方法:
Dim MyObjects As New List(Of Object)
For Each O As Object In GlobalFunctions.GeneralFunctions.FindControlsRecursive(MyObjects, Form)
Select Case True
Case TypeOf O Is MenuStrip Or TypeOf O Is ToolStripButton Or TypeOf O Is Panel Or TypeOf O Is Label Or TypeOf O Is ToolStripSeparator
AddHandler DirectCast(O, O.GetType).Click, AddressOf GotFocus
End Select
Next
我试图使代码更高效,这样我就不必直接转换为指定的 object 类型。 前任。:
Dim MyObjectsAs New List(Of Object)
For Each O As Object In GlobalFunctions.GeneralFunctions.FindControlsRecursive(MyObjects, Form)
Select Case True
Case TypeOf O Is MenuStrip
AddHandler DirectCast(O, MenuStrip).Click, AddressOf GotFocus
Case TypeOf O Is Panel
AddHandler DirectCast(O, Panel).Click, AddressOf GotFocus
Case TypeOf O Is ToolStripButton
AddHandler DirectCast(O, ToolStripButton).Click, AddressOf GotFocus
Etc...
End Select
Next
据我所知, ToolStripItem
( ToolStripButton ) 不是Control
,因此我不能在这种情况下使用List(Of Control)
。 当我第一次使用控件列表时,工具条项目不包括在内。 这是我第一次在应用程序中使用ToolStrip
,所以直到现在我才没有理由不使用List(Of Control)
。
所有控件都派生自Control
。 因此,不要使用Object
类型,而是使用Control
。 Control
具有这些控件的大部分成员,例如Click
事件。
Dim myControls As New List(Of Control)
For Each ctrl As Control In _
GlobalFunctions.GeneralFunctions.FindControlsRecursive(myControls, Form)
AddHandler ctrl.Click, AddressOf GotFocus
Next
在FindControlsRecursive
中也可以使用Control
。
看:
事实证明,您有一些组件不是控件。 但是您仍然可以将所有控件转换为Control
Dim myControls As New List(Of Object)
For Each obj As Object In
GlobalFunctions.GeneralFunctions.FindControlsRecursive(myControls, Form)
Select Case True
Case TypeOf obj Is Control
AddHandler DirectCast(obj, Control).Click, AddressOf GotFocus
Case TypeOf obj Is ToolStripItem
AddHandler DirectCast(obj, ToolStripItem).Click, AddressOf GotFocus
End Select
Next
注意ToolStripItem
包括ToolStripButton
、 ToolStripControlHost
、 ToolStripDropDownItem
、 ToolStripLabel
和ToolStripSeparator
,因为所有这些组件都派生自ToolStripItem
。 您可以在 Visual Studio 的 Object 浏览器中看到这一点:
MenuStrip
是一个Control
。 因此,这两种情况应该涵盖您的大部分控件和组件。 如果您发现此处未涵盖的另一个组件,请搜索其具有Click
事件的派生最少的基本类型,以便新案例涵盖尽可能多的组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.