繁体   English   中英

带小数点的文本框显示格式

[英]textbox display formatting with decimal point

我想在每组 3 位数字后添加“,”。 例如:当我输入 123456789 时,文本框将显示 123,456,789,我使用以下代码得到它:

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
    if (!string.IsNullOrEmpty(textBox1.Text))
    {
        System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
        decimal valueBefore = decimal.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands);
        textBox1.Text = String.Format(culture, "{0:N0}", valueBefore);
        textBox1.Select(textBox1.Text.Length, 0);
    }
}

我想更具体地了解这种格式。 我只想为此文本框键入数字并使用十进制格式(之后键入 .),例如123,456,789.00 ,我尝试使用此代码:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
    {
        e.Handled = true;
    }
}

但它不起作用

您可以使用MSDN中定义的数字分组格式字符串类似以下内容应该可以工作(修改版):

private void textBox1_TextChanged(object sender, EventArgs e)
{
    decimal myValue;
    if (decimal.TryParse(textBox1.Text, out myValue))
    {
        textBox1.Text = myValue.ToString("N", CultureInfo.CreateSpecificCulture("en-US"));
        textBox1.SelectionStart = 0;
        textBox1.SelectionLength = 0;
    }
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.')
    {
        e.Handled = true;
    }           
}

http://msdn.microsoft.com/en-us/library/fzeeb5cd.aspx#Y600

将值解析为十进制数据类型后,只需使用ToStringtextbox1.Text分配该十进制变量的值,并将其传递给格式参数。

TextBox1.Text = valueBefore.ToString("C")

至于防止输入到文本框,我认为肯定已经有一种模式了。

无论如何,试试这个:

if !(Char.IsControl(e.KeyChar) || Char.IsDigit(e.KeyChar) || (e.KeyChar == Keys.Decimal && !(TextBox1.Text.Contains("."))))
{
    e.Handled = true;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM