Merhaba arkadaslar bu makalemizde DataTable da olusturdugumuz listeyi tanimlayacagiz ve bu tanimladigimiz listeyi dataGridView nesnesinde gosterecegiz.
Sekil 1
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
namespace list_to_datatable
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Miami");
cities.Add("Los Angles");
cities.Add("London");
cities.Add("Paris");
cities.Add("Berlin");
cities.Add("Rome");
cities.Add("Barcelona");
cities.Add("Madrid");
cities.Add("Tokyo");
cities.Add("Buenos Aires");
cities.Add("Hong Kong");
cities.Add("Singapore");
cities.Add("Dubai");
cities.Add("Toronto");
cities.Add("Istanbul");
cities.Add("Chicago");
cities.Add("Beijing");
cities.Add("Sydney");
cities.Add("Amsterdam");
cities.Add("Seoul");
cities.Add("Zurich");
cities.Add("Rio de Janerio");
cities.Add("Delhi");
cities.Add("Bangkok");
DataTable dt =listtodatatable(cities);
dataGridView1.DataSource = dt;
}
public static DataTable listtodatatable<T>(IList<T> thisList)
{
DataTable dt = new DataTable();
if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
{
DataColumn col = new DataColumn("Top 25 Cities");
dt.Columns.Add(col);
foreach (T item in thisList)
{
DataRow dr = dt.NewRow();
dr[0] = item;
dt.Rows.Add(dr);
}
}
else
{
PropertyInfo[] pInfo = typeof(T).GetProperties();
foreach (PropertyInfo pinfo in pInfo)
{
DataColumn dc = new DataColumn(pinfo.Name, pinfo.PropertyType);
dt.Columns.Add(dc);
}
for (int item = 0; item < thisList.Count(); item++)
{
DataRow dr = dt.NewRow();
for (int property = 0; property < pInfo.Length; property++)
{
dr[property] = pInfo[property].GetValue(thisList[item], null);
}
dt.Rows.Add(dr);
}
}
dt.AcceptChanges();
return dt;
}
}
}
Bir makalenin daha sonuna geldik. Bir sonraki makalede gorusmek uzere. Bahadir SAHIN
0 comments:
Yorum Gönder