问题
Suppose I have a simple class, and list of its instances:
public class Class1
{
public int a;
public int b;
}
List<Class1> l = new List<Class1>();
l.AddRange(new[] { new Class1 { a = 1, b = 2 }, new Class1 { a = 3, b = 4 } });
How do I bind a DataGridView with columns for a
and b
to it?
I've found answers, but not any that work. This should be simple, but I can't figure it out.
回答1:
assuming that you have columns colA
and colB
, set their DataPropertyName
property and set grid DataSource
colA.DataPropertyName = "a";
colB.DataPropertyName = "b";
grid.DataSource = l;
回答2:
You can do like this
DataTable dt= new DataTable();
dt.Columns.Add("a");
dt.Columns.Add("b");
foreach(var v in l)
{
dt.Rows.Add(v.a,v.b);
}
dgv.DataSource=dt;
来源:https://stackoverflow.com/questions/32180392/how-to-bind-datagridviews-multiple-columns-to-a-custom-classs-fields