2016-03-31 11 views
0

私はTextBoxを持っていて、右から左に値を入力してカンマを追加したいと思います。私は千の値にコンマを加えたいと思います。私はタイプするときに値をフォーマットしたいと思います。右から左に入力し、テキストボックスに1000の値にカンマを追加しますか?

どうすればいいですか?

お試しください。

public class AddCommaToThousand { 
     private TextBox txtBox; 
     private String txt = string.Empty; 
     private Double valor = 0; 

     public AddCommaToThousand(TextBox txtBox) { 
      this.txtBox = txtBox; 
      this.txtBox.RightToLeft = RightToLeft.Yes;    
      this.txtBox.Text = "1,000"; 
      this.txtBox.KeyPress += keyPress; 
      this.txtBox.TextChanged += new EventHandler(textChanged);    
      this.txtBox.Font = new Font(this.txtBox.Font, FontStyle.Bold);    
     } 

     private void textChanged(object obj, EventArgs e) { 
      try { 
       txt = txtBox.Text.Replace(",", "").Replace(".", ""); 
       if (txt.Length == 0) { 
        txtBox.Text = "1,000"; 
       } 
       txt = txt.PadLeft(4, '0'); 
       if (txt.Length > 4 && txt.Substring(0, 1) == "0") 
        txt = txt.Substring(1, txt.Length - 1); 
       valor = Convert.ToDouble(txt); 
       txtBox.Text = string.Format("{0:N}", valor); 
       txtBox.SelectionStart = txtBox.Text.Length;     
      } 
      catch (Exception ex) { 
       Console.WriteLine(ex.Message); 
      }   
     } 

     private void keyPress(object obj, KeyPressEventArgs e) { 
      if (!(Char.IsDigit(e.KeyChar) || Char.IsControl(e.KeyChar))) { e.Handled = true; } 
     } 


    } 

答えて

0

あなたは文字列の長さを使用するか、またはあなたがそう

txtBox.Text = double.parse(txtBox.Text).ToString("N0"); 
ようにToStringメソッドを使用することができますカンマを追加するには

txtBox.TextAlign = HorizontalAlignment.Right; 

を使用し、右にテキストを整列させます

またはこれも使用できます。

txtBox.Text = double.parse(txtBox.Text).ToString("#,#"); 
0

代わりにMaskedTextBoxを使用してください。

はあなたの特性の残りはちょうど(RightToLeftを含む)は、正規TextBoxのように使用することができます###,###

のようなものにそのマスクを設定します。

関連する問題