Stranger Stranger - 1 month ago 15
C# Question

Prevent continue Typing in TextBox When a Char is Entered

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;

Answer

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;
    }
}