DataGridview绑定复杂对象

假设有一个类

DataGridview绑定复杂对象
class Person
    {
        private string id;
        private string name;
        private Address homeAddr;
        public string ID
        {
            get { return id; }
            set { id = value; }
        }
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public Address HomeAddr
        {
            get { return homeAddr; }
            set { homeAddr = value; }
        }
    }

    class Address
    {
        private string cityname;
        private string postcode;
        public string CityName
        {
            get { return cityname; }
            set { cityname = value; }
        }
        public string PostCode
        {
            get { return postcode; }
            set { postcode = value; }
        }
    }
DataGridview绑定复杂对象

将类绑定到Datagridview

DataGridview绑定复杂对象
List<Person> lst = new List<Person>();
            for (int i = 0; i < 10000; ++i)
            {
                lst.Add(new Person()
                {
                    ID = "1",
                    Name = "name",
                    HomeAddr = new Address() { CityName = “CityName”, PostCode = “PostCode ”}
                });
            }
            dataGridView1.DataSource = lst;
DataGridview绑定复杂对象

DataGridview绑定复杂对象

其实值已经有了,只是Datagridview不显示。可以通过DataPropertyName指定子属性名字,在CellFormatting事件中通过反射获取。

DataGridview绑定复杂对象

DataGridview绑定复杂对象
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if ((dataGridView1.Rows[e.RowIndex].DataBoundItem != null) &&
                (dataGridView1.Columns[e.ColumnIndex].DataPropertyName.Contains(".")))
            {
                string[] names = dataGridView1.Columns[e.ColumnIndex].DataPropertyName.Split(.);
                object obj = dataGridView1.Rows[e.RowIndex].DataBoundItem;
                for (int i = 0; i < names.Count(); ++i)
                {
                    try
                    {
                        var result = obj.GetType().GetProperty(names[i]).GetValue(obj, null);
                        obj = result;
                        e.Value = result.ToString();
                    }
                    catch (Exception)
                    {
                        return;
                        throw;
                    }
                }
            }
        }
DataGridview绑定复杂对象

结果发现Datagridview列多了

DataGridview绑定复杂对象

可以指定dataGridView1的AutoGenerateColumns属性为false,让datagridview不自动生成列。(要在绑定前指定)

 


DataGridview绑定复杂对象,布布扣,bubuko.com

DataGridview绑定复杂对象

上一篇:Windows 8.1 应用再出发 - 创建我的第一个应用


下一篇:Windows如何安装自定义服务