Articles in this section
Category / Section

How to put a cell in overstrike mode in WinForms GridControl?

1 min read

Overstrike textbox cell

Enabling overstrike means to replace the existing characters with a new character as you type in a cell. The idea of doing this is to select one character when a key is pressed and ignoring the backspace key.

Solution

This can be achieved by using the TextBox.SelectionLength property of the GridTextBoxCellRenderer in the CurrentCellKeyPress event. The Backspace key can optionally be translated to the Left Arrow key in the CurrentCellKeyDown event when you want the Backspace to move to the left without deleting characters.

C#

//Hooking the Events in the Form_Load.
this.gridControl1.CurrentCellKeyPress += gridControl1_CurrentCellKeyPress;
this.gridControl1.CurrentCellKeyDown += gridControl1_CurrentCellKeyDown;
void gridControl1_CurrentCellKeyPress(object sender, KeyPressEventArgs e)
{
    GridTextBoxCellRenderer cr = this.gridControl1.CurrentCell.Renderer as GridTextBoxCellRenderer;
    if (e.KeyChar != Convert.ToChar(Keys.Back) && cr.TextBox.SelectionLength == 0)
    {
        //Programatically selecting One char.
        cr.TextBox.SelectionLength = 1;
    }
}
void gridControl1_CurrentCellKeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Back)
    {
        //Translating the Backspace key to the left arrow key.
        SendKeys.Send("{LEFT}");
        e.Handled = true;
    }
}

VB

'Hooking the Events in the Form_Load.
Me.gridControl1.CurrentCellKeyPress += gridControl1_CurrentCellKeyPress
Me.gridControl1.CurrentCellKeyDown += gridControl1_CurrentCellKeyDown
Private Sub gridControl1_CurrentCellKeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
    Dim cr As GridTextBoxCellRenderer = TryCast(Me.gridControl1.CurrentCell.Renderer, GridTextBoxCellRenderer)
    If e.KeyChar <> Convert.ToChar(Keys.Back) AndAlso cr.TextBox.SelectionLength = 0 Then
        'Programatically selecting One char.
        cr.TextBox.SelectionLength = 1
    End If
End Sub
Private Sub gridControl1_CurrentCellKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
    If e.KeyCode = Keys.Back Then
        'Translating the Backspace key to a left arrow key
        SendKeys.Send("{LEFT}")
        e.Handled = True
    End If
End Sub

Samples:

C#: OverStrikeTextBoxCell-CS.zip

VB: OverStrikeTextBoxCell-VB.zip

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied