C# List<T> 转 DataTable

C # List<T>turnDataTable

Learning From: blog Garden <step-hyun to eat cat>

Overview

data! ! Personally I think that the program is changing the pattern of the data shows it. So this time we get on data processing and when our critical step, if you have data handled properly, what about the image data display it.

List<T> 转 DataTable

We here use Entity Frameworkto get data from the database.
We look at the complete source code:

void ListToDataTable()
{
    using (var context = new WorldSkillsChina2016Entities())
    {
        List<User> userList = (from a in context.User select a).ToList<User>();//将查询出来的User表 转换成一个集合

        DataTable dt = new DataTable();//创建一个DataTable来存储数据

        PropertyInfo[] properties = new User().GetType().GetProperties();//然后我们获取User表的所有属性。注意:是属性而不是字段。

        foreach (var item in properties)//根据我们的属性创建DataTable的列
        {
            dt.Columns.Add(item.Name, item.PropertyType);
        }

        for (int i = 0; i < userList.Count; i++)//使用for循环添加数据
        {
            object[] objects = new object[properties.Length];//创建一个和User类等长的数组。

            for (int a = 0; a < properties.Length; a++)
            {
                objects[a] = properties[a].GetValue(userList[i], null);//循环添加数据
            }

            dt.LoadDataRow(objects, true);//将数据作为一整行的形式添加到我们的DataGridView中。
        }
        this.dataGridView1.DataSource = dt;//数据实现绑定。
    }

}

Then we According to our source code to explain.

  • First, we create a List<User>receive data our User table.
  • Then we create a DataTable.
  • Get all the properties of the User class, but the property does not contain the field.
  • Use foreach according to the attributes of the User class to create our DataTable columns.
  • Then add the data used for loop
    • Create an array of a long table and User attributes.
    • Each cycle User objects according to the specified property values ​​acquired, and in order to pay the specified position in the array.
    • The entire array in rows added to our DataTable.
  • Finally, this DataTableand DataGridView bind.

Guess you like

Origin www.cnblogs.com/cao-1/p/12075990.html