自定义货币TextBox和粘贴文本检查

时间:2014-12-07 11:19:58

标签: .net vb.net controls

我制作了自己的货币文本框,这里是代码:

CurrencyTextBox.Designer.vb:

Partial Class CurrencyTextBox
    Inherits System.Windows.Forms.TextBox
    (...)
End Class

和CurrencyTextBox.vb:

Public Class CurrencyTextBox

Protected Overrides Sub OnKeyPress(e As Windows.Forms.KeyPressEventArgs)
    If Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or
    e.KeyChar = Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator Then
        MyBase.OnKeyPress(e)
    Else
        e.Handled = True
    End If
End Sub

End Class

它有效,但我不知道如何处理粘贴的文本,这里有很多例子(Capture CTRL+V or paste in a textbox in .NET)如何捕获CTRL + V,但不知道如何检查是否粘贴文字是"正确"。

我的想法是:

Dim text As String = Clipboard.GetText(TextDataFormat.Text)
For Each ch As Char In text
(...)
Next

但我觉得这不是最好的方式。我能做到吗"更好"?

1 个答案:

答案 0 :(得分:0)

应该是:

Private Sub CurrencyTextBox_TextChanged(sender As Object, e As EventArgs) Handles CurrencyTextBox.TextChanged
    Dim text As String = Clipboard.GetText(TextDataFormat.Text)
    For Each ch As Char In text
        (...)
    Next

End Sub

我在这种情况下使用的代码是:

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    If (Clipboard.GetText()) Then 'If we go straight to `Dim text...` then the application *could* crash, thus we filter out if they have any text on the clipboard first.
        Dim text As String = Clipboard.GetText()
        For Each ch As Char In text
            'Custom validation here.
        Next
    End If
End Sub

这里的关键变量是Handles CurrencyTextBox.TextChanged

只要在文本框中更改文本并运行您需要的任何验证,上述代码就会执行。