Search code examples
c#visual-studiowinformstextbox

C# TextBox allow minus sign (-) only in the beginning of string


Sorry if this is a really basic question but I'm new to C# and it's my first windows form app.

In the code below my TextBox only accepts a decimal point ",", a minus sign "-", digits, and it also accepts the input of the delete and backspace keys (correct me if I'm wrong). So I can input and delete numbers like:

-12.31
-.31

The problem is I can also input something like:

12-

Is there a way to only input "-" if its the first character of the string? I tried google and I tried to come up with something but nothing seems to work.

And thank you for your time.

private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsDigit(e.KeyChar) && (e.KeyChar != ',') && (e.KeyChar != '-') && (e.KeyChar != (char)8))
        {
            e.Handled = true;
        }
        if ((e.KeyChar == ',') && ((sender as TextBox).Text.IndexOf(',') > -1))
        {
            e.Handled = true;
        }

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

Solution

  • You can check where the cursor is by using SelectionStart:

    var textBox = (TextBox)sender;
    
    if (e.KeyChar == '-' && (textBox.SelectionStart !=0 || textBox.Text.Contains("-"))) 
    {
      e.Handled = true;
    }