1. 程式人生 > >C#中的textbox可以輸入兩位有效數字

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