How to place the cursor at the beginning of the text when editing a DataGridView cell programmatically, when the user starts editing the cell text?

I am using a DataGridView that gets data from a DataTable to edit some amount of data. Everything looks fine, but there are some inconveniences. When the user starts editing a cell, the text of that cell automatically becomes selected, and the cursor moves to the end of the cell text. I want to place the cursor (carriage) at the beginning of the text when editing the cell programmatically, when the user starts editing the cell text. I tried:

private void gridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { DataGridViewTextBoxEditingControl dText = (DataGridViewTextBoxEditingControl)e.Control; dText.Select(0, 0); } 

This does not work. I also tried to deselect the text in CellBeginEdit - there is no result either.

+4
source share
1 answer

I would expect what you did to work. But a DataGridView is a complex control with many events, and often it does not work intuitively. It appears that when the EditingControlShowing event EditingControlShowing , the control is not yet initialized, so you cannot affect it. And when the CellBeginEdit event CellBeginEdit , the control has not yet been created.

There should be and probably the best way to do this, but I got it to work using the CellEnter event:

 private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e) { if (dgv.CurrentCell.EditType == typeof(DataGridViewTextBoxEditingControl)) { dgv.BeginEdit(false); ((TextBox)dgv.EditingControl).SelectionStart = 0; } } 

So, when the cell is entered, I just go directly to edit mode, but pass false to BeginEdit() , which tells it not to select any text. Now the edit control is fully initialized, and I can set SelectionStart to zero to move the cursor to the beginning of the text.

If the cell is not a text field, I do nothing.

If you want, you can do

 dgv.EditMode = DataGridViewEditMode.EditProgrammatically; 

so that you have full control over the start of editing, but I believe that this is not necessary.

+8
source

Source: https://habr.com/ru/post/1386160/


All Articles