Maybe this first example will help. It selects 3 characters from the clicked mouse position when entering the cell edit mode:
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);
}
}
Note that the code only executes when we are not in edit mode already! This is probably where your code fails..
Update: As you seem to want the option of the user to start both edit mode and setting a selection at the first mouse down, here is a piece of code that does just that for me.
It uses a little Lambda
for both the TextBox
edit control and a temporary Timer
but could just as well be written without the Lambda
.. The Timer
is needed as the MouseDown
event keeps the mouse captured until the event is done even after releasing the Capture
, thereby preventing the cell from entering edit mode..
Note that all further error checking is left to you, especially for the editor control, which will be null for protected cells and for non-text cells..
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;
}
}