C#中的textbox可以输入两位有效数字

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar == '\b') || (e.KeyChar == '.'))
{
e.Handled = false; // 允许输入
if ((e.KeyChar == '.') && (textBox1.Text.IndexOf('.') > -1))
{
e.Handled = true;
int pos = textBox1.SelectionStart;
if ((pos < textBox1.Text.Length - 1) && (textBox1.Text.Substring(pos, 1) == "."))
{
textBox1.SelectionStart = ++pos;
}
}
}
else
{
e.Handled = true; // 不允许输入
}
}

private void textBox1_Validating(object sender, CancelEventArgs e)
{
errorProvider.SetError(textBox1, "");
double dValue;
if (!double.TryParse(textBox1.Text,out dValue))
{
errorProvider.SetError(textBox1, string.Format("请输入带{0}位小数的有效数字", DecimalLength.ToString()));
e.Cancel = true;
}
}

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
int pos = textBox1.SelectionStart;
string strValue = textBox1.Text.Trim();
int pointPos = strValue.IndexOf('.');
if (pointPos < 0)
{
strValue += ".00";
}
if (pointPos == 0)
{
strValue = "0" + strValue;
textBox1.SelectionStart = ++pos;
}
// 自动使其保留两位小数
string[] strs = strValue.Split(new char[] { '.' });
strs[0] = strs[0].Length > 0 ? strs[0] : "0";

while (strs[0].Substring(0, 1) == "0")
{
if (strs[0].Length > 1)
{
strs[0] = strs[0].Substring(1, strs[0].Length - 1);
if (pos > 0)
{
--pos;
}
}
else
{
break;
}
}

if (strs[1].Length > 2)
{
strs[1] = strs[1].Substring(0, 2);
}
else if (strs[1].Length < 2)
{
strs[1] = strs[1].PadRight(2, '0');
}
textBox1.Text = strs[0] + "." + strs[1];
textBox1.SelectionStart = pos;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值