Search code examples
c#.netwinformslistviewtextbox

Put TextBox into editing mode programmatically


I am modifying a multi-column listview in order to be able to edit its cells. When the user clicks into an already selected cell, a TextBox shall be shown and by subsequently typing a text, the cell content shall be changed (after confirmation with enter of course).

But when I use the method below, the TextBox appears, but it does not seem to be focused, and so does not get into editing mode: the caret is not shown and typing with the keyboard does not change the Text field of the TextBox. Only after clicking into the TextBox a second time the caret appears.

public void startEditing(TableIndex cell)
{
    editedCell = cell;
    editTextBox.Bounds = CellBounds(cell);
    editTextBox.Text = this[editedCell.RowIndex, editedCell.ColumnIndex];
    editTextBox.Show();
    editTextBox.Focus();
}

How can I put the TextBox into editing mode programmatically?

Before anyone bothers to suggest: no, I don't want to switch to DataGridView and such. Everytime I have tried to use them, they were so slow it made me feel like I was emulating Windows on a Raspberry Pi.


Solution

  • OP: I am calling it in ListView.OnMouseDown.

    Show and focus the editor control in OnMouseUp.

    The ListView handles WM_LBUTTONDOWN and pushes a focus which means after processing your OnMouseDown code, the ListView will get the focus.

    The easiest fix for you to make the TextBox get the focus, would be showing the TextBox and focusing in in OnMouseUp.