1using System;2using System.Collections.Generic;3using System.ComponentModel;4using System.Data;5using System.Drawing;6using System.Linq;7using System.Text;8using System.Threading.Tasks;9using System.Windows.Forms;1011namespace WinFormsApp1
12{13 public partial class Form6 : Form
14{15// デザイナで DataGridView をドラッグ&ドロップしてデザイン16// 画面でそれを編集した方が簡単ですが、ここではコードで書いておきます17 private DataGridView dataGridView1;18 private DataGridViewTextBoxColumn column1;19 private DataGridViewTextBoxColumn column2;20 private DataGridViewTextBoxColumn column3;2122 private BindingSource bindingSource1;2324 public Form6()25{26InitializeComponent();2728 this.dataGridView1 = new DataGridView();29 this.column1 = new DataGridViewTextBoxColumn();30 this.column2 = new DataGridViewTextBoxColumn();31 this.column3 = new DataGridViewTextBoxColumn();3233 this.dataGridView1.Columns.AddRange(new DataGridViewColumn[]{ this.column1, this.column2, this.column3});34 this.dataGridView1.Dock = DockStyle.Fill;3536 this.column1.DataPropertyName ="Id";37 this.column1.HeaderText ="No.";3839 this.column2.DataPropertyName ="Name";40 this.column2.HeaderText ="ユーザー名";4142 this.column3.DataPropertyName ="Age";43 this.column3.HeaderText ="年齢";4445 this.components = new Container();46 this.bindingSource1 = new BindingSource(this.components);47 this.dataGridView1.DataSource = this.bindingSource1;48 this.Controls.Add(this.dataGridView1);4950// List<T> 型(T は下に定義した Item クラス)のデータソースを作成51 List<Item> list = new List<Item>52{53 new Item { Id =1, Name ="ユーザー1", Age =28},54 new Item { Id =2, Name ="ユーザー2", Age =22},55 new Item { Id =3, Name ="ユーザー3", Age =34}56};5758 this.bindingSource1.DataSource = list;59}6061// これはオマケです。一番最初の行にデータを追加する例です。62 private voidbutton1_Click(object sender, EventArgs e)63{64 Item item = new Item { Id =4, Name ="ユーザー4", Age =22};65 this.bindingSource1.Insert(0, item);66}67}6869// これが List<T> の T クラスの定義です。70 public class Item
71{72 public int Id { get; set;}73 public string Name { get; set;}74 public int Age { get; set;}75}76}