datagridview-combobox-column-allow-input ソースコード全文
DataGridView_ComboBoxColumn_Input.slnx
<Solution> <Project Path="DataGridView_ComboBoxColumn_Input/DataGridView_ComboBoxColumn_Input.csproj" /></Solution>DataGridView_ComboBoxColumn_Input/DataGridView_ComboBoxColumn_Input.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_ComboBoxColumn_Input/DataGridView_ComboBoxColumn_Input.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_ComboBoxColumn_Input/Form1.cs
using System.ComponentModel;using System.Data;using System.Runtime.InteropServices;using System.Text;
namespace DataGridView_ComboBoxColumn_Input{ public partial class Form1 : Form { private DataTable _productsTable = new DataTable();
// 選択肢は DataGridViewComboBoxColumn.Items で一元管理する // BindingList を DataSource に設定すると ListChanged 発火時に // 編集コントロールがリセットされ ArgumentOutOfRangeException の原因となるため使用しない private readonly List<string> _categories = new List<string> { "食品", "家電", "雑貨" };
// IME確定Enter問題の対策:確定済みの入力値を別途保持する // Leave や CellValidating が走るタイミングでは comboBox.Text が // 空になっている場合があるため、TextChanged で随時記録しておく private string _pendingInputValue = "";
// IME変換中かどうかを判定するための Win32 API [DllImport("imm32.dll")] private static extern IntPtr ImmGetContext(IntPtr hWnd);
[DllImport("imm32.dll")] private static extern bool ImmReleaseContext(IntPtr hWnd, IntPtr hIMC);
[DllImport("imm32.dll", CharSet = CharSet.Unicode)] private static extern int ImmGetCompositionString(IntPtr hIMC, uint dwIndex, StringBuilder lpBuf, uint dwBufLen);
// GCS_COMPSTR:現在の未確定文字列を取得するフラグ private const uint GCS_COMPSTR = 0x0008;
public Form1() { InitializeComponent(); InitializeDataGridView(); }
private void InitializeDataGridView() { // 1. メインのデータテーブルを準備 _productsTable.Columns.Add("Name", typeof(string)); _productsTable.Columns.Add("Category", typeof(string)); _productsTable.Rows.Add("ノートパソコン", "家電"); _productsTable.Rows.Add("ミネラルウォーター", "食品");
// 2. コンボボックス列を手動で作成して追加 var comboCol = new DataGridViewComboBoxColumn(); comboCol.DataPropertyName = "Category"; comboCol.HeaderText = "カテゴリ"; comboCol.Name = "CategoryCombo";
// DataSource ではなく Items に直接追加する // DataSource (BindingList等) を使うと Add() 時に ListChanged が発火し、 // 編集コントロールの Items が再構築されて SelectedIndex がリセットされる comboCol.Items.AddRange(_categories.ToArray());
// グリッドに列を追加してデータソースを設定 dataGridView1.Columns.Add(comboCol); dataGridView1.DataSource = _productsTable; dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
// 3. 必要なイベントを購読 dataGridView1.EditingControlShowing += DataGridView1_EditingControlShowing; dataGridView1.CellValidating += DataGridView1_CellValidating; dataGridView1.CellEndEdit += DataGridView1_CellEndEdit; dataGridView1.DataError += DataGridView1_DataError; }
/// <summary> /// セルが編集状態になったときに発生するイベント /// </summary> private void DataGridView1_EditingControlShowing(object? sender, DataGridViewEditingControlShowingEventArgs e) { if (e.Control is ComboBox comboBox) { string columnName = dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name;
if (columnName == "CategoryCombo") { comboBox.DropDownStyle = ComboBoxStyle.DropDown;
// イベントの重複購読を防ぐため、一度解除してから再購読する comboBox.Leave -= CategoryComboBox_Leave; comboBox.TextChanged -= CategoryComboBox_TextChanged; comboBox.KeyDown -= CategoryComboBox_KeyDown;
comboBox.Leave += CategoryComboBox_Leave; comboBox.TextChanged += CategoryComboBox_TextChanged; comboBox.KeyDown += CategoryComboBox_KeyDown;
// 編集開始時に既存のセル値で初期化する _pendingInputValue = comboBox.Text; } else { comboBox.DropDownStyle = ComboBoxStyle.DropDownList; comboBox.Leave -= CategoryComboBox_Leave; comboBox.TextChanged -= CategoryComboBox_TextChanged; comboBox.KeyDown -= CategoryComboBox_KeyDown; } } }
/// <summary> /// テキストが変化するたびに呼ばれる。 /// IME変換中でない(未確定文字列がない)タイミングのみ _pendingInputValue に記録する。 /// これにより、Leave や CellValidating が走った時点で comboBox.Text が空でも /// 確定済みの正しい値を参照できる。 /// </summary> private void CategoryComboBox_TextChanged(object? sender, EventArgs e) { if (sender is not ComboBox comboBox) return;
if (!IsImeComposing(comboBox.Handle)) { _pendingInputValue = comboBox.Text; } }
/// <summary> /// Enter キー押下時に IME 変換中であれば DataGridView へのキー伝播を止める。 /// これにより、IME確定のEnterがセル編集終了として扱われることを防ぐ。 /// ユーザーが IME 確定後に改めて Enter を押すと、正常にセル編集が終了する。 /// </summary> private void CategoryComboBox_KeyDown(object? sender, KeyEventArgs e) { if (sender is not ComboBox comboBox) return;
if (e.KeyCode == Keys.Return && IsImeComposing(comboBox.Handle)) { // IME変換中の Enter はセル移動に使わせない e.Handled = true; e.SuppressKeyPress = true; } }
/// <summary> /// IME変換中かどうかを Win32 API で判定する。 /// ImmGetCompositionString で未確定文字列(GCS_COMPSTR)の長さが 0 より大きければ変換中。 /// </summary> private static bool IsImeComposing(IntPtr hWnd) { IntPtr hIMC = ImmGetContext(hWnd); if (hIMC == IntPtr.Zero) return false;
try { var sb = new StringBuilder(256); int len = ImmGetCompositionString(hIMC, GCS_COMPSTR, sb, (uint)sb.Capacity); return len > 0; } finally { ImmReleaseContext(hWnd, hIMC); } }
/// <summary> /// 直接入力を許可したコンボボックスからフォーカスが離れる直前に発生するイベント。 /// CellValidating より前のタイミングで値をリストへ追加しておくことで、 /// DataGridView の内部検証(「選択肢にない値」エラー)を回避する。 /// comboBox.Text ではなく _pendingInputValue を参照する点がポイント。 /// </summary> private void CategoryComboBox_Leave(object? sender, EventArgs e) { if (sender is not ComboBox comboBox) return;
// comboBox.Text ではなく _pendingInputValue を使用する // IME確定直後に Leave が走った場合、comboBox.Text が空になることがある string inputValue = _pendingInputValue; if (string.IsNullOrEmpty(inputValue)) return;
if (!comboBox.Items.Contains(inputValue)) { comboBox.Items.Add(inputValue);
if (!_categories.Contains(inputValue)) { _categories.Add(inputValue);
// DataGridViewComboBoxColumn.Items にも追加して // 次回以降の編集時にドロップダウンに表示されるようにする var col = dataGridView1.Columns["CategoryCombo"] as DataGridViewComboBoxColumn; col?.Items.Add(inputValue); } }
comboBox.SelectedItem = inputValue; }
/// <summary> /// セルの値が検証されるときに発生するイベント /// </summary> private void DataGridView1_CellValidating(object? sender, DataGridViewCellValidatingEventArgs e) { if (dataGridView1.Columns[e.ColumnIndex].Name == "CategoryCombo") { // e.FormattedValue は IME確定直後に空になることがあるため信頼しない // Leave で記録済みの _pendingInputValue を優先して参照する string newValue = !string.IsNullOrEmpty(_pendingInputValue) ? _pendingInputValue : e.FormattedValue?.ToString() ?? "";
// Leave で未処理だった場合の保険として Items に追加する if (!string.IsNullOrEmpty(newValue) && dataGridView1.EditingControl is ComboBox comboBox && !comboBox.Items.Contains(newValue)) { comboBox.Items.Add(newValue);
if (!_categories.Contains(newValue)) { _categories.Add(newValue); var col = dataGridView1.Columns["CategoryCombo"] as DataGridViewComboBoxColumn; col?.Items.Add(newValue); } }
// SelectedIndex を再設定して値を確定させる if (dataGridView1.EditingControl is ComboBox cb) { int index = cb.Items.IndexOf(newValue); if (index >= 0) { cb.SelectedIndex = index; } } } }
/// <summary> /// セルの編集が完了し、値がコミットされた直後に発生するイベント。 /// 新規追加行(IsNewRow)の場合、CellValidating での SelectedIndex 設定が /// DataTable.Rows.Add() のタイミングで空文字に上書きされてしまうため、 /// CellEndEdit で DataTable の該当セルに直接 _pendingInputValue を書き込む。 /// </summary> private void DataGridView1_CellEndEdit(object? sender, DataGridViewCellEventArgs e) { if (dataGridView1.Columns[e.ColumnIndex].Name != "CategoryCombo") return; if (string.IsNullOrEmpty(_pendingInputValue)) return;
// 新規行・既存行を問わず、DataTable の該当セルを _pendingInputValue で上書きする // 新規行の場合は DataTable.Rows.Add() 後に空が書き込まれることへの対策 // 既存行の場合も、CellValidating での設定を確実に永続化するための保険となる DataGridViewRow row = dataGridView1.Rows[e.RowIndex]; if (row.DataBoundItem is DataRowView drv) { string colName = ((DataGridViewComboBoxColumn)dataGridView1.Columns[e.ColumnIndex]).DataPropertyName; if (drv[colName]?.ToString() != _pendingInputValue) { drv[colName] = _pendingInputValue; } } }
/// <summary> /// データエラーが発生したときに呼び出されるイベント /// </summary> private void DataGridView1_DataError(object? sender, DataGridViewDataErrorEventArgs e) { // 予期せぬ整合性エラーが発生した場合に、標準のエラーダイアログが表示されるのを防ぐ if (dataGridView1.Columns[e.ColumnIndex].Name == "CategoryCombo") { e.ThrowException = false; e.Cancel = false; } } }}DataGridView_ComboBoxColumn_Input/Form1.Designer.cs
namespace DataGridView_ComboBoxColumn_Input{ 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_ComboBoxColumn_Input/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_ComboBoxColumn_Input/Program.cs
namespace DataGridView_ComboBoxColumn_Input{ 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()); } }}