轉自:http://hi.baidu.com/zhaolianbin521/item/e4664e286f3e47c1dcf69ae4
C#的winform中控制TextBox中只能輸入數字(加上固定位數和首位不能為0)
給個最簡單的方法:
private void textBox3_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
//阻止從鍵盤輸入鍵
e.Handled = true;
if(e.KeyChar>='0' && e.KeyChar <='9')
{
e.Handled = false;
}
}
或者
private void tbID_KeyPress(object sender, KeyPressEventArgs e)
{
if (!((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == ' '))//不輸入輸入除了數字之外的所有非法字符的判斷
{
e.Handled = true;
}
}
多條件的:
private void TxtUser_KeyPress(object sender, KeyPressEventArgs e)
{
//阻止從鍵盤輸入鍵
e.Handled = true;
if ((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar == (char)8))
{
if ((e.KeyChar == (char)8)) { e.Handled = false; return; }
else
{
int len = TxtUser.Text.Length;
if (len < 5)
{
if (len == 0 && e.KeyChar != '0')
{
e.Handled = false; return;
}
else if(len == 0)
{
MessageBox.Show("編號不能以0開頭!"); return;
}
e.Handled = false; return;
}
else
{
MessageBox.Show("編號最多只能輸入5位數字!");
}
}
}
else
{
MessageBox.Show("編號只能輸入數字!");
}
}
也可以用正則表達式:
C#Winform下用正則表達式限制TextBox只能輸入數字 昨天,在網上特別是園子里搜了下如何在Winform下限制TextBox只能輸入數字的功能。可是結果基本上都是在web的環境下用正則表達式實現的,而在Winform的平台下,好像沒有發現。 就自己循着思路實現了下。
首先,先定義一個string,用來表示數字的正則表達式:privatestring pattern =@"^[0-9]*$";
然后再定義一個string,用來記錄TextBox原來的內容,以便在輸入非數字的時候,文本框的內容可以恢復到原來的值(我不知道TextBox怎么恢復到上一次的內容,只能采用這個笨辦法了):privatestring param1 =null;
接着,我們就可以在textBox的TextChanged事件中判斷輸入的是否是數字,如果是數字,那么就把文本框的內容保存在param1中;如果不是數字,那么取消這次輸入,即重新設置文本框的內容為param1: privatevoid textBoxParam1_TextChanged(object sender, EventArgs e)
{
Match m = Regex.Match(this.textBoxParam1.Text, pattern); // 匹配正則表達式
if (!m.Success) // 輸入的不是數字
{
this.textBoxParam1.Text = param1; // textBox內容不變
// 將光標定位到文本框的最后
this.textBoxParam1.SelectionStart =this.textBoxParam1.Text.Length;
}
else // 輸入的是數字
{
param1 =this.textBoxParam1.Text; // 將現在textBox的值保存下來
}
}
網頁里面:
<asp:textbox id="TextBox1" onkeyup="if(isNaN(value))execCommand('undo')" runat="server"
Width="80px" onafterpaste="if(isNaN(value))execCommand('undo')"></asp:textbox>
其實服務器控件也能加上onkeydown與up等事件的
這樣就行了 只能輸入小數與數字
//本文為轉載網上資源,又加上自己總結!