2012-09-26 42 views
11

如何僅允許Visual C#文本框中的某些字符?用戶應該能夠將下列字符輸入到文本框中,其他所有內容都應該被阻止:0-9,+, - ,/,*,(,)。只允許文本框中的特定字符

我已經使用谷歌來查找這個問題,但我得到的唯一解決方案是隻允許字母字符,只能數字或不允許某些字符。我想要的是不禁止某些字符,除了我在代碼中放置的字符之外,我想要默認禁止所有內容。

+4

ASP.NET?的WinForms? WPF?所有這些都可以使用C#,並且都是不同的。 – David

+0

這是一個Windows窗體應用程序。 –

+1

您是否嘗試過爲PropertyChanged事件創建一個事件處理程序,該事件刪除該字符是否無效? –

回答

23

正如在評論中提到的(以及我輸入的另一個答案),您需要註冊一個事件處理函數來捕獲文本框上的keydown或keypress事件。這是因爲框TextChanged當文本框失去焦點

下面的正則表達式,您可以匹配你要允許

Regex regex = new Regex(@"[0-9+\-\/\*\(\)]"); 
MatchCollection matches = regex.Matches(textValue); 

這些字符只有解僱,這則正好相反,卻捉住了不允許使用的字符

Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]"); 
MatchCollection matches = regex.Matches(textValue); 

我不假定會有單個匹配,因爲有人可以將文本粘貼到文本框中。在這種情況下,捕捉框TextChanged

textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged); 
private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]"); 
    MatchCollection matches = regex.Matches(textBox1.Text); 
    if (matches.Count > 0) { 
     //tell the user 
    } 
} 

,並驗證單個按鍵

textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress); 
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) 
{ 
    // Check for a naughty character in the KeyDown event. 
    if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"[^0-9^+^\-^\/^\*^\(^\)]")) 
    { 
     // Stop the character from being entered into the control since it is illegal. 
     e.Handled = true; 
    } 
} 
+2

您可能希望爲代碼8添加額外的密鑰檢查,否則退格將不起作用 – imaximchuk

+0

如果有其他人遇到此問題......我無法在「KeyPress」處理程序中使用此工作。即使我將'e.Handled'設置爲'true',它仍然會將字符插入到控件中。當我改用「KeyDown」處理時,一切正常。我使用的控件是一個'RichTextBox',所以這可能與它有關。在我開始工作後,我沒有多少實驗。 – danBhentschel

+1

作爲一個附註,TextChanged在文本丟失焦點時不會被觸發,而是在文本發生變化之後(例如,如果文本有效,則使用它來對文本着色)。這太難了。 – Teejay

10

您需要訂閱的文本框中KeyDown事件。然後是這樣的:

private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) 
{ 
    if (!char.IsControl(e.KeyChar) 
     && !char.IsDigit(e.KeyChar) 
     && e.KeyChar != '.' && e.KeyChar != '+' && e.KeyChar != '-' 
     && e.KeyChar != '(' && e.KeyChar != ')' && e.KeyChar != '*' 
     && e.KeyChar != '/') 
    { 
     e.Handled = true; 
     return; 
    } 
    e.Handled=false; 
    return; 
} 

重要的是要知道的是,如果你改變了Handled屬性true,它不會處理擊鍵。將其設置爲false即可。

-1
private void txtuser_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     if (!char.IsLetter(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar) && !char.IsControl(e.KeyChar)) 
     { 
      e.Handled = true; 
     } 
    } 
0

截取KeyPressed事件在我看來是一個很好的解決方案。如果使用RegExp,請注意觸發代碼字符(e.KeyChar低於32)。

但是用這種方法,只要用戶從剪貼板粘貼文本,仍然可以注入超出範圍的字符。不幸的是,我沒有找到正確的剪貼板事件來解決這個問題。

所以防水解決方案是攔截TextBox.TextChanged。這裏有時候是原始的超範圍字符可見,很短的時間。我建議實施這兩個。

using System.Text.RegularExpressions;

private void Form1_Shown(object sender, EventArgs e) 
{ 
    filterTextBoxContent(textBox1); 
} 


string pattern = @"[^0-9^+^\-^/^*^(^)]"; 

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if(e.KeyChar >= 32 && Regex.Match(e.KeyChar.ToString(), pattern).Success) { e.Handled = true; } 
} 

private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    filterTextBoxContent(textBox1); 
} 

private bool filterTextBoxContent(TextBox textBox) 
{ 
    string text = textBox.Text; 

    MatchCollection matches = Regex.Matches(text, pattern); 
    bool matched = false; 

    int selectionStart = textBox.SelectionStart; 
    int selectionLength = textBox.SelectionLength; 

    int leftShift = 0; 
    foreach (Match match in matches) 
    { 
     if (match.Success && match.Captures.Count > 0) 
     { 
      matched = true; 
      Capture capture = match.Captures[0]; 

      int captureLength = capture.Length; 
      int captureStart = capture.Index - leftShift; 
      int captureEnd = captureStart + captureLength; 

      int selectionEnd = selectionStart + selectionLength; 

      text = text.Substring(0, captureStart) + text.Substring(captureEnd, text.Length - captureEnd); 

      textBox.Text = text; 

      int boundSelectionStart = selectionStart < captureStart ? -1 : (selectionStart < captureEnd ? 0 : 1); 
      int boundSelectionEnd = selectionEnd < captureStart ? -1 : (selectionEnd < captureEnd ? 0 : 1); 

      if (boundSelectionStart == -1) 
      { 
       if (boundSelectionEnd == 0) 
       { 
        selectionLength -= selectionEnd - captureStart; 
       } 
       else if (boundSelectionEnd == 1) 
       { 
        selectionLength -= captureLength; 
       } 
      } 
      else if (boundSelectionStart == 0) 
      { 
       if (boundSelectionEnd == 0) 
       { 
        selectionStart = captureStart; 
        selectionLength = 0; 
       } 
       else if (boundSelectionEnd == 1) 
       { 
        selectionStart = captureStart; 
        selectionLength -= captureEnd - selectionStart; 
       } 
      } 
      else if (boundSelectionStart == 1) 
      { 
       selectionStart -= captureLength; 
      } 

      leftShift++; 
     } 
    } 

    textBox.SelectionStart = selectionStart; 
    textBox.SelectionLength = selectionLength; 

    return matched; 
} 
相關問題