Keypress of DataGridViewCell

styxke

Member
Joined
May 18, 2006
Messages
16
Programming Experience
5-10
Hi,

I'm trying to catch the KeyPress event in a datagridviewcell.
Here is some code:
VB.NET:
Public Class CommonDataGridViewTextBoxColumn
  Inherits DataGridViewTextBoxColumn

  Private _uppercase As Boolean

  Public Property Uppercase() As Boolean
    Get
      Return _uppercase
    End Get
    Set(ByVal value As Boolean)
      _uppercase = value
    End Set
  End Property

End Class

Public Class CommonDataGridViewTextBoxCell
  Inherits DataGridViewTextBoxCell

  Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs, ByVal rowIndex As Integer)
    MyBase.OnKeyPress(e, rowIndex)
    If CType(Me.OwningColumn, CommonDataGridViewTextBoxColumn).Uppercase Then
      e.KeyChar = Char.ToUpper(e.KeyChar, My.Computer.Info.InstalledUICulture)
    End If
  End Sub

End Class
The InitializeComponent of CommonDataGridViewTextBoxColumn:
VB.NET:
Me.CellTemplate = New CommonDataGridViewTextBoxCell
In my datagridview I set the columntype to CommonDataGridViewTextBoxColumn ... but when I press a key in the cell the keypress isn't fired.

Thanks in advance for any help.
 
If that's all the code you've written then your cell class isn't even being used. You have to write much more code than that to get the column class to use the cell class. Plus that is not how you should be handling that sort of thing anyway. What you should do is propagate the CharacterCasing property of your own editing control class through the cell class to the column class. believe me, I know how this stuff works because I've been creating my own TextBox, MaskedTextBox, NumericUpDown and DateTimePicker columns lately. Here's a couple of links that will show you how to handle this sort of thing:

http://msdn2.microsoft.com/en-us/library/7tas5c80.aspx
http://www.windowsforms.net/WhidbeyFeatures/default.aspx?PageID=2&ItemID=13&Cat=Controls
 
Thanks again for the links. These are helpful!

Do you maybe have a simple example how to propagate such property ?
 
Last edited:
The first link is as simple as examples of this sort of thing get. If you check out the NumericUpDown column from the second link you'll see just how complex you can get if you want to do a really thorough job. A couple of things that you absolutely must remember is you need to override the Clone method for your column and cell classes or else they just won't work, and you also need to write the column constructor such that it will use your cell class as its CellTemplate, otherwise it will just use the default cell type for the class it inherits.
 
Thanks for all your help.
I finally got it to work ... I forgot one line in InitializeEditingControl which turned it all upside down ...:)
 
Back
Top