DataTable转换成ObservableCollection

工作中遇到了一个需求,我想把数据库查出来的数据动态绑定到一个Datagrid,但是问题是,Datatable的数据作为数据源不能始时的更新列表,所以就想把DataTable先转换成一个实现了InotyfiProperty接口的ObservableCollection的集合,然后再把ObservableCollection作为数据源绑定。转换成ObservableCollection的代码如下:

        public ObservableCollection ToObservableCollection(DataTable dt) where T :     class, new()
        {
            Type t = typeof(T);
            PropertyInfo[] propertys = t.GetProperties();
            ObservableCollection lst = new ObservableCollection();
            string typeName = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                T entity = new T();
                foreach (PropertyInfo pi in propertys)
                {
                    typeName = pi.Name;
                    if (dt.Columns.Contains(typeName))
                    {
                        if (!pi.CanWrite) continue;
                        object value = dr[typeName];
                        if (value == DBNull.Value) continue;
                        if (pi.PropertyType == typeof(string))
                        {
                            pi.SetValue(entity, value.ToString(), null);
                        }
                        else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?))
                        {
                            pi.SetValue(entity, int.Parse(value.ToString()), null);
                        }
                        else if (pi.PropertyType == typeof(DateTime?) || pi.PropertyType == typeof(DateTime))
                        {
                            pi.SetValue(entity, DateTime.Parse(value.ToString()), null);
                        }
                        else if (pi.PropertyType == typeof(float))
                        {
                            pi.SetValue(entity, float.Parse(value.ToString()), null);
                        }
                        else if (pi.PropertyType == typeof(double))
                        {
                            pi.SetValue(entity, double.Parse(value.ToString()), null);
                        }
                        else
                        {
                            pi.SetValue(entity, value, null);
                        }
                    }
                }
                lst.Add(entity);
            }
            return lst;
        }

实现的就是一个简单的把Datatable作为一个参数,把ObservableCollection的泛型返回。

你可能感兴趣的:(WPF,C#)