验证不使用c#.net在文本框中输入点作为第一个字符 [英] validate not to enter dot as first character in textbox using c#.net

查看:96
本文介绍了验证不使用c#.net在文本框中输入点作为第一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想在文本框中输入点作为第一个字符
我尝试使用此代码...但是问题是它没有在整个文本框中输入点...
请解决这个

hi i want not to enter dot as first character in textbox
i tried with this code...but the problem is it is not entering dot in entire text box...
pls solve this

if (char.IsDigit(e.KeyChar) || e.KeyChar == 8 || e.KeyChar != '.')
                    {
                        e.Handled = false;
                    }
                    else
                    {
                        e.Handled = true;
                    }

推荐答案

两个选项:

请改用NumericUpDown. NumericUpDown为您进行过滤,这很好.当然,它还使您的用户能够按键盘上的向上和向下箭头来增加和减少当前值.

处理适当的键盘事件,以防止除数字输入之外的任何操作.我已经在标准TextBox上成功使用了这两个事件处理程序:

Two options:

Use a NumericUpDown instead. NumericUpDown does the filtering for you, which is nice. Of course it also gives your users the ability to hit the up and down arrows on the keyboard to increment and decrement the current value.

Handle the appropriate keyboard events to prevent anything but numeric input. I''ve had success with this two event handlers on a standard TextBox:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) 
        && !char.IsDigit(e.KeyChar) 
        && e.KeyChar != '.')
    {
        e.Handled = true;
    }

    // only allow one decimal point
    if (e.KeyChar == '.' 
        && (sender as TextBox).Text.IndexOf('.') > -1)
    {
        e.Handled = true;
    }
}


如果您的文本框不允许小数位,则可以删除对.''的检查(以及随后对多个检查的检查.).如果您的文本框应允许使用负值,也可以添加对-"的检查.


You can remove the check for ''.'' (and the subsequent check for more than one ''.'') if your TextBox shouldn''t allow decimal places. You could also add a check for ''-'' if your TextBox should allow negative values.


用作
if (e.KeyChar == '.')
           {
               if(textBox1.TextLength<1)
               e.Handled = true;
           }
           else
           {
               e.Handled = false;
           }


TextBox textbox = sender as TexBox;
while(textbox.Text.StartsWith("."))
{
   textbox.Text = textbox.Text.Remove(0, 1);
}


这篇关于验证不使用c#.net在文本框中输入点作为第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆