Capturing keys in datagrid comboboxcolumn

scottyrs

Newcomer
Joined
Nov 12, 2004
Messages
5
I am trying to resolve a problem with keyboard handling for a Windows Forms application that consists of a number of datagrids. Adding and deleting records is allowed only with button actions. The datagrids contain combobox columns. Column navigation is by TAB/Shift-TAB and RIGHT/LEFT Arrows. I am trying to achieve keyboard control for the combobox columns as follows:

Press ENTER for first time in the combobox column drops the list (droppeddown=true), UP/DOWN Arrows navigates the list, press ENTER again closes the drop (droppeddown=false) and selects the value. I am able to get the combobox to drop on the first ENTER press, navigate UP/DOWN the list, but am having trouble with the second ENTER.

I have tried multiple configurations using variously KeyPress, KeyDown and KeyUp in my comboboxcolumn. As well I have added code to the combobox trapping various messages. Any help would be appreciated.

Here is a version of code for both the ComboBoxColumn and ComboBox that kind of works:

ComboBox Code:


Code:
Public Class NoKeyUpCombo 
Inherits CompletionCombo 
Private Const WM_KEYUP As Integer = 257 

Protected Overloads Overrides Function ProcessKeyMessage(ByRef m As Message) As Boolean 
Dim key As Keys = CType(CType(m.WParam.ToInt32, Integer), Keys) 

Select Case key 
Case Keys.Tab 
Return True 
Case Keys.Up, Keys.Down 
Return False 
Case Else 
Return MyBase.ProcessKeyMessage(m) 
End Select 
End Function 

Protected Overloads Overrides Function IsInputKey(ByVal key As Keys) As Boolean 
Select Case key 
Case Keys.Up, Keys.Down 
Return True 
End Select 
Return MyBase.IsInputKey(key) 
End Function

ComboBoxColumn Code:

Code:
Private _ColumnComboBox As NoKeyUpCombo

AddHandler _ColumnComboBox.KeyUp, AddressOf ComboBoxKeyUp 
AddHandler _ColumnComboBox.KeyDown, AddressOf ComboBoxKeyDown 


Private Sub ComboBoxKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) 
If e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Execute Or e.KeyCode = Keys.Return Then 
Dim cbx As NoKeyUpCombo = CType(sender, NoKeyUpCombo) 
cbx.SelectedIndex = _SelectedIndex 
Debug.WriteLine(_ColumnComboBox.SelectedIndex.ToString & "KeyDown-ENTER:" & _ColumnComboBox.Text) 
e.Handled = False 
End If 
End Sub 

Private Sub ComboBoxKeyUp(ByVal sender As Object, ByVal e As KeyEventArgs) 
Dim i As Integer 
If Not _ColumnComboBox.DroppedDown Then 
If e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Execute Or e.KeyCode = Keys.Return Then 
_ColumnComboBox.DroppedDown = True 
KeyStrokeProcessed = True 
_ColumnComboBox.Invalidate() 
_ColumnComboBox.Update() 
End If 
Else 
Select Case e.KeyCode 
Case Keys.Down 
i = _ColumnComboBox.SelectedIndex 
If _ColumnComboBox.Items.Count > i Then 
_SelectedIndex = i + 1 
_ColumnComboBox.SelectedIndex = _SelectedIndex 
_ColumnComboBox.Invalidate() 
_ColumnComboBox.Update() 
e.Handled = False 
Debug.WriteLine(_ColumnComboBox.SelectedIndex.ToString & "-Down:" & _ColumnComboBox.Text) 
End If 
Case Keys.Up 
i = _ColumnComboBox.SelectedIndex 
If i > 0 Then 
_SelectedIndex = i - 1 
_ColumnComboBox.SelectedIndex = _SelectedIndex 
_ColumnComboBox.Invalidate() 
_ColumnComboBox.Update() 
e.Handled = False 
Debug.WriteLine(_ColumnComboBox.SelectedIndex.ToString & "-Up:" & _ColumnComboBox.Text) 
End If 

Case Keys.Enter, Keys.Execute, Keys.Return 
If _ColumnComboBox.DroppedDown Then 
_ColumnComboBox.SelectedIndex = _SelectedIndex 
Debug.WriteLine(_SelectedIndex.ToString & ":*" & _ColumnComboBox.Text) 
_ColumnComboBox.DroppedDown = False 
KeyStrokeProcessed = False 
_ColumnComboBox.Invalidate() 
_ColumnComboBox.Update() 
'e.Handled = True 
Debug.WriteLine(_ColumnComboBox.SelectedIndex.ToString & "ENTER Press 2-New Value:" & _ColumnComboBox.Text) 
End If 
End Select 
'Dim cbx As NoKeyUpCombo = CType(sender, NoKeyUpCombo) 
'cbx.SelectedIndex = _SelectedIndex 
' Debug.WriteLine(_ColumnComboBox.SelectedIndex.ToString & "-dgcKeyPress:" & _ColumnComboBox.Text) 
Return 
End If 
End Sub
 
I am not sure why you need to look at the key events so much, but try this class and see if it helps.
'-------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System.Collections
Imports System.ComponentModel
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Data

Public Class DataGridComboBox
Inherits ComboBox
Public Sub New()
MyBase.New()
End Sub
Public isInEditOrNavigateMode As Boolean = True
End Class

Public Class DataGridComboBoxColumn 'DataGridComboBoxColumnStyle
Inherits DataGridColumnStyle

Public TextBox As New TextBox() ' Temp added by donnacha 17/11/04 to allow compilation with old appli code
Public BackGroundColor As Color ' ''
Public ReadOnly Property ComboBox() As ComboBox ' ''
Get
Try
Return Me.Combo
Catch ex As Exception
Finally
End Try
End Get
End Property
Private cm As CurrencyManager
Private iCurrentRow As Integer
'****************************************************
' UI constants
Private xMargin As Integer = 2
Private yMargin As Integer = 1
Private Combo As DataGridComboBox
Private _DisplayMember As String
Private _ValueMember As String
'
' Used to track editing state
'
Private OldVal As String = String.Empty
Private InEdit As Boolean = False
'
' Create a new column - DisplayMember, ValueMember
' Passed by ordinal
'
Public Sub New(ByRef DataSource As DataTable, _
ByVal DisplayMember As Integer, _
ByVal ValueMember As Integer)
Me.cm = Nothing '---------
Combo = New DataGridComboBox()
_DisplayMember = DataSource.Columns.Item(index:=DisplayMember).ToString
_ValueMember = DataSource.Columns.Item(index:=ValueMember).ToString
With Combo
.Visible = False
.DataSource = DataSource
.DisplayMember = _DisplayMember
.ValueMember = _ValueMember
End With
End Sub
'
' Create a new column - DisplayMember, ValueMember
' passed by string
'
Public Sub New(ByRef DataSource As DataTable, _
ByVal DisplayMember As String, _
ByVal ValueMember As String)
Me.cm = Nothing '---------
Combo = New DataGridComboBox()
With Combo
.Visible = False
.DataSource = DataSource
.DisplayMember = DisplayMember
.ValueMember = ValueMember
End With

End Sub
'------------------------------------------------------
' Methods overridden from DataGridColumnStyle
'------------------------------------------------------
' Abort Changes
'
Protected Overloads Overrides Sub Abort(ByVal RowNum As Integer)
Debug.WriteLine("Abort()")
RollBack()
HideComboBox()
EndEdit()
End Sub
'
' Commit Changes
'
Protected Overloads Overrides Function Commit(ByVal DataSource As CurrencyManager, _
ByVal RowNum As Integer) As Boolean
HideComboBox()
If Not InEdit Then
Return True
End If
Try
Dim Value As Object = Combo.SelectedValue
If NullText.Equals(Value) Then
Value = Convert.DBNull
End If
SetColumnValueAtRow(DataSource, RowNum, Value)
Catch e As Exception
RollBack()
Return False
End Try
EndEdit()
Return True
End Function
'
' Remove focus
'
Protected Overloads Overrides Sub ConcedeFocus()
Me.Commit(Me.cm, Me.iCurrentRow)
Combo.Visible = False
End Sub
'
' Edit Grid
'
Protected Overloads Overrides Sub Edit(ByVal Source As CurrencyManager, _
ByVal Rownum As Integer, _
ByVal Bounds As Rectangle, _
ByVal [ReadOnly] As Boolean, _
ByVal InstantText As String, _
ByVal CellIsVisible As Boolean)
Me.iCurrentRow = Rownum '----
Me.cm = Source '-----
'---------------------------
Combo.Text = String.Empty
Dim OriginalBounds As Rectangle = Bounds
OldVal = Combo.Text
If CellIsVisible Then
Bounds.Offset(xMargin, yMargin)
Bounds.Width -= xMargin * 2
Bounds.Height -= yMargin
Combo.Bounds = Bounds
Combo.Visible = True
Else
Combo.Bounds = OriginalBounds
Combo.Visible = False
End If
Combo.SelectedValue = GetText(GetColumnValueAtRow(Source, Rownum))
If Not InstantText Is Nothing Then
Combo.SelectedValue = InstantText
End If
Combo.RightToLeft = Me.DataGridTableStyle.DataGrid.RightToLeft
Combo.Focus()
If InstantText Is Nothing Then
Combo.SelectAll()
Else
Dim [End] As Integer = Combo.Text.Length
Combo.Select([End], 0)
End If
If Combo.Visible Then
DataGridTableStyle.DataGrid.Invalidate(OriginalBounds)
End If
InEdit = True
End Sub

Protected Overloads Overrides Function GetMinimumHeight() As Integer
'
' Set the minimum height to the height of the combobox
'
Return Combo.PreferredHeight + yMargin
End Function

Protected Overloads Overrides Function GetPreferredHeight(ByVal g As Graphics, _
ByVal Value As Object) As Integer
Debug.WriteLine("GetPreferredHeight()")
Dim NewLineIndex As Integer = 0
Dim NewLines As Integer = 0
Dim ValueString As String = Me.GetText(Value)
Do
While NewLineIndex <> -1
NewLineIndex = ValueString.IndexOf("r\n", NewLineIndex + 1)
NewLines += 1
End While
Loop
Return FontHeight * NewLines + yMargin
End Function

Protected Overloads Overrides Function GetPreferredSize(ByVal g As Graphics, _
ByVal Value As Object) As Size
Dim Extents As Size = Size.Ceiling(g.MeasureString(GetText(Value), _
Me.DataGridTableStyle.DataGrid.Font))
Extents.Width += xMargin * 2 + DataGridTableGridLineWidth
Extents.Height += yMargin
Return Extents
End Function


Protected Overloads Overrides Sub Paint(ByVal g As Graphics, _
ByVal Bounds As Rectangle, _
ByVal Source As CurrencyManager, _
ByVal RowNum As Integer)
Paint(g, Bounds, Source, RowNum, False)
End Sub

Protected Overloads Overrides Sub Paint(ByVal g As Graphics, _
ByVal Bounds As Rectangle, _
ByVal Source As CurrencyManager, _
ByVal RowNum As Integer, _
ByVal AlignToRight As Boolean)
Dim Text As String = GetText(GetColumnValueAtRow(Source, RowNum))
PaintText(g, Bounds, Text, AlignToRight)
End Sub

Protected Overloads Sub Paint(ByVal g As Graphics, _
ByVal Bounds As Rectangle, _
ByVal Source As CurrencyManager, _
ByVal RowNum As Integer, _
ByVal BackBrush As Brush, _
ByVal ForeBrush As Brush, _
ByVal AlignToRight As Boolean)
Dim Text As String = GetText(GetColumnValueAtRow(Source, RowNum))
PaintText(g, Bounds, Text, BackBrush, ForeBrush, AlignToRight)
End Sub

Protected Overloads Overrides Sub SetDataGridInColumn(ByVal Value As DataGrid)
MyBase.SetDataGridInColumn(Value)
If Not (Combo.Parent Is Value) Then
If Not (Combo.Parent Is Nothing) Then
Combo.Parent.Controls.Remove(Combo)
End If
End If
If Not (Value Is Nothing) Then Value.Controls.Add(Combo)
End Sub

Protected Overloads Overrides Sub UpdateUI(ByVal Source As CurrencyManager, _
ByVal RowNum As Integer, ByVal InstantText As String)
Combo.Text = GetText(GetColumnValueAtRow(Source, RowNum))
If Not (InstantText Is Nothing) Then
Combo.Text = InstantText
End If
End Sub
 
Here is the remainder of the class

'----------------------------------------------------------------------
' Helper Methods
'----------------------------------------------------------------------
Private ReadOnly Property DataGridTableGridLineWidth() As Integer
Get
If Me.DataGridTableStyle.GridLineStyle = DataGridLineStyle.Solid Then
Return 1
Else
Return 0
End If
End Get
End Property

Private Sub EndEdit()
InEdit = False
Invalidate()
End Sub

Private Function GetText(ByVal Value As Object) As String
If Value Is System.DBNull.Value Then Return NullText
If Not Value Is Nothing Then
Return Value.ToString
Else
Return String.Empty
End If
End Function

Private Sub HideComboBox()
If Combo.Focused Then
Me.DataGridTableStyle.DataGrid.Focus()
End If
Combo.Visible = False
End Sub

Private Sub RollBack()
Combo.Text = OldVal
End Sub

Private Sub PaintText(ByVal g As Graphics, _
ByVal Bounds As Rectangle, _
ByVal Text As String, _
ByVal AlignToRight As Boolean)

Dim BackBrush As Brush = New SolidBrush(Me.DataGridTableStyle.BackColor)
Dim ForeBrush As Brush = New SolidBrush(Me.DataGridTableStyle.ForeColor)
PaintText(g, Bounds, Text, BackBrush, ForeBrush, AlignToRight)
End Sub

Private Sub PaintText(ByVal g As Graphics, _
ByVal TextBounds As Rectangle, _
ByVal Text As String, _
ByVal BackBrush As Brush, _
ByVal ForeBrush As Brush, _
ByVal AlignToRight As Boolean)

Dim Rect As Rectangle = TextBounds
Dim RectF As RectangleF = RectF.op_Implicit(Rect) ' Convert to RectangleF
Dim Format As StringFormat = New StringFormat()

If AlignToRight Then
Format.FormatFlags = StringFormatFlags.DirectionRightToLeft
End If
Select Case Me.Alignment
Case Is = HorizontalAlignment.Left
Format.Alignment = StringAlignment.Near
Case Is = HorizontalAlignment.Right
Format.Alignment = StringAlignment.Far
Case Is = HorizontalAlignment.Center
Format.Alignment = StringAlignment.Center
End Select
Format.FormatFlags = Format.FormatFlags Or StringFormatFlags.NoWrap
g.FillRectangle(Brush:=BackBrush, Rect:=Rect)
Rect.Offset(0, yMargin)
Rect.Height -= yMargin
g.DrawString(Text, Me.DataGridTableStyle.DataGrid.Font, ForeBrush, RectF, Format)
Format.Dispose()
End Sub
End Class
 
Thanks for your reply. Your code is similar to what I am using. My problem lies with assigning specific keyboard navigation for both the grid and the comboboxcolumn (and inherited objects).
 
Back
Top