How to bind DataGridView's multiple columns to a custom class's fields?

亡梦爱人 提交于 2019-12-31 07:29:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!