[英]Allow only {'delete' , 'backspace' , one '.' , '-' , numbers '0 to 9'} on a textbox C#/winforms
[英]Only allow a specific Value Format in a Textbox C# WinForms
我要確保“文本框”的輸入具有特定格式。
+101.800
-085.000
+655.873
正確的長度以及+/-符號對於過程中的通信很重要。
我考慮過使用MaskedTextbox
但是如果我正確理解了文檔,那不會強迫用戶添加+/-符號。
試試這個正則表達式:
private void InputTextbox_Leave(object sender, EventArgs e)
{
Regex r = new Regex(@"^[+-]?[0-9]{3}\.[0-9]{3}$");
Match m = r.Match(InputTextbox.Text);
if (m.Success)
{
// Code
}
}
您可以在離開文本框后在“離開”事件中輸入檢查值,如果該值引起用戶注意,則將文本顏色設為紅色,並禁用提交按鈕以防止在按正確格式寫入數字之前按下按鈕。
private void myInput_Leave(object sender, EventArgs e)
{
Regex r = new Regex(@"^[+-]?[0-9]{3}\.[0-9]{3}$");
Match m = r.Match(InputTextbox.Text);
if (!m.Success)
{
myInput.ForeColor = Color.Red; // Text color will go red
submitBtn.Enabled = false; // Submit button is disabled now
}
else
{
myInput.ForeColor = Color.Black;
submitBtn.Enabled = true; // Submit button is enabled now
}
}
我使用了@Max Voisard的正則表達式,但是它給了我一個未知的Escape Sequnece錯誤,所以我添加了@Symbol使其對我有用。
private void textBox18_Validating(object sender, CancelEventArgs e)
{
Regex r = new Regex(@"^[+-]?[0-9]{3}\.[0-9]{3}$");
Match m = r.Match(((TextBox)sender).Text);
if (!m.Success)
{
// Cancel the event and select the text to be corrected by the user.
e.Cancel = true;
((TextBox)sender).Select(0, ((TextBox)sender).Text.Length);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.