单击时部分选择DataGridView单元格的文本 [英] Partially select the text of a DataGridView cell when clicked

查看:78
本文介绍了单击时部分选择DataGridView单元格的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以在用户输入时以编程方式选择DataGridView单元格文本的特定部分?
例如,如果用户输入一个单元格并在其中输入 hello world ,然后重新输入相同的单元格,则子字符串 world 将被自动选择(即,无需用户操作).

像这样:

解决方案

使用

  private void dataGridView1_EditingControlShowing(对象发送者,DataGridViewEditingControlShowingEventArgs e){如果(e.Control是DataGridViewTextBoxEditingControl tbec){var cellText = tbec.Text;如果(cellText?.Length> 1){BeginInvoke(new Action(()=> {字串= cellText.Split().Last();tbec.Select(cellText.Length-word.Length,word.Length);}));}}} 

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:

解决方案

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);
            }));
        }
    }
}

这篇关于单击时部分选择DataGridView单元格的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆