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;
}

你可能感兴趣的:(C#中的textbox可以输入两位有效数字)