LoginSignup
3
1

More than 5 years have passed since last update.

DataGirdViewのチェックボックスサイズを変更してみた

Last updated at Posted at 2017-11-10

DataGirdViewのチェックボックスサイズを拡大したので紹介します。
(※なお、シンプルなチェックボックスを表示することしか行っていません。)

手順としては、DataGridViewCheckBoxCellクラスの派生クラスを作成して、下記メソッドをオーバーライドします。
protected override void Paint():セルの描画
protected override Rectangle GetContentBounds():コンテンツ領域を取得する

当初はPaint()だけオーバライドしていたのですが、マウスで拡大した領域をクリックしてもチェックボックスが変化しなかったため、GetContentBounds()も対応しました。

以下、コードです。

public class DataGridViewCheckBoxCellEx : DataGridViewCheckBoxCell
{
    // チェックボックス拡大サイズ
    private const int CHECKBOX_INFLATE_SIZE = 8;

    protected override void Paint(Graphics graphics, ...)
    {
        // 塗りつぶしと枠線描画
        bool cellSelected = (elementState & DataGridViewElementStates.Selected) != 0;
        SolidBrush br = new SolidBrush(cellSelected ? cellStyle.SelectionBackColor : cellStyle.BackColor);
        graphics.FillRectangle(br, cellBounds);
        this.PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);

        // チェックボックス描画
        Rectangle checkboxRect = this.GetCheckboxBounds(graphics, cellStyle, rowIndex);
        checkboxRect.Offset(cellBounds.Location);
        ControlPaint.DrawCheckBox(graphics, checkboxRect, his.GetButtonState(formattedValue));
}

    protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
    {
        Rectangle checkboxBounds = base.GetContentBounds(graphics, cellStyle, rowIndex);
        Rectangle cellBounds = this.DataGridView.GetCellDisplayRectangle(this.ColumnIndex, rowIndex, false);
        Size marginSize = new Size(cellBounds.Width - checkboxBounds.Width, cellBounds.Height - checkboxBounds.Height);
        if (marginSize.Width < CHECKBOX_INFLATE_SIZE * 2 || marginSize.Height < CHECKBOX_INFLATE_SIZE * 2)
        {
            return checkboxBounds;
        }
        checkboxBounds.Inflate(CHECKBOX_INFLATE_SIZE, CHECKBOX_INFLATE_SIZE);
        return checkboxBounds;
    }

    private ButtonState GetButtonState(object formattedValue)
    {
        ButtonState bs = ButtonState.Normal;
        if (formattedValue != null && formattedValue is CheckState)
        {
            bs = ((CheckState)formattedValue == CheckState.Unchecked) ? ButtonState.Normal : ButtonState.Checked;
        }
        else if (formattedValue != null && formattedValue is bool)
        {
            bs = ((bool)formattedValue) ? ButtonState.Checked : ButtonState.Normal;
        }
        return bs;
    }
}
3
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1