Partially select the text of a DataGridView cell when clicked

穿精又带淫゛_ 提交于 2021-01-27 17:35:53

问题


Is there a way to programmatically select a specific portion of the text of a DataGridView cell whenever a user enters it?
For example, if a user enters a cell and types hello world in it and then re-enters the same cell, the substring world will be automatically selected, (i.e. without user action).

Like this:


回答1:


A possible solution, using the EditingControlShowing event. The e.Control member of the DataGridViewEditingControlShowingEventArgs, references the Edit Control of the current cell.
After having checked whether the Edit Control is of type DataGridViewTextBoxEditingControl, e.Control is cast to a TextBoxBase class, which provides the Select() method used to select the cell's Text.

I introduced a short delay before selecting part of the Text, because the event is raised before the cell is invalidated. If the selection is performed right away, the Edit Control will re-select all the Text after the cell is invalidated and the previous selection is lost.

This method selects the last word of the text or all the text if there's only one word. Can be easily adapted to select any other section of the text.

Sample functionality:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control is DataGridViewTextBoxEditingControl tbec)
    {
        var cellText = tbec.Text;
        if (cellText?.Length > 1)
        {
            BeginInvoke(new Action(() => {
                string word = cellText.Split().Last();
                tbec.Select(cellText.Length - word.Length, word.Length);
            }));
        }
    }
}


来源:https://stackoverflow.com/questions/54776177/partially-select-the-text-of-a-datagridview-cell-when-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!