如何使用Visual Basic将文本框限制为仅正数?

时间:2017-12-19 18:42:20

标签: vb.net visual-studio

处理折扣字段。该字段只需要允许0到100之间的正数。字段是一个文本框。使用visual studio和visual basic。

1 个答案:

答案 0 :(得分:1)

您可以使用NumericUpDown控件及其Minimum,Maximum和DecimalPlaces属性。

但是,如果你不喜欢滚动框并且真的想使用TextBox,可以这样做:

Private min As Decimal = 1
Private max As Decimal = 100

Private Sub txtDiscount_TextChanged(sender As Object, e As EventArgs) Handles txtDiscount.TextChanged
    Dim i As Decimal
    Static lastValidText = ""
    If (txtDiscount.Text = "") OrElse (Decimal.TryParse(txtDiscount.Text, i) AndAlso (i >= min And i <= max)) Then
        lastValidText = txtDiscount.Text
    Else
        txtDiscount.Text = lastValidText
        txtDiscount.SelectionStart = txtDiscount.TextLength
    End If
End Sub