如何在 Winforms、C# 中为文本框添加千位分隔符 [英] How to add a thousand separator for a textbox in Winforms, C#

查看:40
本文介绍了如何在 Winforms、C# 中为文本框添加千位分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在输入数字时为文本框添加千位分隔符(如逗号).

I want to know how can I add a thousand separator like a comma for my textBox while I am typing a number in it.

即1,500 而不是 1500.

i.e. 1,500 instead of 1500.

推荐答案

幸运的是,我解决了我的问题.

Fortunately, I solved my problem.

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (textBox1.Text == "" || textBox1.Text == "0") return;                         
    decimal price;                                                                   
    price = decimal.Parse(textBox1.Text, System.Globalization.NumberStyles.Currency);
    textBox1.Text = price.ToString("#,#");                                           
    textBox1.SelectionStart = textBox1.Text.Length;                                  
}

我们可以在 textBox 的 TextChanged 方法中编写此代码,为 textBox 添加千位分隔符.

we can write this code in the TextChanged method of our textBox to add a thousand separator for the textBox.

顺便说一句,如果你想稍后将其更改为第一个状态,或者如果你想使用文本框中的数字,在数据库中,你可以使用替换方法.

by the way, If you wanted to change it later to the first state or if you wanted to use the number in the textbox, in the database, you can use the Replace method.

textBox1.Text.Replace(",","");

希望你觉得它有用.

这篇关于如何在 Winforms、C# 中为文本框添加千位分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆