C# 验证整数
我想要整数中的小数点。如果小数点不存在,则显示错误消息 主席先生,以下代码写在用户控件文本框中。用户访问用户控件时给出的最大长度 以下代码限制用户输入最大长度后的小数点 请运行代码,先生C# 验证整数,c#,winforms,textbox,C#,Winforms,Textbox,我想要整数中的小数点。如果小数点不存在,则显示错误消息 主席先生,以下代码写在用户控件文本框中。用户访问用户控件时给出的最大长度 以下代码限制用户输入最大长度后的小数点 请运行代码,先生 public virtual int MaximumLength { get; set; } private void txtCurrency_KeyPress(object sender, KeyPressEventArgs e) { txtCurrency.MaxLen
public virtual int MaximumLength { get; set; }
private void txtCurrency_KeyPress(object sender, KeyPressEventArgs e)
{
txtCurrency.MaxLength = MaximumLength + 3;
int dotIndex = txtCurrency.Text.IndexOf('.');
if (e.KeyChar != (char)Keys.Back)
{
if (char.IsDigit(e.KeyChar))
{
if (dotIndex != -1 && dotIndex < txtCurrency.SelectionStart && txtCurrency.Text.Substring(dotIndex + 1).Length >= 2)
{
e.Handled = true;
}
else if (txtCurrency.Text.Length == MaximumLength)
{
if (e.KeyChar != '.')
{ e.Handled = true; }
}
}
else
{
e.Handled = e.KeyChar != '.' || dotIndex != -1 || txtCurrency.Text.Length == 0 || txtCurrency.SelectionStart + 2 < txtCurrency.Text.Length;
}
}`enter code here`
公共虚拟整数最大长度{get;set;}
私有void txtCurrency\u按键(对象发送方,按键事件参数e)
{
txtCurrency.MaxLength=最大长度+3;
int dotIndex=txtCurrency.Text.IndexOf('.');
if(e.KeyChar!=(char)Keys.Back)
{
if(字符IsDigit(e.KeyChar))
{
if(dotIndex!=-1&&dotIndex=2)
{
e、 已处理=正确;
}
else if(txtCurrency.Text.Length==最大长度)
{
如果(例如KeyChar!='.'))
{e.Handled=true;}
}
}
其他的
{
e、 Handled=e.KeyChar!='.| | dotIndex!=-1 | | txtCurrency.Text.Length==0 | | txtCurrency.SelectionStart+2
您可以使用
更新:
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
e.Handled = true;
if (e.KeyChar == '.'
&& (textBox2).Text.IndexOf('.') > -1) //Allow one decimal point
e.Handled = true;
}
太好了…你试过什么?我不知道…有什么想法吗?先生,我有点怀疑“我的价值”是什么?一个不应该用地板代替圆形吗?@SztupY(在这种情况下)没有什么区别似乎OP不熟悉一些硬编码的代码。但无论如何,我们的答案适合她的问题。我希望他能理解。先生,我想要在按键事件中。但是上面的代码不支持小数点。我只是尝试了。先生,您的回答对我很有帮助。先生。先生,我想向您展示我的代码。先生。这是怎么可能的先生。我正在使用用户控件。welcom对于StackOverflow,请努力学习并阅读
:D
private void textBox2_Validating(object sender, CancelEventArgs e)
{
Regex r = new Regex(@"^\d+.\d{0,1}$");
if (r.IsMatch(textBox2.Text))
{
MessageBox.Show("Okay");
}
else
{
e.Cancel = true;
MessageBox.Show("Error");
}
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
e.Handled = true;
if (e.KeyChar == '.'
&& (textBox2).Text.IndexOf('.') > -1) //Allow one decimal point
e.Handled = true;
}