編制計(jì)算類程序時(shí)文本框一般都用于輸入數(shù)字?jǐn)?shù)據(jù),此時(shí)可以通過以下步驟來(lái)確保用戶輸入數(shù)據(jù)的正確性: 首先添加好文本框控件TextBox后把屬性IMEMode的值改成Disable,這樣在該文本框中就不能使用中文輸入法了。然后對(duì)文本框的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是鍵盤輸入的鍵對(duì)應(yīng)的字符,IsDigit函數(shù)可以判斷是否為0到9的數(shù)字,Chr(8)為退格鍵,當(dāng)e.Handled為True時(shí),程序認(rèn)為該KeyPress事件已經(jīng)被處理過了,文本框的內(nèi)容也就不會(huì)發(fā)生變化了。從以上程序中不難看出,此時(shí)文本框只能接受數(shù)字和退格鍵,也就是說這個(gè)文本框是用來(lái)輸入整數(shù)的。 如果文本需要輸入小數(shù)的話,就要能夠輸入小數(shù)點(diǎn)".",而且小數(shù)點(diǎn)只能輸入一次,此時(shí)可以將上面的函數(shù)改為下面的格式: 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 其中函數(shù)InStr返回指定字符在字符串中的位置,當(dāng)字符串中不含此字符時(shí),返回一個(gè)負(fù)數(shù)。這時(shí)文本框可以用來(lái)輸入正整數(shù)及小數(shù)。 如果文本需要輸入負(fù)數(shù)的話,就要能夠輸入負(fù)號(hào)"-",而且只能是文本框輸入的第一個(gè)字符,此時(shí)又可以將上面的函數(shù)改為下面的格式: 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 這時(shí)文本框可以用來(lái)輸入正的或負(fù)的整數(shù)及小數(shù)。 當(dāng)有多個(gè)文本框需要做輸入限制時(shí),可以在以上代碼Handles后面加上多個(gè)文本框的KeyPress事件,各事件之間用逗號(hào)隔開,例如 Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Textbox1.KeyPress,Textbox2.KeyPress,Textbox3.KeyPress 對(duì)于要判斷文本框內(nèi)容的函數(shù),就要把代碼進(jìn)行修改,使其能夠同時(shí)處理多個(gè)文本框,也就是把上面后兩段程序中的TextBox1.Text改為CType(sender, TextBox).Text,這樣一來(lái)就能夠?qū)μ?hào)入座了,比如上面能夠輸入負(fù)號(hào)的代碼就可以改成: 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
|