2013-04-14 20 views
0

我想在用戶鍵入值到文本框中時更改文本。如何使用keydown動態格式字符串

這樣:

1 = 1 
12 = (12) 
123 = (12) 3 
1234 = (12) 34 

我做了這個代碼:

private void txtFoneres_KeyDown(object sender, KeyEventArgs e) 
{ 
    string p1 = e.KeyData.ToString(); 
    if (p1.StartsWith("D")) 
    { 
     p1 = p1.Replace("D", ""); 
    } 
    if (p1.StartsWith("NumPad")) 
    { 
     p1 = p1.Replace("NumPad", ""); 
    } 

    if (txtFoneres.TextLength == 1) 
    { 

     txtFoneres.Text = txtFoneres.Text + "(" + p1 + ")"; 
     txtFoneres.SelectionStart = 2; 
     txtFoneres.SelectionLength = 2; 
    } 
} 

使用我的代碼,結果是波紋管:

"1" = "1 
"12" = "1(2" (this is the problem, it would have to start with "(" 

有誰知道如何解決它,並改變1(2 for(12)?

+0

一行代碼什麼是你正在尋找你的「()」插入確切的規則是什麼?如果兩個或兩個以上的數字加起來()圍繞前兩個? – LightStriker

+1

這就像你試圖重新創建一個面具輸入?有控制,可以做到這一點,如果你使用的WinForms或WebForms – codingbiz

回答

0

我會嘗試使用MaskedTextBox 與像

private void maskedTextBox1_KeyUp(object sender, KeyEventArgs e) 
{ 
    if (maskedTextBox1.Text.Length == 1) 
    { 
     maskedTextBox1.Mask = "(00) 00"; 
     maskedTextBox1.SelectionStart = 2; 
    } 
} 
+0

問題是格式不是很好,它顯示()時什麼都沒有在字段上鍵入,我真的不明白這一點,我想讓它出現在用戶啓動後 –

+0

將Mask屬性留空,直到用戶輸入第一個數字。 – PLED

相關問題