TextBox输入控制代码
C#控制TextBox输入的源代码:
public static void KeyPressUFloat(object sender, KeyPressEventArgs e,int decCount)
...{
TextBox txtBox = (TextBox)sender;
int curPos = txtBox.SelectionStart; // 当前光标位置
int pointPos = txtBox.Text.LastIndexOf(''.''); // 小数点位置
// 输入位置在两位小数点后,不允许输入
if ((pointPos > 0) && (curPos > (pointPos + decCount)))
...{
if (e.KeyChar != '''')
...{
e.Handled = true;
}
return;
}
try
...{
string strInt = txtBox.Text.Trim().Substring(0, curPos);
string strDec = "";
if (pointPos < 0)
...{
strDec = ".00";
}
else
...{
// 读取并规范化小数部分
strDec = txtBox.Text.Trim().Substring(pointPos);
if (strDec.Length > decCount + 1)
...{
strDec = strDec.Substring(0, decCount + 1);
}
else
...{
strDec = strDec.PadRight(decCount + 1, ''0'');
}
}
// 检测输入的字符
if ((e.KeyChar < ''0'' || e.KeyChar > ''9'') &&
(e.KeyChar != ''.'') && (e.KeyChar != ''''))
...{
e.Handled = true;
}
else if (e.KeyChar == ''.'')
...{
// 输入了小数点
e.Handled = true;
if (strInt.Length == 0)
...{
strInt = "0";
}
// 消除整数部分的小数点
if (strInt.IndexOf(".") != -1)
...{
strInt = strInt.Remove(strInt.IndexOf(''.''));
}
txtBox.Text = strInt + strDec;
txtBox.SelectionStart = curPos;
}
else
...{
// 输入数字的操作
e.Handled = false;
if (curPos > pointPos)
...{
// 小数点后,覆盖选择的后一个字符
txtBox.SelectionLength = 1;
}
else if (curPos == pointPos)
...{
//txtBox.SelectionStart = curPos;
//SendKeys.Send(e.KeyChar.ToString());
// 输入位置在小数点之前的处理
if (txtBox.Text.Trim().Length == txtBox.MaxLength)
...{
strDec = strDec.Remove(1, 1);
strDec = strDec.Insert(1, e.KeyChar.ToString());
txtBox.Text = strInt + strDec;
curPos += 2;
e.Handled = true;
txtBox.SelectionStart = curPos;
}
else
...{
txtBox.SelectionStart = curPos;
}
}
if (pointPos < 0)
...{
txtBox.Text = strInt + strDec;
pointPos = txtBox.Text.LastIndexOf(''.''); // 小数点位置
}
if ((curPos < pointPos) &&
(txtBox.Text.Trim().Length == txtBox.MaxLength))
...{
txtBox.SelectionLength = 1;
}
txtBox.SelectionStart = curPos;
}
}
catch (Exception)
...{
throw new Exception("Internal error : UFloat");
}
}
注: 本代码参照: 编程中国 http://www.bc-cn.net
作者: C_B_Lu QQ:184118549
时间: 2007-9-4 编程论坛首发
补充:asp.net教程,.Net开发