0

I'm writing a NumberTextbox, which extends the standard Textbox class of Winforms. The class includes the following override for the Text property:

    [DefaultValue("")]
    public override string Text
    {
        get
        {
            return base.Text;
        }

        set
        {
            if (!IsNumber(value))
                throw new FormatException();
            base.Text = value;
        }
    }

The constructor does explicitly insert an empty string into the Text property. When I try to insert this textbox into a form using the designer, I get a FormatException. Replacing the throw line with a return; fixes the issue, but that seems to me to be wrong. Is there any better solution to this issue? Note that the IsNumber method does return a true for the empty string.

user3745785
  • 87
  • 1
  • 8
  • please add `IsNumber` implementation to the question – styx Dec 03 '17 at 08:32
  • You can consider reading this question on [how to make number only textbox](https://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers) – lamandy Dec 03 '17 at 08:36
  • You might want to check the answers [here](https://stackoverflow.com/questions/1166226) to cover for being in design mode (the accepted answer might not work for your scenario, so be aware of that, the other answers provide solutions to different contexts). Alternatively set the `base.Text` in your constructor instead of the `Text` property. – rene Dec 03 '17 at 10:08

1 Answers1

0

Not sure why your IsNumber method not working properly in design mode. The simple way to address this is to not call the method if you are in design mode...

        set
        {
            if (!DesignMode && !IsNumber(value))
                throw new FormatException();
            base.Text = value;
        }

The designer works in mysterious ways its wonders to perform. So occasionally you need to test for design mode to keep it working in my experience.

AQuirky
  • 4,691
  • 2
  • 32
  • 51