C# List 轉 DataTable


C# List<T>DataTable

學習自:博客園<吃了炫邁的貓>

Overview

數據!!個人認為程序就是將數據變着花樣的顯示它。那么這個時候我們的數據處理和獲取就時我們的關鍵一步,如果你數據都處理不好,何談形象的顯示數據呢。

List<T> 轉 DataTable

我們這邊使用Entity Framework從數據庫獲取數據。
我們先看一下完整的源碼:

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;//數據實現綁定。
    }

}

接着我們根據我們的源碼來講解一下。

  • 首先我們創建了一個List<User>來接收我們的User表的數據。
  • 然后我們創建一個DataTable
  • 獲取User類的所有屬性,只是屬性不包含字段。
  • 使用foreach 根據User類的屬性,來創建我們DataTable的列。
  • 接着使用for循環添加數據
    • 創建一個和User表屬性等長的一個數組 。
    • 循環每個User對象根據的指定屬性獲取值,並依次付給數組的指定位置。
    • 將整個數組以行的方式添加到我們的DataTable中。
  • 最后將這個DataTable和DataGridView 進行綁定。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM