简体   繁体   中英

restrict combobox input zero by user

Is there any way to restrict combobox value as '0' where i have volume value divided by target value as my target value is combobox and gives me an error divide by zero.I tried this but not to luck.

private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar) && (e.KeyChar != '0'))
            {
                e.Handled = true;
            }

        }

Easy way to go would be handling the TextChanged event and reset it back to previous value. or as suggested in comments don't allow user to enter value just make him to select from a list(DropDownList style).

private string previousText = string.Empty;
private void comboBox1_TextChanged(object sender, EventArgs e)
{
    if (comboBox1.Text == "0")
    {
        comboBox1.Text = previousText;
    }

    previousText = comboBox1.Text;
}

I propose this solution since handling Key Events is a nightmare, you need to check previous values, Copy + Paste menus, Ctrl+ V shortcuts etc..

you can try this:

    private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsNumber(e.KeyChar)
            || (e.KeyChar == '0'
                && this.comboBox1.Text.Length == 0))
        {
            e.Handled = true;
        }
    }

If you do wish to use this event to block the entry of the zeroes then consider the following:

private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsNumber(e.KeyChar))
    {
        e.Handled = true;
        return;
    }

    if (e.KeyChar == '0')
    {
        if (comboBox1.Text == "")
        {
            e.Handled = true;
            return;
        }
        if (int.Parse(comboBox1.Text) == 0)
        {
            e.Handled = true;
            return;
        }
    }
}

The code could stand a little tidying, but hopefully it shows a simple method of blocking leading zeroes - which I think is what you were after. And, of course, the clauses can all be combined into a single IF once you've got the logic right.

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