2013-04-21 57 views
-2

我需要使一個TextBox控件一次只接受一個字符。例如,如果我輸入「aaa」,那麼它只會接受「a」textbox一次只接受一個字符

我該如何做到這一點?

+0

您一次只能寫一個字符。你的意思是重複的人物? – nmat 2013-04-21 18:39:34

+0

你希望Text屬性的長度不會超過1,是嗎? – 2013-04-21 18:40:31

+0

'如果我發送「aaa」'你如何一次發送所有這些文件? – I4V 2013-04-21 18:40:32

回答

1

TextBox具有MaxLength屬性。 MaxLength獲取或設置可以手動輸入文本框的最大字符數。

<TextBox MaxLength="1" Width="120" Height="23" /> 

所以在這裏,您只能手動輸入一個字符。

1

如果我理解正確,您不希望用戶能夠連續多次輸入相同的密鑰。這應該防止:

private void textBox_KeyDown(object sender, KeyEventArgs e) 
{ 
    TextBox textBox = sender as TextBox; 
    if(textBox != null) 
    { 
     if (!String.IsNullOrEmpty(textBox.Text)) 
     { 
      //get the last character and convert it to a key 
      char prevChar = textBox.Text[textBox.Text.Length - 1]; 
      Keys k = (Keys)char.ToUpper(prevChar); 

      //compare the Key pressed to the previous Key 
      if (e.KeyData == k) 
      { 
       //suppress the keypress if the key is the same as the previous one 
       e.SuppressKeyPress = true;    
      } 
     } 
    } 
} 
相關問題