DataGridViewの右端の列の幅を増加させる方法

既定では右端の列がDataGridViewの右端に接しているとき、その列の幅を増加させることはできません。これを解決する方法を考えます。

右端に、ダミーの列を配置する

問題の列が右端にならないように、さらに右に列を追加します。DataGridViewの右端の列の幅を操作させるには?

// ダミーの列を追加する
{
    DataGridViewColumn column = new DataGridViewTextBoxColumn();

    column.Width = 10;
    column.ReadOnly = true; // 書き換え禁止
    column.Resizable = DataGridViewTriState.False; // リサイズ禁止
    column.SortMode = DataGridViewColumnSortMode.NotSortable; // ソート禁止

    this.Columns.Add(column);
}
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
{
    base.OnCellPainting(e);

    // 右端の列ならば、セルを描画しない
    if (e.ColumnIndex == this.ColumnCount - 1)
    {
        // DataGridViewの背景色で塗りつぶす
        Brush brush = new SolidBrush(this.BackgroundColor);
        e.Graphics.FillRectangle(brush, e.CellBounds);

        e.Handled = true;
    }
}

Mouseのイベントを捕捉し、コードで列の幅を指定する

リサイズされるときにクリッピング領域を拡大し、マウスボタンが離された位置を列の幅としてコードで指定します。c# - DataGridView rightmost column user increase size not working - Stack Overflow

private enum DataGridViewHitTestTypeInternal
{
    None,
    Cell,
    ColumnHeader,
    RowHeader,
    ColumnResizeLeft,
    ColumnResizeRight,
}

private int resizeColumnIndex = -1;

protected override void OnMouseDown(MouseEventArgs e)
{
    base.OnMouseDown(e);

    HitTestInfo hitTestInfo = this.HitTest(e.X, e.Y);
    if (hitTestInfo.Type == DataGridViewHitTestType.ColumnHeader)
    {
        // クリックされた位置を詳細に特定するため、リフレクションによりInternalな情報を取得する
        System.Reflection.FieldInfo fieldInfo = typeof(HitTestInfo).GetField("typeInternal", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        DataGridViewHitTestTypeInternal hitTestType = (DataGridViewHitTestTypeInternal)fieldInfo.GetValue(hitTestInfo);

        // クリックされた位置が区分線上ならば、リサイズされると見なす
        if (hitTestType == DataGridViewHitTestTypeInternal.ColumnResizeLeft
        || hitTestType == DataGridViewHitTestTypeInternal.ColumnResizeRight)
        {
            this.resizeColumnIndex = hitTestInfo.ColumnIndex - (hitTestType == DataGridViewHitTestTypeInternal.ColumnResizeLeft ? 1 : 0);

            Rectangle clip = Cursor.Clip;
            Rectangle screenBounds = Screen.GetBounds(this);

            // クリッピング領域がコントロール内に制限されないように、スクリーンの右端まで拡大する
            clip.Width = screenBounds.Width - clip.Left;
            Cursor.Clip = clip;
            return;
        }
    }

    this.resizeColumnIndex = -1;
}

protected override void OnMouseUp(MouseEventArgs e)
{
    base.OnMouseUp(e);

    // コントロールの右端を超えた大きさを指定されたならば、コードで列の幅を指定する
    if (this.resizeColumnIndex != -1 && this.Right < e.X)
    {
        Rectangle columnRectangle = this.GetColumnDisplayRectangle(this.resizeColumnIndex, false);
        this.Columns[this.resizeColumnIndex].Width = e.X - columnRectangle.Left;
    }
}
Microsoft Learnから検索