限制TextBox只能输入数字,逗号,和删除 C#

限制TextBox只能输入数字,逗号,也允许删除
开始写了一种办法可以实现,但是我切换一种输入法之后又有问题了.
用JS和C#都可以.
还有textbox输入的时候第一个不允许为逗号,只能输入数字之后才能写逗号 ,
如果是html控件怎么写.晕

在TextBox的KeyPress事件添加下面代码:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//允许输入的字符
string AstrictChar = "0123456789,";

//「BackSpace」「Delete」后退键正常删除操作
if ((Keys)(e.KeyChar) == Keys.Back || (Keys)(e.KeyChar) == Keys.Delete)
{
return;
}
//「Ctrl+C」(3)「Ctrl+X」(24)特殊组合键正常
//「Ctrl+Z」(26) 撤消组合键正常
if ((e.KeyChar == 3) || (e.KeyChar == 24) || (e.KeyChar == 26))
{
return;
}

//允许输入的字符外,
if (AstrictChar.IndexOf(e.KeyChar.ToString()) == -1)
{
e.Handled = true;
return;
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-09-07
在textBox1中的TextChanged事件里添加如下代码
private void textBox1_TextChanged(object sender, System.EventArgs e)
{
if (this.textBox1.Text.Length>0)
{
if (this.textBox1.Text.Length==1)
{
if (this.textBox1.Text == ",")
{
this.textBox1.Text = "";
this.textBox1.Focus();
return;//首字是 , 时返回
}
else
{
try
{
Int32.Parse(this.textBox1.Text);
}
catch
{
this.textBox1.Text = "";
this.textBox1.Focus();
return;//首字非数字时返回
}
}
}
else
{
try
{
Int32.Parse(this.textBox1.Text.Replace(",",""));
}
catch
{
this.textBox1.Text = "";
this.textBox1.Focus();
return;//替换掉 , 后字符串转换成数字失败时返回
}
}
}
}
第2个回答  2009-09-07
切换输入法,中文逗号和英文的不一样,加上处理不就行了,或者把你写的贴出来,给你改改
第3个回答  2009-09-07
JS直接监视按键动作,如果是指定按键就输入。不是就返回
function document.onkeydown() //网页内按下回车触发
{
if(event.keyCode==?)
{
.................
}
}
第4个回答  2009-09-07
二楼的可行,但需要在程序里面用正则表达式验证