datagridview-image-button-column ソースコード全文
DataGridView_ImageButtonColumn.slnx
<Solution> <Project Path="DataGridView_ImageButtonColumn/DataGridView_ImageButtonColumn.csproj" /></Solution>DataGridView_ImageButtonColumn/DataGridView_ImageButtonColumn.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>
<ItemGroup> <None Update="Images\search.png"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup>
</Project>DataGridView_ImageButtonColumn/DataGridView_ImageButtonColumn.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_ImageButtonColumn/Form1.cs
using System.Data;
namespace DataGridView_ImageButtonColumn{ public partial class Form1 : Form { private DataTable _dataTable = new DataTable();
// 読み込んだ画像オブジェクトを使い回す(キャッシュする)ための変数 private Bitmap? _searchIcon;
public Form1() { InitializeComponent(); LoadFileIcon(); // 起動時に一度だけ画像を読み込む InitializeDataGridView(); }
/// <summary> /// 出力ディレクトリにコピーされたファイルから画像を読み込む /// </summary> private void LoadFileIcon() { try { // 実行ファイルがあるフォルダ(StartupPath)内の「Images/search.png」の絶対パスを結合 string imagePath = Path.Combine(Application.StartupPath, "Images", "search.png");
if (File.Exists(imagePath)) { // ファイルから24x24のBitmapを生成してキャッシュ _searchIcon = new Bitmap(imagePath); } else { MessageBox.Show($"画像ファイルが見つかりません。想定パス: {imagePath}", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception ex) { MessageBox.Show($"画像の読み込み中にエラーが発生しました:\n{ex.Message}", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void InitializeDataGridView() { // 1. テストデータの準備 _dataTable.Columns.Add("Keywords", typeof(string)); _dataTable.Columns.Add("Target", typeof(string)); _dataTable.Rows.Add("C# 画面遷移", "Google"); _dataTable.Rows.Add("DataGridView 描画", "Bing");
dataGridView1.DataSource = _dataTable;
// 2. 検索ボタン列を手動で追加 var btnColumn = new DataGridViewButtonColumn(); btnColumn.Name = "SearchBtn"; btnColumn.HeaderText = "検索実行"; btnColumn.Text = ""; // ボタン上のテキストは空にして画像だけにする btnColumn.UseColumnTextForButtonValue = true; btnColumn.Width = 100; // 24x24のアイコンが余裕を持って収まる列幅
dataGridView1.Columns.Insert(0, btnColumn);
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
// 24x24のアイコンが上下に見切れないよう、行高さを少し広めに設定(推奨: 32以上) dataGridView1.RowTemplate.Height = 38;
// 3. セルの描画イベント(CellPainting)を購読 dataGridView1.CellPainting += DataGridView1_CellPainting;
// 4. ボタンのクリックイベント(CellContentClick)を購読 dataGridView1.CellContentClick += DataGridView1_CellContentClick; }
/// <summary> /// セルの描画が行われるときに呼び出されるイベント(画像の描画) /// </summary> private void DataGridView1_CellPainting(object? sender, DataGridViewCellPaintingEventArgs e) { // ヘッダー行や、目的のボタン列以外の列は処理対象外にする if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
if (dataGridView1.Columns[e.ColumnIndex].Name == "SearchBtn") { // A. ボタンの背景・枠線だけを通常通りシステムに描画させる(文字用のForegroundは除外) e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.ContentForeground);
// B. キャッシュしておいた 24x24 のアイコンを中央寄せで描画 if (_searchIcon != null) { // セルの幅・高さから、中央寄せになるX, Y座標を算出 int x = e.CellBounds.Left + (e.CellBounds.Width - _searchIcon.Width) / 2; int y = e.CellBounds.Top + (e.CellBounds.Height - _searchIcon.Height) / 2;
e.Graphics.DrawImage(_searchIcon, x, y); }
// C. システムによる標準のテキスト重ね描きなどをキャンセル e.Handled = true; } }
/// <summary> /// セルの中身(今回の場合はボタン)がクリックされたときに呼び出されるイベント /// </summary> private void DataGridView1_CellContentClick(object? sender, DataGridViewCellEventArgs e) { // 列ヘッダーのクリックや、目的のボタン列以外のクリックは無視する if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
if (dataGridView1.Columns[e.ColumnIndex].Name == "SearchBtn") { // クリックされた行のデータを取得 string keywords = dataGridView1.Rows[e.RowIndex].Cells["Keywords"].Value?.ToString() ?? ""; string target = dataGridView1.Rows[e.RowIndex].Cells["Target"].Value?.ToString() ?? "";
// イベントハンドリングの証明として、メッセージボックスを表示 MessageBox.Show($"「{target}」でキーワード「{keywords}」の検索を実行します。", "検索イベント感知", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
protected override void OnFormClosed(FormClosedEventArgs e) { base.OnFormClosed(e);
// ファイルから生成した画像リソースを明示的に解放 // これを怠るとWindowsによってファイルがロックされ続け、アプリ実行中に画像を上書き・削除できなくなります _searchIcon?.Dispose(); } }}DataGridView_ImageButtonColumn/Form1.Designer.cs
namespace DataGridView_ImageButtonColumn{ 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_ImageButtonColumn/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_ImageButtonColumn/Images/search.png
🗎 バイナリファイル(画像・実行ファイル等)のため、内容の表示は省略しています。 全体は ZIP ダウンロード でご確認ください。
DataGridView_ImageButtonColumn/Program.cs
namespace DataGridView_ImageButtonColumn{ 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()); } }}