[英]How to only allow Integers into a textbox
我有一個憑證應用程序,當有人要創建活動憑證時,他們必須指定的字段之一是“目標受眾”。 有時,該人員可能輸入字符串或不是int的變量,並且服務器將崩潰。 我只想實現一個if語句,以查看其是否不是int,然后執行某些操作。 我有一個正則表達式,我只是不知道如何實現它。 嘗試了很多事情。 (要驗證的文本框是“ campaignAudience”)
System.Text.RegularExpressions.Regex.IsMatch(campaignAudience.Value, "[ ^ 0-9]");
我最近需要一個類似的解決方案。 假設您需要一個整數(不帶小數點的數字)。
public static bool IntegerAndIsANumber(this string val)
{
if (string.IsNullOrEmpty(val) || val.Contains(',') || val.Contains('.'))
return false;
decimal decimalValue;
if (!Decimal.TryParse(val, out decimalValue))
return false;
decimal fraction = decimalValue - (Int64)decimalValue;
if (fraction == 0)
return true;
return false;
}
它檢查給定的字符串是否為Integer,以及是否首先為數字。
使用:
if(YourString.IntegerAndIsANumber()){
//value is Integer
}
else{
//incorrect value
}
PS也已使用此擴展方法進行了Unit testing
。
使用僅接受數字的自定義TextBox,將以下內容添加到項目中,進行編譯,然后在IDE中顯示表單時,自定義TextBox將出現在工具箱的頂部。 將文本框添加到窗體,現在用戶只能輸入數字。
using System;
using System.Windows.Forms;
public class numericTextbox : TextBox
{
private const int WM_PASTE = 0x302;
protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
string Value = this.Text;
Value = Value.Remove(this.SelectionStart, this.SelectionLength);
Value = Value.Insert(this.SelectionStart, e.KeyChar.ToString());
e.Handled = Convert.ToBoolean(Value.LastIndexOf("-") > 0) ||
!(char.IsControl(e.KeyChar) ||
char.IsDigit(e.KeyChar) ||
(e.KeyChar == '.' && !(this.Text.Contains(".")) ||
e.KeyChar == '.' && this.SelectedText.Contains(".")) ||
(e.KeyChar == '-' && this.SelectionStart == 0));
base.OnKeyPress(e);
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == WM_PASTE)
{
string Value = this.Text;
Value = Value.Remove(this.SelectionStart, this.SelectionLength);
Value = Value.Insert(this.SelectionStart, Clipboard.GetText());
decimal result = 0M;
if (!(decimal.TryParse(Value, out result)))
{
return;
}
}
base.WndProc(ref m);
}
}
if(campaignAudience.Value.All(x => Char.IsLetter(x)))
{
// text input is OK
}
if(new Regex("^[A-Za-z]*$").Match(campaignAudience.Value).Success)
{
// text input is OK
}
將文本框的按鍵事件限制為數字
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.