VB.NET  •  Create a Combo Box Column

Listing 1. You can make a DataGrid column show and hide a combo box, instead of the classic textbox, by deriving from the DataGridTextBoxColumn class to manage events such as Edit and Leave.

Public Class DataGridComboBoxColumn
   Inherits DataGridTextBoxColumn

   Public MyCombo As ComboBox

   Public Sub New()
      MyBase.New()

      MyCombo = New ComboBox
      AddHandler MyCombo.Leave, New EventHandler( _
         AddressOf LeaveComboBox)

   End Sub

   Protected Overloads Overrides Sub Edit(ByVal _
      source As CurrencyManager, ByVal rowNum _
      As Integer, ByVal bounds As Rectangle, _
      ByVal readOnly1 As Boolean, ByVal _
      instantText As String, ByVal cellIsVisible As Boolean)
      MyBase.Edit(source, rowNum, bounds, _
         readOnly1, instantText, cellIsVisible)

      MyCombo.Parent = Me.TextBox.Parent
      MyCombo.Location = Me.TextBox.Location
      MyCombo.Size = New Size(Me.TextBox.Size.Width, _
         MyCombo.Size.Height)
      MyCombo.Text = Me.TextBox.Text
      Me.TextBox.Visible = False
      MyCombo.Visible = True
      MyCombo.BringToFront()
      MyCombo.Focus()

   End Sub

   Private Sub LeaveComboBox(ByVal sender _
      As Object, ByVal e As EventArgs)
      MyCombo.Hide()
   End Sub
End Class