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

保護されたセルと非テキスト セルの場合は null になる、特にエディター コントロールの場合、それ以降のすべてのエラー チェックはユーザーに委ねられていることに注意してください。

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 に答える