C# Textbox to stop receiving after comma

Asked

Viewed 447 times

4

I need a textbox to stop receiving values after the comma, once it reaches 2 houses.

To simplify, think that the text has limit after the comma, but none before it.

Example:

Type the number 2.99. So, whenever the user tries to put a value after the 99 it should be locked. However it should still be possible to delete, delete, and insert values before the comma.

Current code:

public static void verificarCasasPosVirgula(object sender, KeyPressEventArgs e, String Texto)
{
    if(Texto.Contains(','))
    {
        int posicaoVirgula = Texto.IndexOf(',');
        String[] array = Texto.Split(',');

        if (array[1].Length > 1) 
        {

            if ((e.KeyChar == (char)Keys.Return || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Delete))
            {
                e.Handled = false;
            }
            else if(posicaoVirgula > -1)
            {
                e.Handled = true;
            }
        }
    }
}
  • What kind of application is?

  • Desktop, made in C#

  • windows Forms ?

  • This, done with windows Forms.

4 answers

1

Most of my code was purchased in a post here, the only thing I added was a line.

private void sua_TextBox1_KeyPress(object sender, KeyPressEventArgs e)
    {         
           if (e.KeyChar == '.' || e.KeyChar == ',')
            {
                e.KeyChar = ',';

                if (sua_TextBox1.Text.Contains(","))
                {
                    e.Handled = true;                       
                }
                sua_TextBox1.MaxLength = sua_TextBox1.TextLength +3;
            }

            else if (!char.IsNumber(e.KeyChar) && !(e.KeyChar == (char)Keys.Back))
            {
                e.Handled = true;                   
            }               
    }

1

Good afternoon

Try to give a tryparse in value, so will not accept letters and not two commas.

To delete the value check if the e.KeyChar = (char)8 (Backspace)

Check the cursor position and validate whether the character is being inserted before or after the comma

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    double value = 0;
    if (!double.TryParse(textBox1.Text + e.KeyChar.ToString(), out value) && !char.IsControl(e.KeyChar))
    {
        e.Handled = true;
    }
    if (e.KeyChar == (char)8)
    {
        return;
    }


    Char separator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator[0];
    Int32 indexSeparator = textBox1.Text.IndexOf(separator);
    String[] array = textBox1.Text.Split(separator);

    if (textBox1.SelectionStart > indexSeparator)
    {
        if (array.Length == 2)
        {
            if (array[1].Length >= 2)
                e.Handled = true;
        }
    }
}

I hope I’ve helped!

  • Good afternoon, using the code you gave me the entry will accept only 2 houses post comma, but when you have comma, I will not be able to edit before it.

  • I edited the answer. Try now..

0

To solve this problem dynamically, I suggest the following:

Creation of the Keypress event

//Validação de Input na textBox
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == '.')
        {
            e.KeyChar = ',';
        }

        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != ','))
        {
            e.Handled = true;
        }

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

        if (Regex.IsMatch((sender as TextBox).Text, @"\,\d\d") && e.KeyChar != 8) //Necessario adicionar "using System.Text.RegularExpressions;"
        {
            e.Handled = true;
        }
    }

Also creating the Textchanged event

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        //Caso seja inserido uma "," no inicio coloca "0,"
        if ((sender as TextBox).Text == ",")
        {
            (sender as TextBox).Text = "0,";
            (sender as TextBox).SelectionStart = (sender as TextBox).Text.Length + 1;
        }
    }

0

I managed to solve the problem, follow the solution:

    public static void verificarCasasPosVirgula(object sender, KeyPressEventArgs e, String Texto)
    {

        if(Texto.Contains(',')){
            int posicaoVirgula = Texto.IndexOf(',');
            TextBoxDVJ txt = (TextBoxDVJ)sender;
            int cursor = Texto.LastIndexOf(e.KeyChar.ToString());
            String[] array = Texto.Split(',');


        if (array[1].Length > 1) {

            if ((e.KeyChar == (char)Keys.Return || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Delete))
            {
                e.Handled = false;
            }
            else if(txt.SelectionStart > posicaoVirgula) //Aqui está o truque
            {
                e.Handled = true;


            }

        }

        }

    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.