Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to place cursor to the start of the text in editing DataGridView cell programmatically when user start to edit cell text?

I use DataGridView that gets Data from DataTable for editing some amount of data. Everything seems ok, but there is some inconvenience. When user starts to edit cell, text of this cell automatically become selected and cursor moves to the end of cell text. I want to place cursor(caret) to the start of the text in editing cell programmatically when user starts to edit cell text. I tried:

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

That is not work. Also I tried to deselect text in CellBeginEdit- also no result.

like image 587
Alexander Avatar asked Dec 13 '11 17:12

Alexander


1 Answers

I would have expected what you did to work too. But the DataGridView is a complex control with many events and often it doesn't work intuitively. It seems that when the EditingControlShowing event happens, the control hasn't been initialized yet, so you can't affect it. And when the CellBeginEdit event happens, the control hasn't even been created yet.

There should be and probably is a better way to do it, 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 straight into edit mode, but I 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 start of the text.

If the cell isn't a textbox then I do nothing.

If you want you can do

dgv.EditMode = DataGridViewEditMode.EditProgrammatically;

so that you have full control over when editing begins, but I find this isn't necessary.

like image 155
Igby Largeman Avatar answered Nov 08 '22 20:11

Igby Largeman