by Bar Zohan
21. January 2010 02:06
Generic ListView is a class that derives from standart ListView of .Net Framework. But it can also take a generic list as datasource and databind itself to it.
Here is the code
public class ListViewGeneric: ListView
{
public delegate void ItemBoundingHandler(ListViewItem sender,object e);
public event ItemBoundingHandler ItemBounding;
public ListViewGeneric()
{
this.View = View.Details;
this.FullRowSelect = true;
}
public object DataSource { get; set; }
public bool AlternatifColumn { get; set; }
public Color AlternatifColumnColor { get; set; }
public void DataBind()
{
IList dataSourceAsList = (IList)DataSource;
foreach (PropertyInfo pi in dataSourceAsList[0].GetType().GetProperties())
{
ColumnHeader ch = new ColumnHeader();
ch.Text = pi.Name;
this.Columns.Add(ch);
}
int j = 0;
foreach (object t in dataSourceAsList)
{
int i = 0;
ListViewItem li = new ListViewItem();
foreach (PropertyInfo pt in t.GetType().GetProperties())
{
ItemBounding(li, t);
if (i == 0)
{
li.Text = pt.GetValue(t, null).ToString();
li.Tag = t;
}
else
{
li.SubItems.Add(pt.GetValue(t, null).ToString());
li.Tag = t;
}
i++;
}
if ((j % 2) == 0 && AlternatifColumn)
li.BackColor = AlternatifColumnColor;
this.Items.Add(li);
j++;
}
}
}
Some Explanation
DataBind method first selects the first object of the list and loops through it's property fields using reflection. By doing this it creates column structure of our listview.
After creating columns we enumerate the list that we've taken as datasource. Foreach object, we create a new row and put the related property values into appropriate columns. Also as it databinds each row it fires an ItemBound event too.
I really don't know why I did this whole thing but I think I was just really bored those days 
Sample Usage
//HERE LST OBJECT IS OUR GENERIC LISTVIEW
List<Personel> Personeller = new List<Personel>();
Personel Kisi = new Personel();
Kisi.ID = 1;
Kisi.Adi = "Dandan";
Kisi.SoyAdi = "Akan";
Personel Kisi1 = new Personel();
Kisi1.ID = 2;
Kisi1.Adi = "Teytey";
Kisi1.SoyAdi = "Reflection";
Personel Kisi3 = new Personel();
Kisi3.ID = 3;
Kisi3.Adi = "Kerry";
Kisi3.SoyAdi = "King";
Personeller.Add(Kisi);
Personeller.Add(Kisi1);
Personeller.Add(Kisi3);
lst.DataSource = Personeller;
lst.DataBind();
