Monday, February 19, 2018

C# DataGridView 에 바인딩 하는 여러가지 방법


1. List

public class Member
{
  public string Name {get; set}
  public int Age {get; set;}
  public Member(string name, int age)
  {
    this.Name = name;
    this.Age = age;
  }
}
protected List GetMember()
{
  List<member> lm = new List<member>();
  Member m = new Member("John",20);
  lm.Add(m);
  m = new Member("Marry",21);
  lm.Add(m);
  m = new Member("Jane",18);
  lm.Add(m);
  return lm;
}
dataGridView.DataSource = GetMember();
2. DataTable

DataTable d = new DataTable();
d.Columns.Add("Name",typeof(string));
d.Columns.Add("Age",typeof(int));
d.Rows.Add("John",20);
d.Rows.Add("Marry",21);
d.Rows.Add("Jane",18);
dataGridView.DataSource = d;

3. LINQ

protected List<member> GetMember()
{
  List<member> lm = new List<member>();
  Member m = new Member("John",20);
  lm.Add(m);
  m = new Member("Marry",21);
  lm.Add(m);
  m = new Member("Jane",18);
  lm.Add(m);
  return lm;  
}
List<member> lm = GetMember(); 
int i=0;
var cols = from q in lm 
orderby q.Name  
select new  
{  
  i = ++i,
  Name = q.Name,  
  Age = q.Age  
};
dataGridView.DataSource = cols.ToList();

4. Array

public class Member
{
  public string Name {get; set}
  public int Age {get; set;}
  public Member(string name, int age)
  {
    this.Name = name;
    this.Age = age;
  }
}
var arr = new[] {  
  new Member("John", 20),  
  new Member("Marry", 21),
  new Member("Jane", 18)
};  
dataGridView.Source = arr;

5. 2 Array

string[][] Array = new string[10][];
for (int i = 0; i < 10; i++)  
  Array[i] = new string[2] { "NUM:"+i, "ID:"+i };  
var d = (from arr in Array select new { num = arr[0], id = arr[1] }); 
dataGridView.Source = d.ToList();

6. Direct

dataGridView.ColumnCount = 2;  
dataGridView.Columns[0].Name = "Name";  
dataGridView.Columns[1].Name = "Age";  
string[] r = new string[] {"John", "20" };  
dataGridView.Rows.Add(r);  
r = new string[] {"Marry", "21" };  
dataGridView.Rows.Add(r);  
r = new string[] {"Jane", "18" };  
dataGridView.Rows.Add(r);  

No comments:

Post a Comment