datagridview-progress-cell ソースコード全文
DataGridView_ProgressCell.slnx
<Solution> <Project Path="DataGridView_ProgressCell/DataGridView_ProgressCell.csproj" /></Solution>DataGridView_ProgressCell/DataGridView_ProgressCell.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_ProgressCell/DataGridView_ProgressCell.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_ProgressCell/Form1.cs
using System.Data;
namespace DataGridView_ProgressCell;
public partial class Form1 : Form{ private DataTable _taskTable = new DataTable();
public Form1() { InitializeComponent(); InitializeData(); InitializeDataGridView(); }
private void InitializeData() { // 1. データソースの準備(値は 0 〜 100 の整数を想定) _taskTable.Columns.Add("TaskName", typeof(string)); _taskTable.Columns.Add("Progress", typeof(int)); // 進捗率
_taskTable.Rows.Add("画面設計の作成", 100); _taskTable.Rows.Add("データバインディング実装", 65); _taskTable.Rows.Add("デバッグ・テスト", 10); }
private void InitializeDataGridView() { dataGridView1.DataSource = _taskTable;
// 列名の調整 dataGridView1.Columns["TaskName"].HeaderText = "タスク名"; dataGridView1.Columns["Progress"].HeaderText = "進捗状況";
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dataGridView1.AllowUserToAddRows = false;
// カスタム描画イベントを購読 dataGridView1.CellPainting += DataGridView1_CellPainting;
// 入力制限(バリデーション)イベントを購読 dataGridView1.CellValidating += DataGridView1_CellValidating; dataGridView1.CellEndEdit += DataGridView1_CellEndEdit; }
/// <summary> /// セルの値が確定する直前に呼び出される検証イベント /// </summary> private void DataGridView1_CellValidating(object? sender, DataGridViewCellValidatingEventArgs e) { // Progress列以外はチェック対象外にする if (dataGridView1.Columns[e.ColumnIndex].Name != "Progress") return;
// 新しく入力された「画面上の文字列」は e.FormattedValue から取得します string newValueStr = e.FormattedValue?.ToString() ?? "";
// 未入力(空っぽ)はエラーにする場合 if (string.IsNullOrWhiteSpace(newValueStr)) { dataGridView1.Rows[e.RowIndex].ErrorText = "進捗状況を入力してください。"; e.Cancel = true; return; }
// 整数に変換できるか、および 0 〜 100 の範囲内かをチェック if (!int.TryParse(newValueStr, out int parsedValue) || parsedValue < 0 || parsedValue > 100) { // 行にエラーテキストを設定(行ヘッダーにエラーアイコンが表示されます) dataGridView1.Rows[e.RowIndex].ErrorText = "進捗率は 0 〜 100 の間の整数で入力してください。";
// これに true をセットすることで、不正な値のままフォーカスが外れるのを阻止します e.Cancel = true; } }
/// <summary> /// セルの編集が正常に終了したときに呼び出されるイベント /// </summary> private void DataGridView1_CellEndEdit(object? sender, DataGridViewCellEventArgs e) { // 正しい値が入力されて編集が無事終わったら、行のエラーテキストを綺麗に消去します dataGridView1.Rows[e.RowIndex].ErrorText = string.Empty; }
/// <summary> /// セルの描画イベント /// </summary> private void DataGridView1_CellPainting(object? sender, DataGridViewCellPaintingEventArgs e) { // ヘッダーや無効なセル、および「Progress」列以外は通常通りシステムに描画させる if (e.RowIndex < 0 || e.ColumnIndex < 0) return; if (dataGridView1.Columns[e.ColumnIndex].Name != "Progress") return;
// 3. 現在「編集モード中」であるかチェック // PaintPartsに「All」が指定されている、かつ、セルの状態に「Editing(編集中)」が含まれている場合 if (dataGridView1.IsCurrentCellInEditMode && dataGridView1.CurrentCell.RowIndex == e.RowIndex && dataGridView1.CurrentCell.ColumnIndex == e.ColumnIndex) { // 編集中の場合は自前での描画(プログレスバー)は一切せず、システム(標準のTextBox)に丸投げする return; }
// --- ここから非編集時の「プログレスバー」描画ロジック ---
// セルの値を数値(0〜100)として取得 int progressValue = 0; if (e.Value != null && int.TryParse(e.Value.ToString(), out int parsedValue)) { // 0〜100の範囲に収めるガード処理 progressValue = Math.Max(0, Math.Min(100, parsedValue)); }
// A. まずはセルの背景と枠線を描画(選択状態の色なども自動考慮されます) e.PaintBackground(e.CellBounds, true);
// B. プログレスバー(横バー)の描画領域を計算(セルの内側に少しマージンを取る) int marginX = 4; int marginY = 4; Rectangle barBounds = new Rectangle( e.CellBounds.X + marginX, e.CellBounds.Y + marginY, e.CellBounds.Width - (marginX * 2), e.CellBounds.Height - (marginY * 2) );
// バーの背景(薄いグレー)を塗る using (SolidBrush bgBrush = new SolidBrush(Color.FromArgb(240, 240, 240))) { e.Graphics.FillRectangle(bgBrush, barBounds); }
// 進捗率に応じた「緑色のバー」の幅を計算し、配色する if (progressValue > 0) { int fillWidth = (int)(barBounds.Width * (progressValue / 100.0)); Rectangle fillBounds = new Rectangle(barBounds.X, barBounds.Y, fillWidth, barBounds.Height);
// 100%なら緑、それ以外は黄緑で配色する Color barColor = (progressValue == 100) ? Color.MediumSeaGreen : Color.LightGreen; using (SolidBrush barBrush = new SolidBrush(barColor)) { e.Graphics.FillRectangle(barBrush, fillBounds); } }
// C. バーの枠線(細いグレー)を描画 using (Pen borderPen = new Pen(Color.LightGray)) { e.Graphics.DrawRectangle(borderPen, barBounds); }
// D. 中央に「〇〇%」というテキストを重ねて描画 string text = $"{progressValue}%";
// 文字の配置(中央揃え)を指定 TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.PreserveGraphicsClipping;
// 選択されている行かどうかで文字色を変える Color textColor = (e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected ? e.CellStyle.SelectionForeColor : e.CellStyle.ForeColor;
TextRenderer.DrawText(e.Graphics, text, e.CellStyle.Font, e.CellBounds, textColor, flags);
// 4. 「描画は完了した」とシステムに通知(標準の数値テキストが上書きされるのを防ぐ) e.Handled = true; }}DataGridView_ProgressCell/Form1.Designer.cs
namespace DataGridView_ProgressCell{ 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_ProgressCell/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_ProgressCell/Program.cs
namespace DataGridView_ProgressCell{ 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()); } }}