Convert generic List/Enumerable to DataTable?

后端 未结 27 2599
臣服心动
臣服心动 2020-11-21 23:20

I have few methods that returns different Generic Lists.

Exists in .net any class static method or whatever to convert any list into a datatable? The only thing tha

27条回答
  •  日久生厌
    2020-11-21 23:48

    if you have properties in your class this line of code is OK !!

    PropertyDescriptorCollection props =
                TypeDescriptor.GetProperties(typeof(T));
    

    but if you have all public fields then use this:

    public static DataTable ToDataTable(  IList data)
            {
            FieldInfo[] myFieldInfo;
            Type myType = typeof(T);
            // Get the type and fields of FieldInfoClass.
            myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance
                | BindingFlags.Public);
    
            DataTable dt = new DataTable();
            for (int i = 0; i < myFieldInfo.Length; i++)
                {
                FieldInfo property = myFieldInfo[i];
                dt.Columns.Add(property.Name, property.FieldType);
                }
            object[] values = new object[myFieldInfo.Length];
            foreach (T item in data)
                {
                for (int i = 0; i < values.Length; i++)
                    {
                    values[i] = myFieldInfo[i].GetValue(item);
                    }
                dt.Rows.Add(values);
                }
            return dt;
            }
    

    the original answer is from above , I just edited to use fields instead of properties

    and to use it do this

     DataTable dt = new DataTable();
                dt = ToDataTable(myBriefs);
                gridData.DataSource = dt;
                gridData.DataBind();
    

提交回复
热议问题