轉自: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("編號只能輸入數字!");
}
}
也可以用Regex:
C#Winform下用Regex限制TextBox只能輸入數字 昨天,在網上特別是園子裡搜了下如何在Winform下限制TextBox只能輸入數位功能。可是結果基本上都是在web的環境下用Regex實現的,而在Winform的平台下,好像沒有發現。 就自己循著思路實現了下。
首先,先定義一個string,用來表示數位Regex:
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); // 匹配Regex
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等事件的
這樣就行了 只能輸入小數與數字
//本文為轉載網上資源,又加上自己總結!