Populating WinForms Controls at Runtime with C#


Populate a Winforms ListView at Runtime Using C#

The ListView is a powerful and dynamic WinForms presentation control. It can display data as text, icons or both across multiple columns and rows. In Details view it presents data in tabular form, like this:

A Simple WinForms ListView

C# ListView

Items can be manually added to a ListView at design time using the control's Items property.

IDE Properties View

properties view screenshot


A more powerful solution is to populate the control programatically at runtime. The C# class below fills a WinForms ListView at runtime using a DataTable.

Create a new class file called ListViewRenderer.cs and paste the code below into it. Replace the yourNamespace placeholder with you own project's namespace.

UML Class Diagram

UML Class Diagram

using System;
using System.Data;
using System.Windows.Forms;

namespace yourNamespace
{
  public class ListViewRenderer
  {
    ListView listView;
    DataTable dataTable;

    public ListViewRenderer(ListView listView, DataTable dataTable)
    {
      this.listView = listView;
      this.dataTable = dataTable;
      PopulateControl(); 
    }
    
    public void PopulateControl()
    {
      listView.Items.Clear();
      listView.Columns.Clear();
    
      foreach(DataColumn dc in dataTable.Columns)
      {
        this.listView.Text = dc.ColumnName;
        this.listView.Columns.Add(dc.ColumnName);
      }
      
      for (int i = 0; i < dataTable.Rows.Count; i++)
      {
        DataRow row = dataTable.Rows[i];
        ListViewItem listViewItem = new ListViewItem(row[0].ToString().Trim());
        for (int c = 1; c < dataTable.Columns.Count; c++)
        {
          listViewItem.SubItems.Add (row[c].ToString());
        }
        listView.Items.Add(listViewItem);
      }
    }
  }
}

Drag and drop a ListView onto your Windows form. To use the ListViewRenderer class in your code, instantiate a new object in the form's code, providing the name of your ListView and your DataTable in the method's arguments, like this:

ListViewRenderer lvR = new ListViewRenderer(<yourListView>, <yourDataTable>);

Place the above snippet in the form's constructor, load event or other method. You're now ready to create and populate a DataTable to pass to the new ListViewRenderer object and populate the WinForms ListView.


Next Topic