Skip to content

Instantly share code, notes, and snippets.

@KentaYamada
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KentaYamada/9066065 to your computer and use it in GitHub Desktop.
Save KentaYamada/9066065 to your computer and use it in GitHub Desktop.
List<T>のデータをDataGridViewへ格納、データ取り出しサンプル
// DataTable & DataSetは列名の指定と型のコンバート処理が発生して冗長
// データ構造を柔軟にかつインテリセンスで出てくれるように操作できないかと思って作ってみました。
// DBでList<T>で取得するには、LINQ to SQLがベスト!?と今のところ考えてます。
// 大雑把にコーディングしたので、利用される方は参考程度で見ていただけたらありがたいです。
// DataGridViewで生成した列とバインドしたい場合は、デザイナからDataPropertyNameに格納するプロパティ名を記述することでバインド可能です。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DataGridView_List
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//サンプルデータ作成
var sam1 = new Sample();
sam1.Id = 1;
sam1.Name = "Tarou";
var sam2 = new Sample();
sam2.Id = 2;
sam2.Name = "Jirou";
var list = new List<Sample>();
list.Add(sam1);
list.Add(sam2);
//List<T>型データをDataGridViewに格納
this.dataGridView1.DataSource = list;
}
private void button1_Click(object sender, EventArgs e)
{
List<Sample> list = this.dataGridView1.DataSource as List<Sample>;
//一番目のデータの型名を取り出してメッセージボックスで表示
//DataTable & DataSetと違って、行列操作にインテリセンス表示、型変換も気にせずできるのはありがたい!!
MessageBox.Show(list[0].Name.GetType().Name, list[0].Id.GetType().Name);
}
}
///<summary>
/// テスト用データクラス
///</summary>
public class Sample
{
public Sample()
{ }
public int Id { get; set; }
public string Name { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment