[原创]让TextBox只允许输入带3位小数的数字
*/ --------------------------------------------------------------------------------------*/ 出自: 编程中国 http://www.bc-cn.net
*/ 作者: C_B_Lu QQ:184118549
*/ 时间: 2007-8-21 编程论坛首发
*/ 声明: 尊重作者劳动,转载请保留本段文字
*/ --------------------------------------------------------------------------------------
注:tbRate为一个TextBox控件, tbRate_Validating和tbRate_KeyPress他别的这个控件的Validating事件和KeyPress事件.
private void tbRate_Validating(object sender, CancelEventArgs e)
{
string strRate = double.Parse(tbRate.Text).ToString();
if(strRate.Trim().Length == 0)
{
strRate = "1.000";
}
int pos = strRate.LastIndexOf('.');
if (pos < 0)
{
strRate += ".000";
}
string[] strs = strRate.Split(new char[] { '.' });
if (strs[1].Length > 3)
{
strs[1] = strs[1].Substring(0, 3);
}
else
{
strs[1] = strs[1].PadRight(3, '0');
}
tbRate.Text = strs[0] + "." + strs[1];
}
private void tbRate_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar < '0' || e.KeyChar > '9')
{
e.Handled = true;
}
if (e.KeyChar == '\b') // '\b'表示退格鍵
{
e.Handled = false;
}
if (e.KeyChar == '.')
{
if (tbRate.Text.LastIndexOf('.') >= 0) // 只允許輸入一個小數點號
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
}