datagridview-header-checkbox-select-all-rows ソースコード全文

DataGridView_HeaderCheckBox.slnx

DataGridView_HeaderCheckBox.slnx
<Solution>
<Project Path="DataGridView_HeaderCheckBox/DataGridView_HeaderCheckBox.csproj" />
</Solution>

DataGridView_HeaderCheckBox/DataGridView_HeaderCheckBox.csproj

DataGridView_HeaderCheckBox.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

DataGridView_HeaderCheckBox/DataGridView_HeaderCheckBox.csproj.user

DataGridView_HeaderCheckBox.csproj.user
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Compile Update="Form1.cs">
<SubType>Form</SubType>
</Compile>
</ItemGroup>
</Project>

DataGridView_HeaderCheckBox/Form1.cs

Form1.cs
using System.Data;
using System.Windows.Forms.VisualStyles; // CheckBoxRenderer を使うために必要
namespace DataGridView_HeaderCheckBox;
public partial class Form1 : Form
{
private DataTable _dataTable = new DataTable();
// ヘッダーの状態を管理する変数(初期値は未チェック)
private CheckBoxState _headerState = CheckBoxState.UncheckedNormal;
// 一括更新中の「イベント連打」を防ぐための制御フラグ
private bool _isUpdatingAllRows = false;
public Form1()
{
InitializeComponent();
InitializeData();
InitializeDataGridView();
}
private void InitializeData()
{
// 表示用デモデータの準備
_dataTable.Columns.Add("ID", typeof(string));
_dataTable.Columns.Add("Country", typeof(string));
_dataTable.Columns.Add("City", typeof(string));
_dataTable.Rows.Add("B-6000", "Belgium", "Charleroi");
_dataTable.Rows.Add("04876", "Brazil", "Campinas");
_dataTable.Rows.Add("08737", "Brazil", "Resende");
_dataTable.Rows.Add("T2F 8M4", "Canada", "Tsawwassen");
}
private void InitializeDataGridView()
{
// 1. データソースをバインドする前に、チェックボックス列を手動で先頭に追加
var chkColumn = new DataGridViewCheckBoxColumn();
chkColumn.Name = "SelectChk";
chkColumn.HeaderText = ""; // ヘッダーテキストは空にして、後から画像を描画します
chkColumn.Width = 45;
chkColumn.Resizable = DataGridViewTriState.False;
dataGridView1.Columns.Add(chkColumn);
// データのバインド
dataGridView1.DataSource = _dataTable;
dataGridView1.AllowUserToAddRows = false;
// 2. 必要なイベントを購読
dataGridView1.CellPainting += DataGridView1_CellPainting;
dataGridView1.CellClick += DataGridView1_CellClick;
dataGridView1.CurrentCellDirtyStateChanged += DataGridView1_CurrentCellDirtyStateChanged;
dataGridView1.CellValueChanged += DataGridView1_CellValueChanged;
}
/// <summary>
/// セルの描画イベント(ヘッダーにチェックボックスを描画する)
/// </summary>
private void DataGridView1_CellPainting(object? sender, DataGridViewCellPaintingEventArgs e)
{
// 先頭列(ColumnIndex == 0)かつ ヘッダー行(RowIndex == -1)のときのみカスタム描画
if (e.RowIndex == -1 && e.ColumnIndex == 0)
{
e.PaintBackground(e.CellBounds, true);
Size checkBoxSize = CheckBoxRenderer.GetGlyphSize(e.Graphics, CheckBoxState.UncheckedNormal);
int x = e.CellBounds.X + (e.CellBounds.Width - checkBoxSize.Width) / 2;
int y = e.CellBounds.Y + (e.CellBounds.Height - checkBoxSize.Height) / 2;
Point drawPoint = new Point(x, y);
// 現在の _headerState(Checked/Unchecked/Mixed)に基づいて描画
CheckBoxRenderer.DrawCheckBox(e.Graphics, drawPoint, _headerState);
e.Handled = true;
}
}
/// <summary>
/// セルまたはヘッダーがクリックされたときのイベント
/// </summary>
private void DataGridView1_CellClick(object? sender, DataGridViewCellEventArgs e)
{
// 先頭列のヘッダーがクリックされたかチェック
if (e.RowIndex == -1 && e.ColumnIndex == 0)
{
// 現在編集中のデータ行があれば、その編集状態を強制終了させて確定する
dataGridView1.EndEdit();
// 現在「全選択」状態であれば次は「全解除」、それ以外(未選択・部分選択)なら次は「全選択」にする
bool nextCheckValue = (_headerState != CheckBoxState.CheckedNormal);
// イベント連打防止フラグを立てる
_isUpdatingAllRows = true;
// 3. 全行をループして、チェックボックスの値を一括で書き換える
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (!row.IsNewRow)
{
row.Cells["SelectChk"].Value = nextCheckValue;
}
}
_isUpdatingAllRows = false;
// ヘッダーの状態を更新
_headerState = nextCheckValue ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal;
// ヘッダーだけでなく、データ行全体の見た目を確実に同期させるためグリッド全体を再描画
dataGridView1.Invalidate();
}
}
/// <summary>
/// チェックボックスの値が確定したときに呼び出されるイベント
/// </summary>
private void DataGridView1_CellValueChanged(object? sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex == 0 && !_isUpdatingAllRows)
{
UpdateHeaderCheckBoxState();
}
}
/// <summary>
/// データ行のチェック状態をスキャンし、ヘッダーの状態を決定するメソッド
/// </summary>
private void UpdateHeaderCheckBoxState()
{
int checkedCount = 0;
int dataRowCount = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (!row.IsNewRow)
{
dataRowCount++;
if (row.Cells["SelectChk"].Value is bool b && b)
{
checkedCount++;
}
}
}
// チェック数に応じて、ヘッダーの状態(3つのステータス)を割り出す
if (checkedCount == 0)
{
_headerState = CheckBoxState.UncheckedNormal; // 全て未選択
}
else if (checkedCount == dataRowCount)
{
_headerState = CheckBoxState.CheckedNormal; // 全て選択
}
else
{
_headerState = CheckBoxState.MixedNormal; // 一部のみ選択(部分選択状態)
}
dataGridView1.InvalidateCell(0, -1);
}
private void DataGridView1_CurrentCellDirtyStateChanged(object? sender, EventArgs e)
{
if (dataGridView1.CurrentCell is DataGridViewCheckBoxCell)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
}

DataGridView_HeaderCheckBox/Form1.Designer.cs

Form1.Designer.cs
namespace DataGridView_HeaderCheckBox
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView1 = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit();
SuspendLayout();
//
// dataGridView1
//
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.Location = new Point(0, 0);
dataGridView1.Name = "dataGridView1";
dataGridView1.RowHeadersWidth = 62;
dataGridView1.Size = new Size(800, 450);
dataGridView1.TabIndex = 0;
//
// Form1
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(dataGridView1);
Name = "Form1";
Text = "Form1";
((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView1;
}
}

DataGridView_HeaderCheckBox/Form1.resx

Form1.resx
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

DataGridView_HeaderCheckBox/Program.cs

Program.cs
namespace DataGridView_HeaderCheckBox
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
}