Programmatic selection of the first character when entering a DataGridViewTextBoxCell
Within a TextBox, it is possible to select only a part of a text with the help of the properties SelectionStart and SelectionLength. I also needed the possibility of a targeted selection of text for a TextBox within a DataGridViewTextBoxCell.
I tried it with the event EditingControlShowing but it wasn't working. My selection was reset each time. So, handling the EditingControlShowing works for most properties but not for the selection. The next approach I tried was to use the the DataGridView.BeginEdit methods. But the BeginEdit method accepts only one parameter which is either select all or nothing – this is not what I wanted.
At the end, the Ice Tea Group gave me the problem-solving hint. The selection occurs on both sides, client and server, which means that you cannot perform the simultaneous selection in the same request/response cycle. You should use the Appear event.
With this information I could make it work. So now, I want to share the solution with you.
First, create a new Wisej 2.0 project and add a DataGridView control using the (new) Designer.
Now add an event handler to the Load event of the form and to the EditingControlShowing event of the DataGridView control. The default EditMode of the grid is EditOnKeystrokeOrF2. Change it to EditOnEnter, so you can better see the automatic selection of the first character later.
Set the RowCount to 5 in the Load handler. This will add 5 rows to your grid. Fill the second column with dummy values.
In the EditingControlShowing, add a handler to the Appear event of the TextBox control, which will be created when entering the EditMode of the cell.
Now you can set the SelectionStart and SelectionLength for the TextBox in the Editor_Appear handler.
You can start the application and move through the table cells with tab. When entering the second column, only the first character will be selected.
Download the example code: DGVCellSelection example code (Zip file)