私は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; }
}
}