编制计算类程序时文本框一般都用于输入数字数据,此时可以通过以下步骤来确保用户输入数据的正确性:首先添加好文本框控件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
其中e.KeyChar是键盘输入的键对应的字符,IsDigit函数可以判断是否为0到9的数字,Chr(8)为退格键,当e.Handled为True时,程序认为该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) 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其中函数InStr返回指定字符在字符串中的位置,当字符串中不含此字符时,返回一个负数。这时文本框可以用来输入正整数及小数。
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
这时文本框可以用来输入正的或负的整数及小数。
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