C # Reflection Application

Source: Internet
Author: User

Consider this is because the object collection is returned, it is necessary to bind the object collection to DataGridView, binding DataGridView need the data source, assemble the data, it is troublesome to add columns with a DataTable, so it is possible to use reflection to achieve, it is estimated that there may be more than one place, May be used by different objects, so it is defined as generic

public class Datatablelisthelper<t> {public static DataTable Getdatatablehelper (list<t> items)            {DataTable dt = new DataTable (); Type t = items[0].            GetType ();            propertyinfo[] PiS = t.getproperties (); foreach (PropertyInfo pi in PiS) {dt. Columns.Add (pi.            Name); } foreach (T item in items) {DataRow dr = dt.                NewRow (); foreach (PropertyInfo pi in PiS) {Object obj = Pi.                    GetValue (item, NULL); Switch (pi. PropertyType.Name.ToString (). ToLower ()) {case "datetime": Dr[pi. Name] = convert.todatetime (obj).                            ToString ("Yyyy-mm-dd");                        Break Case "Int32": Dr[pi.                            Name] = Convert.ToInt32 (obj);                        Break Case "Double": Dr[pi.                            Name] = convert.todouble (obj);                        Break Default:dr[pi.                            Name] = obj;                    Break }} dt.            Rows.Add (DR);        } return DT; }    }

Switch type is not very full, you need to add some types

Conversely, if you convert a DataTable to an object, you can do it with reflection.

C # Reflection Application

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.