Thursday, May 8, 2008

How to make a ComboBox Read Only

Issue: ComboBox Control does NOT have a ReadOnly Property
Level: Intermediate
Knowledge Required: To understand the following solution you must have the knowledge of:


  • ComboBox

  • AddHandler

  • RemoveHandler



Description:
Sometimes it is required to have the ComboBox control to be Read Only i.e. it should just be like a TextBox, from which we can Select and Copy Text but cannot change value and cannot open Drop Down List. For this purpose you can call the following public method ToggleComobBoxReadonly.

For Example:

' This will make the comobbox readonly
ToggleComobBoxReadonly(Me.ComboBox1, True)




Public Sub ToggleComboBoxReadonly(ByRef cmbToUse As ComboBox, ByVal bValue As Boolean)
If bValue Then
Dim intHeight As Integer
intHeight = cmbToUse.Height
cmbToUse.Tag = cmbToUse.DropDownStyle
cmbToUse.DropDownStyle = ComboBoxStyle.Simple
cmbToUse.Height = intHeight
AddHandler cmbToUse.KeyDown, AddressOf Common.ComboBox_KeyDown
AddHandler cmbToUse.KeyPress, AddressOf Common.ComboBox_KeyPress
Else
If cmbToUse.Tag IsNot Nothing Then
cmbToUse.DropDownStyle = cmbToUse.Tag
RemoveHandler cmbToUse.KeyDown, AddressOf Common.ComboBox_KeyDown
RemoveHandler cmbToUse.KeyPress, AddressOf Common.ComboBox_KeyPress
End If
End If
End Sub

Private Sub ComboBox_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
Select Case e.KeyCode
Case Keys.Delete, Keys.Down, Keys.Up, Keys.PageDown, Keys.PageUp
e.Handled = True
End Select
End Sub

Private Sub ComboBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
e.Handled = True
End Sub

6 comments:

Kip Dole said...

Hi,
If I could get this work I would be very happy. These lines give me an error.

Thanks,

Kip

nassosk said...

You need to append the line feeds between statements. Its a common error on some websites. Just paste, read the code backwards and press enter as needed.

nassosk said...

Excellent, excellent code.

Anonymous said...

it is working !
thanks

for VB 2008, small changes:

common.ComboBox_KeyDown
to
Me.ComboBox_KeyDown


regards
aSAPlover

Rachat de credit said...

Thanks a lot it was a great guide, now to make a combobox read only is very easy with the help of your information. Thanks

Anonymous said...

This is the best solution I have found on the Internet.
Thanks.