Since listview control in .net framework 2.0 does not have a datasource property, it is not bindable to neither datatable nor generic lists. i created a derived custom listview that is bindable to lists of any type. i attach the .zip to this thread.
I dedicate this custom windows control to Julienne Walker.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;
namespace SmartListView
{
public partial class SmartListView : ListView
{
public SmartListView()
{
InitializeComponent();
}
private IList dataSource = null;
public IList DataSource
{
get
{
return dataSource;
}
set
{
dataSource = value;
if(dataSource != null)
CreateItems();
}
}
private string[] columnHeaders = null;
public string[] ColumnHeaders
{
set
{
columnHeaders = value;
}
}
private void CreateItems()
{
if (dataSource.Count > 0)
{
PropertyInfo[] properties = dataSource[0].GetType().GetProperties();
if(properties.Length > 0)
{
if (columnHeaders != null)
{
foreach (string columnName in columnHeaders)
{
Columns.Add(columnName);
}
}
else
{
foreach (PropertyInfo pInfo in properties)
{
Columns.Add(pInfo.Name);
}
}
for (int i = 0; i < dataSource.Count; i++)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = properties[0].GetValue(dataSource[i],null).ToString();
for (int propIndex = 1; propIndex < properties.Length;propIndex++)
{
lvi.SubItems.Add(properties[propIndex].GetValue(dataSource[i], null).ToString());
}
Items.Add(lvi);
}
}
}
}
}
}
namespace SmartListView
{
partial class SmartListView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.View = System.Windows.Forms.View.Details;
}
#endregion
}
}