多事件处理中sender.GetType()识别DevExpress控件类型报错求助
解决DevExpress LookupEdit/GridLookupEdit共享事件处理的类型转换问题
你的代码核心错误出在**DirectCast(sender, Type)这一行的逻辑偏差**:sender是触发事件的控件实例(比如你的mgrLUE或sectGLUE),而非Type类型对象,直接把实例转成Type必然会报错。
我给你两种贴合需求的可靠解决方案:
方案1:按控件名称判断(最匹配你的原始逻辑)
既然你的分支是按控件名称("mgrLUE"、"sectGLUE")区分的,直接获取控件的Name属性即可,无需绕类型转换:
' 先将sender转为Control,确保类型安全 Dim targetCtrl = TryCast(sender, Control) If targetCtrl IsNot Nothing Then Select Case targetCtrl.Name Case "mgrLUE" ' 转成对应的LookupEdit类型 Dim mgrLUE = DirectCast(targetCtrl, LookUpEdit) log("View metrics for manager: " & mgrLUE.Properties.GetDisplayText(mgrLUE.EditValue), Me.Name) Case "sectGLUE" ' 注意你原始代码里写的是sectLUE但实际用的是sectGLUE,要和控件真实名称一致 Dim sectGLUE = DirectCast(targetCtrl, GridLookUpEdit) log("View metrics for section: " & sectGLUE.Properties.GetDisplayText(sectGLUE.EditValue), Me.Name) End Select End If
方案2:按控件类型判断(适合按类别统一处理场景)
如果你想先区分控件类型(LookupEdit/GridLookupEdit),再按名称细分,可参考这种写法:
Dim ctrlType = sender.GetType() Select Case ctrlType.Name Case "LookUpEdit" Dim lue = DirectCast(sender, LookUpEdit) If lue.Name = "mgrLUE" Then log("View metrics for manager: " & lue.Properties.GetDisplayText(lue.EditValue), Me.Name) End If Case "GridLookUpEdit" Dim glue = DirectCast(sender, GridLookUpEdit) If glue.Name = "sectGLUE" Then log("View metrics for section: " & glue.Properties.GetDisplayText(glue.EditValue), Me.Name) End If End Select
额外注意事项:
- 你原始代码里
Case "sectLUE"但后续调用的是sectGLUE,这大概率是笔误,务必保证分支名称和控件实际的Name属性完全一致,否则分支不会触发。 - 用
TryCast代替直接DirectCast,可以避免类型不匹配时的异常,让代码更健壮。
内容的提问来源于stack exchange,提问作者dk96m
相关产品推荐
相关产品推荐

