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

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;

image

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

image

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列多了

image

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

 


你可能感兴趣的:(datagridview)