C# 在文本框中从右向左键入并将逗号添加到千值?
我有一个文本框,我想从右到左键入值并添加逗号。我想在1000个值中添加逗号,并在输入时格式化这些值 我怎么能这样做 努力C# 在文本框中从右向左键入并将逗号添加到千值?,c#,C#,我有一个文本框,我想从右到左键入值并添加逗号。我想在1000个值中添加逗号,并在输入时格式化这些值 我怎么能这样做 努力 public class AddCommaToThousand { private TextBox txtBox; private String txt = string.Empty; private Double valor = 0; public AddCommaToThousand(TextBox txt
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; }
}
}
要将文本向右对齐,请使用
txtBox.TextAlign = HorizontalAlignment.Right;
要添加逗号,可以使用字符串的长度,也可以像这样使用ToString方法
txtBox.Text = double.parse(txtBox.Text).ToString("N0");
或者,也可以使用此选项
txtBox.Text = double.parse(txtBox.Text).ToString("#,#");
改用a
将其掩码设置为类似于########
您的其他属性可以像普通的文本框一样使用(包括rightoleft
)