0

I have a textbox which user should type a price in it. I need to prevent continue typing if price starts with 0. For example user can not type "000" or "00009".

I tried this on KeyPress, but nothing!

if (txt.Text.StartsWith("0"))
       return; Or e.Handeled = true;
Inside Man
  • 4,194
  • 12
  • 59
  • 119
  • 1
    Refusing to allow any typing when the price starts with 0 seems like a poor user experience - notably, they may want to type a backspace to *remove* the character if they entered it in error. A softer approach that highlights the text box and refuses to submit the entire form, whilst allowing edits/corrections would usually be preferred. – Damien_The_Unbeliever Nov 07 '16 at 07:54
  • Yes User can backspace and delete, but if it starts with 0 it can not type another char. – Inside Man Nov 07 '16 at 07:55
  • Should it be `e.Handeled = true`? [Reference](http://stackoverflow.com/a/2591284/1050927), and you may need to check user input `numeric` instead of control character (backspace, delete...) – Prisoner Nov 07 '16 at 08:05

3 Answers3

2

try this:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    //only allow digit and (.) and backspace
    if ((e.KeyChar < '0' || e.KeyChar > '9') && e.KeyChar != '\b' && e.KeyChar != '.')
    {
        e.Handled = true;
    }

    var txt = sender as TextBox;

    //only allow one dot
    if (txt.Text.Contains('.') && e.KeyChar == (int)'.')
    {
        e.Handled = true;
    }

    //if 0, only allow 0.xxxx
    if (txt.Text.StartsWith("0")
        && !txt.Text.StartsWith("0.")
        && e.KeyChar != '\b'
        && e.KeyChar != (int)'.')
    {
        e.Handled = true;
    }
}
Brian Holsen
  • 350
  • 3
  • 10
0

You could use the TextChanged-event for this.

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (this.textBox1.Text == "0") this.textBox1.Text = "";
}

This will only work, if the TextBox is empty on startup.

Wudge
  • 357
  • 1
  • 6
  • 14
0

I solved it Myself:

private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
    if (txtPrice.Text.StartsWith("0") && !char.IsControl(e.KeyChar))
    {
        e.Handled = true;
        return;
    }
}
Inside Man
  • 4,194
  • 12
  • 59
  • 119