也许这第一个例子会有所帮助。进入单元格编辑模式时,它从单击的鼠标位置选择 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
都使用了一点,但也可以在没有.. 的情况下编写。因为即使在释放 . 之后,事件也会保持鼠标捕获直到事件完成,从而防止单元格进入编辑模式..TextBox
Timer
Lambda
Timer
MouseDown
Capture
请注意,所有进一步的错误检查都留给您,特别是对于编辑器控件,对于受保护的单元格和非文本单元格,它将为空。
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;
}
}