2011-03-28 103 views
0

我需要一些幫助與我的代碼。文本框格式化

我需要的格式如下,

12345-1234567-1

基本上我想只輸入數字和文字時,長度達到5,它應該在「 - 」,並再次上達到13的長度,再次應該追加' - '。

我的代碼做得很好。但是當我使用退格/刪除時,它總是在第6和第14位附加' - '。

這裏是我的代碼,

private void nicNo_txt_KeyUp(object sender, KeyEventArgs e) 
    { 
     if (e.KeyCode.ToString() != "Back" || e.KeyCode.ToString() != "Space" || e.KeyCode.ToString() != "Delete") 
     { 
      if (nicNo_txt.TextLength == 5 || nicNo_txt.TextLength == 13) 
       nicNo_txt.AppendText("-"); 
     } 
    } 

問候

+1

如果您使用Mask和DisplayFormatString屬性。將其設置爲:##### - ####### - #。 – Willem 2011-03-28 09:46:39

回答

4

你試過MaskedTextBox中,在裏面你可以指定任何格式,你需要

+0

感謝您的幫助。還有兩件事,一個是「我可以在輸入時刪除下劃線」,另一個是「當光標到達時' - '它應該移動到' - '的位置,同樣,當我使用退格鍵時,它應該先移到' - '。希望你明白我的意思,就像在安裝時輸入Windows串口一樣(不同之處在於你有多個文本框) – booota 2011-03-28 09:57:44

1

一個下面會做

對於格式化更改後 - 用什麼替代格式的方法你喜歡:

void oTextBoxAmount_TextChanged(object sender, EventArgs e) 
    { 
     //throw new NotImplementedException(); 
     if (sender is TextBox) 
     { 
      TextBox tb = sender as TextBox; 
      tb.Text = FormatAmount(tb.Text); 
      tb.SelectionStart = tb.Text.Length; 
     } 
    } 

對於過濾鍵(下面的例子過濾數字,但你可以改變條件):

void oTextBoxAmount_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     int val = (int)e.KeyChar; 
     if (val >= 0x30 && val <= 0x39) 
     { 
      //Digits are ok 
     } 
     else if (val == 0x08) 
     { 
      //Backspace is ok 
     } 
     else 
     { 
      //Other are disallowed 
      e.Handled = true; 
     } 
    }