When manipulating controls on a .NET windows form which of the following is best practice and why?
//Hide control from user and stop control form being useable
oControl.Enabled = false;
oControl.Visible = false;
or
//Hide control from user and stop control form being useable
oControl.Visible = false;
I've been using the first case and always disabling a control when hiding it, but I've been told that this is wrong and that I should only be hiding it. I seem to vaguely remember reading somewhere that if you don't specifically dissable a control that it can continue to interact with the user.
Any enlightenment would be apreciated.
Whether you will need to set Enabled = false
when hiding a control depends on the control in question, and what kind of interaction it offers. For many controls (such as a Button
or a CheckBox
), setting Visible = false
will suffice to prevent any interaction between the user and the control.
But some controls (it seems to be especially those offering a Shortcut key property), will still offer user interaction when not visible. For instance the ToolStripMenuItem
(and the "older" MenuItem
) will still have their Click
event invoked when the shortcut key is pressed, regardless of Visible
being true
or false
.
Setting Enabled = false
will prevent invoking the Click
event through shortcut keys in those cases. From that point of view, I would not advice against setting Enabled = false
when hiding a control in a WinForms application.
Enabled
refers to whether or not the user can interact with the control (i.e. if the control is grayed out or not)
Visible
refers to wehether or not the control is displayed (usually if this is false the control is not rendered at all, however not all the time apparently - see the comments of this post).
If the control is not rendered then the value of the enabled propery will have no impact.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With