感知文本框中的小数
本文关键字:小数 文本 感知 | 更新日期: 2023-09-27 17:54:13
我正在为Windows Phone开发一种计算器。
不需要使用小数。(谁需要0.39块砖)
如何检测字符串或文本框中是否有小数?
编辑:谢谢@Bala R和@Afnan但我想要的是能够过滤掉字母的东西。我的答案在下面
修改Bala R
代码得到
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Contains(".") || textBox1.Text.Contains(","))
textBox1.Text = textBox1.Text.Replace(".", string.Empty).Replace(",", string.Empty);
}
这将删除输入时输入的无效字符
我认为您需要检查该值是否为有效的十进制值。
使用TryParse方法
decimal value;
string textValue = textBox.Text;
bool isDecimal = decimal.TryParse(textValue, out value)
您可以使用此命令查看字符串
中是否存在"句号" bool hasDecimal = textBox.Text.Contains(".")
这是我发现最有效的方法:
StringBuilder szNumbersOnly = new StringBuilder();
TextBox textSource = sender as TextBox;
if (null == textSource)
return;
foreach (char ch in textSource.Text)
{
if (("0123456789").Contains(ch.ToString()))
{
szNumbersOnly.Append(ch);
}
else
{
bNeedToUpdate = true;
}
}
if (bNeedToUpdate)
{
textSource.Text = szNumbersOnly.ToString();
textSource.SelectionStart = szNumbersOnly.Length;
}bool bNeedToUpdate = false;
我从Erin Fleck那里偷了这个答案,Erin Fleck是一个论坛的版主,他回答了这个类似的问题。
@Afnan得到了绿支票,因为他/她/它回答了我最初的问题。