DataGridViewのDataSourceにList<Model>を渡すとき、DataTableからList<Model>に代入をReflectionで作ってみる。普段はそのまま名前を書いてしまうことも多い。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
private List<EmployeeModel> CreateModel(string queryString) { var modelType = typeof(EmployeeModel); // GetType() var models = new List<EmployeeModel>(); List<string> propNameList = new List<string>(modelType.GetProperties().Select(x => x.Name)); var dt = ExecuteQuery(queryString); for (int r = 0; r < dt.Rows.Count; r++) { var constructor = modelType.GetConstructor(System.Type.EmptyTypes); var model = (EmployeeModel)constructor.Invoke(null); // (EmployeeModel)Activator.CreateInstance(modelType); foreach(var propName in propNameList) { modelType.GetProperty(propName).SetValue(model, dt.Rows[r][propName].ToString()); } models.Add(model); } return models; } |