public static DataTable ToDataTable(List items) { DataTable dataTable = new DataTable(typeof(T).Name); //Get all the properties PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in Props) { //Setting column names as Property names dataTable.Columns.Add(prop.Name); } foreach (T item in items) { var values = new object[Props.Length]; for (int i = 0; i < Props.Length; i++) { //inserting property values to datatable rows values[i] = Props[i].GetValue(item, null); } dataTable.Rows.Add(values); } //put a breakpoint here and check datatable return dataTable; }
变量声明:
DataTable tempTable = new DataTable(); DataTable slectedFieldsTable = new DataTable(); DataRow newRow; List
在DataTable中添加列:
slectedFieldsTable = new DataTable(); slectedFieldsTable.Columns.Add("Field Name"); slectedFieldsTable.Columns.Add("Field Type");
public static DataTable ToDataTable(this IList lst, bool includeAll = true) { DataTable dt = new DataTable(); DataColumn dc; PropertyDescriptor pd; bool Browsable; PropertyDescriptorCollection propCol = TypeDescriptor.GetProperties(typeof(T)); for (int n = 0; n < propCol.Count; n++) { pd = propCol[n]; Type propT = pd.PropertyType; dc = new DataColumn(pd.Name); // if Nullable, get underlying type // the first test may not be needed if (propT.IsGenericType && Nullable.GetUnderlyingType(propT) != null ) { propT = Nullable.GetUnderlyingType(propT); dc.DataType = propT; dc.AllowDBNull = true; } else { dc.DataType = propT; dc.AllowDBNull = false; } // is it readonly? if (pd.Attributes[typeof(ReadOnlyAttribute)] != null) { dc.ReadOnly = ((ReadOnlyAttribute)pd. Attributes[typeof(ReadOnlyAttribute)]).IsReadOnly; } // DefaultValue ... if (pd.Attributes[typeof(DefaultValueAttribute)] != null) { dc.DefaultValue = ((DefaultValueAttribute)pd. Attributes[typeof(DefaultValueAttribute)]).Value; } // caption / display name dc.ExtendedProperties.Add("DisplayName", dc.Caption); if (pd.Attributes[typeof(DisplayNameAttribute)] != null) { // these are usually present but blank string theName = ((DisplayNameAttribute)pd. Attributes[typeof(DisplayNameAttribute)]).DisplayName; dc.Caption = string.IsNullOrEmpty(theName) ? dc.Caption : theName; // DGV doesnt use Caption...save for later dc.ExtendedProperties["DisplayName"] = dc.Caption; } Browsable = true; dc.ExtendedProperties.Add("Browsable", Browsable); var foo = pd.Attributes[typeof(BrowsableAttribute)]; if (pd.Attributes[typeof(BrowsableAttribute)] != null) { Browsable = ((BrowsableAttribute)pd.Attributes[typeof(BrowsableAttribute)]).Browsable; // no such thing as a NonBrowsable DataColumn dc.ExtendedProperties["Browsable"] = Browsable; } // ToDo: add support for custom attributes if (includeAll || Browsable) { dt.Columns.Add(dc); } } // the lst could be empty such as creating a typed table if (lst.Count == 0) return dt; if (lst[0] is IDataValuesProvider) { IDataValuesProvider dvp; // copy the data - let the class do the work foreach (T item in lst) { dvp = (IDataValuesProvider)item; dt.Rows.Add(dvp.GetDataValues(includeAll).ToArray()); } } else { List values; foreach (T item in lst) { values = new List(); // only Browsable columns added for (int n = 0; n < dt.Columns.Count; n++) { values.Add(propCol[dt.Columns[n].ColumnName].GetValue(item)); } dt.Rows.Add(values.ToArray()); } } return dt; }
public interface IDataValuesProvider { IEnumerable GetDataValues(bool includeAll); } ... on the class: public class StockItem : IDataValuesProvider { public int Id { get; set; } public string ItemName {get; set;} [Browsable(false), DisplayName("Ignore")] public string propA {get; set;} [ReadOnly(true)] public string Zone { get; set; } public string Size {get; set;} [DisplayName("Nullable")] public int? Foo { get; set; } public int OnHand {get; set;} public string ProdCode {get; set;} [Browsable(false)] public string propB { get; set; } public DateTime ItemDate {get; set;} // IDataValuesProvider implementation public IEnumerable GetDataValues(bool IncludeAll) { List values = new List(); values.AddRange(new object[] {Id, ItemName }); if (IncludeAll) values.Add(propA); values.AddRange(new object[] { Zone, Size, Foo, OnHand, ProdCode }); if (IncludeAll) values.Add(propB); values.Add(ItemDate); return values; } }
var dtX = someData.ToDataTable(); dgvB.SuspendLayout(); dgvB.DataSource = dtX; // process extended props foreach (DataColumn dc in dtX.Columns) { // no need to test, the code adds them everytime //if (dc.ExtendedProperties.ContainsKey("DisplayName")) //{ dgvB.Columns[dc.ColumnName].HeaderText = dc.ExtendedProperties["DisplayName"].ToString(); //} //if (dc.ExtendedProperties.ContainsKey("Browsable")) //{ dgvB.Columns[dc.ColumnName].Visible = (bool)dc.ExtendedProperties["Browsable"]; //} } dgvB.ResumeLayout();