Disable Property

  • Thread starter Thread starter Paul
  • Start date Start date
P

Paul

I have two properties in a user control of mine. One is FormatValue
which the user can select Currency, Number, etc. The second is
NumberOfDecimalPlaces. When the user chooses Currency, I want to
disable the NumberOfDecimalPlaces property so that it cannot be
changed. How do I do this.
 
I have two properties in a user control of mine. One is FormatValue
which the user can select Currency, Number, etc. The second is
NumberOfDecimalPlaces. When the user chooses Currency, I want to
disable the NumberOfDecimalPlaces property so that it cannot be
changed. How do I do this.

You can't "hide" the property ... but you can throw an exception if the
user attempts to access the property if the first value is set.

Otherwise just ignore the second property in your logic.

Or make both properties read only... and provide a method to set the
values...
 
You can't "hide" the property ... but you can throw an exception if the
user attempts to access the property if the first value is set.

Otherwise just ignore the second property in your logic.

Or make both properties read only... and provide a method to set the
values...
You can't "hide" the property ... but you can throw an exception if the
user attempts to access the property if the first value is set.
Or make both properties read only... and provide a method to set the
values..

I usually go with a readonly property and add a Change method and a
boolean TryChange function for setting the property's value. The
TryChange return a boolean indicating whether the attempt was
successful. And since it uses an internal indicator of whether the
property can be changed it prevents the performance hit of throwing
and catching an exception (though in this case it would be
negligible). Here's an example for the OP:

' Typed in Message

Private allowedToChange As Boolean = False

Private _FormatValue As FormatValues = FormatValues.General
Public Property FormatValue() As FormatValues
Get
Return _FormatValue
End Get
Set (ByVal value as FormatValues)
_FormatValue
allowedToChange = (value = FormatValues.Currency)
End Get
End Property

Private _NumberOfDecimalPlaces As Int32 = 0
Public ReadOnly Property NumberOfDecimalPlaces() As Int32
Get
Return _NumberOfDecimalPlaces
End Get
End Property

Public Sub ChangeNumberOfDecimalPlaces(ByVal value As Int32)
If allowedToChange Then
_NumberOfDecimalPlaces = value
Else
Throw New Exception()
End If
End Sub

Public Function TryChangeNumberOfDecimalPlaces(ByVal value As Int32)
As Boolean
If allowedToChange Then
_NumberOfDecimalPlaces = value
Return True
Else
Return False
End If
End Function

Hope that helps.

Thanks,

Seth Rowe
 
Back
Top