简体   繁体   中英

textbox validation for allow one “ . ” value c#

I want textbox validation for allowing only one . value and only numbers. Means my textbox value should take only numerics and one . value. Value should be like 123.50. I am using a code for adding .oo or .50 value at end of my value. My code is

double x;
double.TryParse(tb.Text, out x);
tb.Text = x.ToString(".00");

It is taking all the keys from keyboard, but I want to take only numbers and one . value.

Add a Control.KeyPress event handler for your textbox.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar))  //bypass control keys
    {
        int dotIndex = textBox1.Text.IndexOf('.');
        if (char.IsDigit(e.KeyChar))     //ensure it's a digit
        {   //we cannot accept another digit if
            if (dotIndex != -1 &&  //there is already a dot and
                //dot is to the left from the cursor position and
                dotIndex < textBox1.SelectionStart &&
                //there're already 2 symbols to the right from the dot
                textBox1.Text.Substring(dotIndex + 1).Length >= 2)
            {
                e.Handled = true;
            }
        }
        else //we cannot accept this char if
            e.Handled = e.KeyChar != '.' || //it's not a dot or
                        //there is already a dot in the text or
                        dotIndex != -1 ||   
                        //text is empty or
                        textBox1.Text.Length == 0 || 
                        //there are more than 2 symbols from cursor position
                        //to the end of the text
                        textBox1.SelectionStart + 2 < textBox1.Text.Length;
    }
}

You may do it through designer or in your constructor like this:

public Form1()
{
    InitializeComponent();
    //..other initialization
    textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
}

I have also added several checks to ensure, that you could insert digits not only in the end of the text, but in any position. Same with a dot. It controls that you have not more than 2 digits to the right from the dot. I've used TextBox.SelectionStart Property to get the position of the cursor in the textbox. Check this thread for more info about that: How do I find the position of a cursor in a text box?

try this one

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 == '.'
            && textBox1.Text.IndexOf('.') > -1)
            e.Handled = true;
    }

Simplly in keyPress event of your textBox you could do this ...

        e.Handled = !char.IsDigit(e.KeyChar)&&(e.KeyChar != '.') && !char.IsControl(e.KeyChar);
        if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
        {
            e.Handled = true;
        }

try this code and just replace what you want input type 'validinpu' string.

try
{
    short charCode = (short)Strings.Asc(e.KeyChar);
    string validinput = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789 .";
    if (Strings.InStr(validamt, Conversions.ToString(Strings.Chr(charCode)), Microsoft.VisualBasic.CompareMethod.Binary) == 0)
    {
        charCode = 0;
    }
    if (charCode == 0)
    {
        e.Handled = true;
    }
}

Another example ,

 private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
    {
         // To disallow typing in the beginning writing
        if (txtPrice.Text.Length == 0)
        {
            if (e.KeyChar == '.')
            {
                e.Handled = true;
            }
        }
        if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != 46)
        {
            e.Handled = true;
        }
        if (e.KeyChar == '.' && txtPrice.Text.IndexOf('.') > -1)
        {
            e.Handled = true;
        }
    }

Also try this short one

e.Handled = (!(e.KeyChar == (char)Keys.Back || e.KeyChar == '.')); //allow  dot and Backspace
e.Handled = (e.KeyChar == '.' && TextBox1.Text.Contains(".")); //allow only one dot

this example only allow one dot and backspace

 if (textBox.Text!="")
        {
            string txt = textBox.Text;
            if (e.KeyChar.ToString().Any(Char.IsNumber) || e.KeyChar == '.')
            {
                textBox.Text = rate;
            }
            else
            {
                MessageBox.Show("Number Only", "Warning");
                textBox.Text = "";
            }
        }

My tested code

if(e.KeyChar.Equals('\b'))
 {
  e.Handled = false;
 }
else
 if (!char.IsControl(e.KeyChar)
           && !char.IsDigit(e.KeyChar)
           && e.KeyChar != '.')
  {
        e.Handled = true;
  }
 else
    // only allow one decimal point
    if (e.KeyChar == '.'
        && textBox1.Text.IndexOf('.') > -1)
  {        
    e.Handled = true;  
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM