使数字文本框像(###,###,###)
本文关键字:数字 文本 | 更新日期: 2023-09-27 18:02:24
我有一个数字文本框,像这样分隔数字(###,###,###),并使用以下代码:
private void txtnum2_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
txtnum2.Text += Convert.ToString(e.KeyChar);
}
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
txtnum2.Text = Regex.Replace(txtnum2.Text, "[^.0-9]", "");
for (int i = 1, j = 0; i < 10; ++i)
{
try
{
txtnum2.Text = txtnum2.Text.Insert(txtnum2.Text.Length - ((3 * i) + j), ",");
++j;
}
catch { }
}
但在第一个"之后,其他数字将放在文本框的第一个
在Winforms中(如@drew_w指出),您将使用MaskedTextBox
maskedTextBox1.Mask = "###,###,###";
maskedTextBox1.KeyDown += new KeyEventHandler(txtnum2_KeyPress);
在WPF中,您可以查看这篇博文(翻译)