ReadOnly CheckedListBox

00shoe

Member
Joined
Oct 12, 2006
Messages
20
Programming Experience
3-5
Hey All,

Hopefully I'm posting this in the right thread (my apologies if it isn't).

I would like to know if it is possible to create a ReadOnly CheckedListBox?

So the user can still select any items on the list, but cannot check and uncheck any items.

Thanks.
 
Last edited:
Inherit the CheckedListBox class and add your own property:
VB.NET:
Public Class ReadOnlyCheckedListBox
    Inherits CheckedListBox

    Private _readOnly As Boolean = False

    <System.ComponentModel.Category("Behavior"), System.ComponentModel.DefaultValue(False)> _
    Public Property [ReadOnly]() As Boolean
        Get
            Return Me._readOnly
        End Get
        Set(ByVal value As Boolean)
            Me._readOnly = value
        End Set
    End Property

    Protected Overrides Sub OnItemCheck(ByVal ice As System.Windows.Forms.ItemCheckEventArgs)
        If Me.ReadOnly Then
            'Do not change the value and do not raise the event.
            ice.NewValue = ice.CurrentValue
        Else
            MyBase.OnItemCheck(ice)
        End If
    End Sub

End Class
Note that you'll want to set the ReadOnly property to False at design time if you want to be able to check any items at the outset. You can then set it to True at the end of the form constructor or in the Load event handler so the user can't make any changes.
 
Thanks it is working perfectly! :)

Do you have good sites/books where I can read up about creating new properities? (because I don't really understand the code you wrote, and would like to make some more in the future).

Thanks.
 
Go to MSDN and read about properties. They're pretty simple. A property is a single entity that encompasses two methods: a getter and a setter. The Get method returns the value of the property while the Set method assigns a value to it. The advantage of using a property rather than a variable is that you can perform any operations you want within those methods. The advantage of using properties over regular methods is that from the outside it appears to be exactly like a simple variable.

Java doesn't have properties so a VB implementation of Java-style code would be:
VB.NET:
Private readOnly As Boolean

Public Function getReadOnly() As Boolean
    Return Me.readOnly
End Function

Public Sub setReadOnly(ByVal value As Boolean)
    Me.readOnly = value
End Sub
These methods are very simple but some getters and setters can be quite complex. One of the favourite operations to perform in a setter is to raise an event that indicates that that property value has changed.

Note also that you can omit the getter to make a WriteOnly property or omit the setter to make a ReadOnly property. WriteOnly properties are fairly rare but ReadOnly properties are very common.
 
Back
Top