c# - Why does custom WinForms control not adhere to properties set in constructor when drawn? -
i have custom text box control inherits system.windows.forms.textbox
.
basically set automatically checks whether value entered number every time text changes. sample code:
public class mytextbox : textbox { public mytextbox() : base() { base.textchanged += mytextbox_textchanged; base.backcolor = color.white; base.forecolor = color.black; } private void mytextbox_textchanged(object sender, eventargs e) { try { int.parse(base.text); base.backcolor = color.white; base.forecolor = color.black; } catch(formatexception) { base.backcolor = color.red; base.forecolor = color.white; } } }
as indicated above, have default background , foreground white
, black
respectively, winforms designer draws component having red background, , comes way when launch program well. when start typing numbers in, however, change black/white , otherwise behaves expected.
but why control seem override properties set in constructor? when control drawn, text isn't changed... or it?
when dropped control onto form, current properties saved form designer.
this includes things like:
- forecolor
- backcolor
- text
when construct form, these properties set control.
in constructor of control set background color white, don't change text, text property stays empty string.
this empty string cannot parsed have 2 possible scenarios:
- backcolor set form designer code before text, in case event handler textchanged wins. since text empty string, cannot parsed, background color turns red though white short while
- the opposite happens, text set, parse fails, background color set red, , form designer sets saved background color white.
control properties set in alphabetical order (if i'm not mistaken) first scenario 1 see.
in short, got couple of ways handle this:
- decide if empty string legal, though possibly default value (null perhaps?)
- make sure constructor of control assigns text legal parsable integer value (
0
comes mind)
Comments
Post a Comment