datagridview-add-row ソースコード全文

DataGridView_AddRow.slnx

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

DataGridView_AddRow/DataGridView_AddRow.csproj

DataGridView_AddRow.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_AddRow/DataGridView_AddRow.csproj.user

DataGridView_AddRow.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_AddRow/Form1.cs

Form1.cs
using System.ComponentModel;
using System.Data;
namespace DataGridView_AddRow
{
public partial class Form1 : Form
{
// ── フィールド変数 ──────────────────────────────
// DataTable バインド用
private DataTable _dataTable = new DataTable();
// BindingList バインド用
private BindingList<Product> _products = new BindingList<Product>();
// ── コンストラクタ ──────────────────────────────
public Form1()
{
InitializeComponent();
// タブ①:バインドなし
SetupNoBindTab();
// タブ②:DataTable バインド
SetupDataTableTab();
// タブ③:BindingList バインド
SetupBindingListTab();
}
// ════════════════════════════════════════════════
// タブ①:バインドなし(Rows.Add で直接追加)
// ════════════════════════════════════════════════
private void SetupNoBindTab()
{
// 列を手動で追加
dataGridViewNoBind.Columns.Add("ColID", "ID");
dataGridViewNoBind.Columns.Add("ColName", "名前");
dataGridViewNoBind.Columns.Add("ColAge", "年齢");
dataGridViewNoBind.AllowUserToAddRows = false;
// ボタンクリックで行を追加
btnAddNoBind.Click += (s, e) =>
{
int nextId = dataGridViewNoBind.Rows.Count + 1;
dataGridViewNoBind.Rows.Add(nextId, $"ユーザー{nextId}", 20 + nextId);
};
}
// ════════════════════════════════════════════════
// タブ②:DataTable バインド
// ════════════════════════════════════════════════
private void SetupDataTableTab()
{
// DataTable の列定義
_dataTable.Columns.Add("ID", typeof(int));
_dataTable.Columns.Add("Name", typeof(string));
_dataTable.Columns.Add("Age", typeof(int));
// 初期データ
_dataTable.Rows.Add(1, "じゅんや", 23);
_dataTable.Rows.Add(2, "きょうこ", 25);
_dataTable.Rows.Add(3, "えみ", 24);
// DataGridView にバインド
dataGridViewDT.DataSource = _dataTable;
dataGridViewDT.AllowUserToAddRows = false;
// ボタンクリックで DataTable に行追加 → DataGridView に自動反映
btnAddDT.Click += (s, e) =>
{
int nextId = _dataTable.Rows.Count + 1;
DataRow newRow = _dataTable.NewRow();
newRow["ID"] = nextId;
newRow["Name"] = $"ユーザー{nextId}";
newRow["Age"] = 20 + nextId;
_dataTable.Rows.Add(newRow);
};
}
// ════════════════════════════════════════════════
// タブ③:BindingList バインド
// ════════════════════════════════════════════════
private void SetupBindingListTab()
{
// 初期データ
_products.Add(new Product { ID = 1, Name = "リンゴ", Price = 150 });
_products.Add(new Product { ID = 2, Name = "バナナ", Price = 100 });
_products.Add(new Product { ID = 3, Name = "メロン", Price = 800 });
// DataGridView にバインド
dataGridViewBL.DataSource = _products;
dataGridViewBL.AllowUserToAddRows = false;
// ボタンクリックで BindingList にオブジェクト追加 → 自動反映
btnAddBL.Click += (s, e) =>
{
int nextId = _products.Count + 1;
_products.Add(new Product
{
ID = nextId,
Name = $"商品{nextId}",
Price = nextId * 100
});
};
}
}
// ── BindingList 用データクラス ──────────────────────
public class Product
{
public int ID { get; set; }
public string Name { get; set; } = string.Empty;
public int Price { get; set; }
// 【ポイント】引数付きコンストラクタを定義する場合は
// 引数なしコンストラクタも明示的に書く必要があります。
public Product() { }
}
}

DataGridView_AddRow/Form1.Designer.cs

Form1.Designer.cs
namespace DataGridView_AddRow
{
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()
{
tabControl1 = new TabControl();
tabPage1 = new TabPage();
tabPage2 = new TabPage();
tabPage3 = new TabPage();
tableLayoutPanel1 = new TableLayoutPanel();
tableLayoutPanel2 = new TableLayoutPanel();
tableLayoutPanel3 = new TableLayoutPanel();
dataGridViewNoBind = new DataGridView();
dataGridViewDT = new DataGridView();
dataGridViewBL = new DataGridView();
btnAddNoBind = new Button();
btnAddDT = new Button();
btnAddBL = new Button();
tabControl1.SuspendLayout();
tabPage1.SuspendLayout();
tabPage2.SuspendLayout();
tabPage3.SuspendLayout();
tableLayoutPanel1.SuspendLayout();
tableLayoutPanel2.SuspendLayout();
tableLayoutPanel3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewNoBind).BeginInit();
((System.ComponentModel.ISupportInitialize)dataGridViewDT).BeginInit();
((System.ComponentModel.ISupportInitialize)dataGridViewBL).BeginInit();
SuspendLayout();
//
// tabControl1
//
tabControl1.Controls.Add(tabPage1);
tabControl1.Controls.Add(tabPage2);
tabControl1.Controls.Add(tabPage3);
tabControl1.Dock = DockStyle.Fill;
tabControl1.Location = new Point(0, 0);
tabControl1.Name = "tabControl1";
tabControl1.SelectedIndex = 0;
tabControl1.Size = new Size(800, 450);
tabControl1.TabIndex = 0;
//
// tabPage1
//
tabPage1.Controls.Add(tableLayoutPanel1);
tabPage1.Location = new Point(4, 34);
tabPage1.Name = "tabPage1";
tabPage1.Padding = new Padding(3);
tabPage1.Size = new Size(792, 412);
tabPage1.TabIndex = 0;
tabPage1.Text = "バインドなし";
tabPage1.UseVisualStyleBackColor = true;
//
// tabPage2
//
tabPage2.Controls.Add(tableLayoutPanel2);
tabPage2.Location = new Point(4, 34);
tabPage2.Name = "tabPage2";
tabPage2.Padding = new Padding(3);
tabPage2.Size = new Size(792, 412);
tabPage2.TabIndex = 1;
tabPage2.Text = "DataTable バインド";
tabPage2.UseVisualStyleBackColor = true;
//
// tabPage3
//
tabPage3.Controls.Add(tableLayoutPanel3);
tabPage3.Location = new Point(4, 34);
tabPage3.Name = "tabPage3";
tabPage3.Padding = new Padding(3);
tabPage3.Size = new Size(792, 412);
tabPage3.TabIndex = 2;
tabPage3.Text = "BindingList バインド";
tabPage3.UseVisualStyleBackColor = true;
//
// tableLayoutPanel1
//
tableLayoutPanel1.ColumnCount = 1;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel1.Controls.Add(dataGridViewNoBind, 0, 0);
tableLayoutPanel1.Controls.Add(btnAddNoBind, 0, 1);
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.Location = new Point(3, 3);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 2;
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 88.423645F));
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 11.576355F));
tableLayoutPanel1.Size = new Size(786, 406);
tableLayoutPanel1.TabIndex = 0;
//
// tableLayoutPanel2
//
tableLayoutPanel2.ColumnCount = 1;
tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel2.Controls.Add(dataGridViewDT, 0, 0);
tableLayoutPanel2.Controls.Add(btnAddDT, 0, 1);
tableLayoutPanel2.Dock = DockStyle.Fill;
tableLayoutPanel2.Location = new Point(3, 3);
tableLayoutPanel2.Name = "tableLayoutPanel2";
tableLayoutPanel2.RowCount = 2;
tableLayoutPanel2.RowStyles.Add(new RowStyle(SizeType.Percent, 88.423645F));
tableLayoutPanel2.RowStyles.Add(new RowStyle(SizeType.Percent, 11.576355F));
tableLayoutPanel2.Size = new Size(786, 406);
tableLayoutPanel2.TabIndex = 1;
//
// tableLayoutPanel3
//
tableLayoutPanel3.ColumnCount = 1;
tableLayoutPanel3.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel3.Controls.Add(dataGridViewBL, 0, 0);
tableLayoutPanel3.Controls.Add(btnAddBL, 0, 1);
tableLayoutPanel3.Dock = DockStyle.Fill;
tableLayoutPanel3.Location = new Point(3, 3);
tableLayoutPanel3.Name = "tableLayoutPanel3";
tableLayoutPanel3.RowCount = 2;
tableLayoutPanel3.RowStyles.Add(new RowStyle(SizeType.Percent, 88.423645F));
tableLayoutPanel3.RowStyles.Add(new RowStyle(SizeType.Percent, 11.576355F));
tableLayoutPanel3.Size = new Size(786, 406);
tableLayoutPanel3.TabIndex = 1;
//
// dataGridViewNoBind
//
dataGridViewNoBind.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewNoBind.Dock = DockStyle.Fill;
dataGridViewNoBind.Location = new Point(3, 3);
dataGridViewNoBind.Name = "dataGridViewNoBind";
dataGridViewNoBind.RowHeadersWidth = 62;
dataGridViewNoBind.Size = new Size(780, 353);
dataGridViewNoBind.TabIndex = 0;
//
// dataGridViewDT
//
dataGridViewDT.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewDT.Dock = DockStyle.Fill;
dataGridViewDT.Location = new Point(3, 3);
dataGridViewDT.Name = "dataGridViewDT";
dataGridViewDT.RowHeadersWidth = 62;
dataGridViewDT.Size = new Size(780, 353);
dataGridViewDT.TabIndex = 0;
//
// dataGridViewBL
//
dataGridViewBL.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewBL.Dock = DockStyle.Fill;
dataGridViewBL.Location = new Point(3, 3);
dataGridViewBL.Name = "dataGridViewBL";
dataGridViewBL.RowHeadersWidth = 62;
dataGridViewBL.Size = new Size(780, 353);
dataGridViewBL.TabIndex = 0;
//
// btnAddNoBind
//
btnAddNoBind.Dock = DockStyle.Fill;
btnAddNoBind.Location = new Point(3, 362);
btnAddNoBind.Name = "btnAddNoBind";
btnAddNoBind.Size = new Size(780, 41);
btnAddNoBind.TabIndex = 1;
btnAddNoBind.Text = "ボタンクリックで行を追加";
btnAddNoBind.UseVisualStyleBackColor = true;
//
// btnAddDT
//
btnAddDT.Dock = DockStyle.Fill;
btnAddDT.Location = new Point(3, 362);
btnAddDT.Name = "btnAddDT";
btnAddDT.Size = new Size(780, 41);
btnAddDT.TabIndex = 1;
btnAddDT.Text = "ボタンクリックで DataTable に行追加 → DataGridView に自動反映";
btnAddDT.UseVisualStyleBackColor = true;
//
// btnAddBL
//
btnAddBL.Dock = DockStyle.Fill;
btnAddBL.Location = new Point(3, 362);
btnAddBL.Name = "btnAddBL";
btnAddBL.Size = new Size(780, 41);
btnAddBL.TabIndex = 1;
btnAddBL.Text = "ボタンクリックで BindingList にオブジェクト追加 → 自動反映";
btnAddBL.UseVisualStyleBackColor = true;
//
// Form1
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(tabControl1);
Name = "Form1";
Text = "Form1";
tabControl1.ResumeLayout(false);
tabPage1.ResumeLayout(false);
tabPage2.ResumeLayout(false);
tabPage3.ResumeLayout(false);
tableLayoutPanel1.ResumeLayout(false);
tableLayoutPanel2.ResumeLayout(false);
tableLayoutPanel3.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewNoBind).EndInit();
((System.ComponentModel.ISupportInitialize)dataGridViewDT).EndInit();
((System.ComponentModel.ISupportInitialize)dataGridViewBL).EndInit();
ResumeLayout(false);
}
#endregion
private TabControl tabControl1;
private TabPage tabPage1;
private TabPage tabPage2;
private TabPage tabPage3;
private TableLayoutPanel tableLayoutPanel1;
private TableLayoutPanel tableLayoutPanel2;
private TableLayoutPanel tableLayoutPanel3;
private DataGridView dataGridViewNoBind;
private DataGridView dataGridViewDT;
private DataGridView dataGridViewBL;
private Button btnAddNoBind;
private Button btnAddDT;
private Button btnAddBL;
}
}

DataGridView_AddRow/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_AddRow/Program.cs

Program.cs
namespace DataGridView_AddRow
{
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());
}
}
}