Entitiy Collection To DataTable
04.02.2009 19:22
N-tier kullandığınız projelerinizde verileri Entity ile taşıyorsanız WindowsForm uygulamalarında DataGrid'de yeni kayıt özelliğinin çalışmadığını farketmişsinizdir.
Bunun için DataGrid'e Entity Collection yerine DataTable vermeniz gerekir.
Elinizdeki Entity Collection nesnesini DataTable'a çevirmek için kullanacabileceğiniz bir fonksiyon.
public static DataTable
ToDataTable<T>(Collection<T> list)
{
if (list == null)
throw new MethodParameterNullException("list");
DataTable table = new DataTable();
System.Reflection.PropertyInfo[] properties = list[0].GetType().GetProperties();
List<string>
columns = new List<string>();
foreach (System.Reflection.PropertyInfo pi in
properties)
{
table.Columns.Add(pi.Name);
columns.Add(pi.Name);
}
foreach (T item in
list)
{
object[]
cells = new object[columns.Count];
for (int i = 0; i < columns.Count; i++)
{
System.Reflection.PropertyInfo pi =
item.GetType().GetProperty(columns[i]);
if
(pi == null) throw
new Exception(String.Format("{0}
property not found in {1}", columns[i], item.GetType().FullName));
cells[i] = pi.GetValue(item, null);
}
table.Rows.Add(cells);
}
return table;
}
For use :
this.dataGridView1.DataSource = IVR.Manager.Data.Utility.ToDataTable<SipProfiles>(new SipProfilesFactory().GetAll());
Special Thanks : Ozan Vural
Bu yazı 533 kere okundu.



