0

我试图弄清楚如何编辑一个 datagridview 单元格,它的行为就像一个普通的文本框。目前,当我单击单元格时,光标位于文本的开头:

dgvVX130.BeginEdit(false);
((TextBox)dgvVX130.EditingControl).SelectionStart = 0;  

然后我可以使用键进行编辑,并可以使用左右箭头移动光标位置。

此外,我希望能够在单元格中选择一部分文本,然后将其复制或删除。目前鼠标选择似乎完全无法操作。

如何也可以用鼠标更改光标位置?如何用鼠标选择部分文本?

4

1 回答 1

2

也许这第一个例子会有所帮助。进入单元格编辑模式时,它从单击的鼠标位置选择 3 个字符:

private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    if (dataGridView1.EditingControl == null)
    {
        dataGridView1.BeginEdit(false);
        TextBox editor = (TextBox)dataGridView1.EditingControl;
        // insert checks for null here if needed!!
        int ms = editor.GetCharIndexFromPosition(e.Location);
        editor.SelectionStart = ms;
        editor.SelectionLength = Math.Min(3, editor.Text.Length - editor.SelectionStart);
    }
}

请注意,代码仅在我们尚未处于编辑模式时执行!这可能是您的代码失败的地方..

更新:由于您似乎希望用户选择启动编辑模式并在第一次按下鼠标时设置选择,这里有一段代码对我来说就是这样做的。

它对编辑控件和临时控件Lambda都使用了一点,但也可以在没有.. 的情况下编写。因为即使在释放 . 之后,事件也会保持鼠标捕获直到事件完成,从而防止单元格进入编辑模式..TextBoxTimerLambdaTimerMouseDownCapture

请注意,所有进一步的错误检查都留给您,特别是对于编辑器控件,对于受保护的单元格和非文本单元格,它将为空。

int mDwnChar = -1;
DataGridViewCell lastCell = null;

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
    if (dataGridView1.EditingControl == null || cell != lastCell)
    {
        dataGridView1.BeginEdit(false);
        TextBox editor = (TextBox)dataGridView1.EditingControl;
        editor.MouseMove += (ts, te) =>
        {
            if (mDwnChar < 0) return;
            int ms = editor.GetCharIndexFromPosition(te.Location);
            if (ms >= 0 && mDwnChar >=0)
            {
               editor.SelectionStart = Math.Min(mDwnChar, ms);
               editor.SelectionLength = Math.Abs(mDwnChar - ms + 1); 
            }
        };
        editor.MouseUp += (ts, te) => { mDwnChar = -1; };

        mDwnChar = editor.GetCharIndexFromPosition(e.Location);
        dataGridView1.Capture = false;
        Timer timer00 = new Timer();
        timer00.Interval = 20;
        timer00.Tick += (ts, te) => { 
            timer00.Stop();
            dataGridView1.BeginEdit(false);
        };
        timer00.Start();

        lastCell = cell;
    }
}
于 2015-04-17T20:02:30.803 回答