发布网友 发布时间:2022-04-30 18:53
共1个回答
热心网友 时间:2022-04-23 05:46
powered by 25175.netVB.net中使文本框只能输入数字首先添加好文本框控件TextBox后把属性IMEMode的值改成Disable,这样在该文本框中就不能使用中文输入法了。然后对文本框的KeyPress事件添加以下代码 Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Textbox1.KeyPress If Char.IsDigit(e.KeyChar) Or e.KeyChar = Chr(8) Then e.Handled = False Else e.Handled = True End If End Sub 如果文本需要输入小数的话,就要能够输入小数点".",而且小数点只能输入一次,此时可以将上面的函数改为下面的格式: Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Textbox1.KeyPress If Char.IsDigit(e.KeyChar) or e.KeyChar = Chr(8) or e.KeyChar = "." Then If e.KeyChar = "." And InStr(TextBox1.Text, ".") >0 Then e.Handled = True Else e.Handled = False End If Else e.Handled = True End If End Sub 如果文本需要输入负数的话,就要能够输入负号"-",而且只能是文本框输入的第一个字符,此时又可以将上面的函数改为下面的格式: Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Textbox1.KeyPress If Char.IsDigit(e.KeyChar) Or e.KeyChar = "." Or e.KeyChar = Chr(8) Then If e.KeyChar = "." And InStr(TextBox1.Text, ".") >0 Then e.Handled = True Else e.Handled = False End If ElseIf e.KeyChar = "-" And TextBox1.Text = "" Then e.Handled = False Else e.Handled = True End If End Sub 这时文本框可以用来输入正的或负的整数及小数。当有多个文本框需要做输入*时,可以在以上代码Handles后面加上多个文本框的KeyPress事件,各事件之间用逗号隔开,例如 Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Textbox1.KeyPress,Textbox2.KeyPress,Textbox3.KeyPress 对于要判断文本框内容的函数,就要把代码进行修改,使其能够同时处理多个文本框,也就是把上面后两段程序中的TextBox1.Text改为CType(sender, TextBox).Text,这样一来就能够对号入座了,比如上面能够输入负号的代码就可以改成: Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Textbox1.KeyPress,Textbox2.KeyPress,Textbox3.KeyPress If Char.IsDigit(e.KeyChar) Or e.KeyChar = "." Or e.KeyChar = Chr(8) Then If e.KeyChar = "." And InStr(CType(sender, TextBox).Text, ".") >0 Then e.Handled = True Else e.Handled = False End If ElseIf e.KeyChar = "-" And CType(sender, TextBox).Text = "" Then e.Handled = False Else e.Handled = True End If End Sub 这样一来四个文本框就都只能输入正的或负的整数及小数了。