如何在没有InvalidCastException的情况下处理TextBox和MaskTextBox的事件?

时间:2018-09-24 21:25:21

标签: vb.net function textbox event-handling maskedtextbox

任何哥们请更正我的脚本,TextBox变量已完成工作,但MaskTextBox在此error中返回了EnterEvent

我想为event-handlingTextBox使用MaskTextBox的一个功能

    Private Sub TextBox_Enter(sender As Object, e As EventArgs) Handles OrgNameTextBox.Enter, AddressTextBox.Enter, ContactNumMaskedTextBox.Enter
        Dim Tb As TextBox = CType(sender, TextBox)
        Dim Mtb As MaskedTextBox = CType(sender, MaskedTextBox)
        If Type = MASKTEXTBOX Then
            MTb.BackColor = Color.Yellow
            MTb.ForeColor = Color.Black
        ElseIf Type = TextBox Then
            Tb.BackColor = Color.Yellow
            Tb.ForeColor = Color.Black
        End If
    End Sub

2 个答案:

答案 0 :(得分:1)

由于始终存在类型转换错误,因此事件处理程序无法工作 正确的版本是

Private Sub TextBox_Enter(sender As Object, e As EventArgs) Handles OrgNameTextBox.Enter, AddressTextBox.Enter, ContactNumMaskedTextBox.Enter
    If TypeOf sender Is MaskedTextBox Then
        Dim Mtb As MaskedTextBox = CType(sender, MaskedTextBox)
        Mtb.BackColor = Color.Yellow
        Mtb.ForeColor = Color.Black
    ElseIf TypeOf sender Is TextBox Then
        Dim Tb As TextBox = CType(sender, TextBox)
        Tb.BackColor = Color.Yellow
        Tb.ForeColor = Color.Black
    End If
End Sub

更好地使用两个控件TextBoxBase的共同祖先

Private Sub TextBox_Enter(sender As Object, e As EventArgs) Handles OrgNameTextBox.Enter, AddressTextBox.Enter, ContactNumMaskedTextBox.Enter
    Dim bt As TextBoxBase = TryCast(sender, TextBoxBase)
    If bt IsNot Nothing Then
        bt.BackColor = Color.Yellow
        bt.ForeColor = Color.Black
    End If
End Sub

答案 1 :(得分:1)

我经常使用@Jimi及其工作示例...

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='ex1'>
<a href="//app.google.com">app google</a> 
<a href="//www.info.google.com">info google</a>
<a href="https://google.com/abc">google abc</a>
<a href="https://www.apple.com">apple</a>
</div>

<hr/>

<div class='ex2'>
<a href="//app.google.com">app google</a> 
<a href="//www.info.google.com">info google</a>
<a href="http://wwwtst.google.com/abc">google abc</a>
<a href="https//wwwdev.apple.com">apple</a>
</div>
相关问题