Search code examples
c#winformscombobox

Only allow integers in a winform combobox


I am currently working on programming a photo editor with c# and I am currently designing the ability to allow the pen tool to change sizes. It works flawlessly except for one problem. Here is some background information: So inside a combobox that I have, there are 10 Items, each are numbers 1 - 10. If I select one, or directly type some number into the combobox, it will set the pen size to that. The problem is, if I type a letter it gives me a

IndexOutOfRangeException

.

Is there a way I can make it so the combobox only accepts integers and floats? Basically what I mean is if I push 3, the pen size will change to 3. But if I push H, it does nothing.


Solution

  • You can do either of the two options. The first option is restrict the user to type in the comboobx by Disable typing. This can be achieved by giving this code in the page_load

     comboBox1.DropDownStyle to ComboBoxStyle.DropDownList
    

    or Access the value like the following:

           if (int.TryParse(comboBox1.Text, out BreshSize))
            {
                // Proceed
            }
            else 
            { 
            //Show errror message
            }