【问题标题】:How to restrict user only being able to enter integer in textbox in vb.net [duplicate]如何限制用户只能在 vb.net 的文本框中输入整数 [重复]
【发布时间】:2016-06-14 22:13:57
【问题描述】:

当用户想要计算他们的 BMI 时,我如何限制他们,以便他们在程序加载时只能在文本框中输入整数?

如果可能的话,我怎样才能将 BMI 答案转换为小数点后 2 位或 1 位?

代码:

Public Class Form1

    Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click

        txtHeight.Text = txtHeight.Text / 100 ' converts txtheight into meter

        lblBMI.Text = txtWeight.Text / txtHeight.Text ^ 2 'BMI is equal to txtweight divided by (txtheight)^2

        'BMI = x KG / (y M * y M)

    End Sub

End Class

这就是设计

我知道这可能很简单,但我对编程还很陌生,谢谢!

【问题讨论】:

  • 图片不是您在这里发布代码的方式,请编辑您的问题并发布代码。
  • 好的,抱歉,我认为带有代码的图像就足够了 :)
  • 使用 NumericUpDown 控件。

标签: vb.net textbox integer restriction


【解决方案1】:

参考here.

 Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

    '97 - 122 = Ascii codes for simple letters
    '65 - 90  = Ascii codes for capital letters
    '48 - 57  = Ascii codes for numbers

    If Asc(e.KeyChar) <> 8 Then
        If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
            e.Handled = True
        End If
    End If

End Sub

将数字格式化为小数位:

YourLabel.Text = FormatNumber(YourNumber,N) 'N = Number of Decimal Places

【讨论】:

  • 无论“e.KeyChar”和“e.handled”在哪里,它都会出现蓝色下划线。它说“不是‘System.EventArgs’的成员。
  • 你把它放在了哪个事件里?
  • 在文本框的 KeyPress 事件中添加代码。
  • 哦,我把它放在“TextChanged”事件中。哈哈,然后我意识到你必须把它放在“按键”事件中。谢谢,它有效! :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多