Populating WinForms Controls at Runtime with C#


Populate a WinForms ComboBox at Runtime Using C#

The WinForms ComboBox control (a combination of a text input box and a drop-down list) presents a single selected text item and displays an intuitive drop down list of selectable items, like this:

A Simple WinForms ComboBox

ComboBox screenshot

Items can be manually added to a ComboBox 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 using its DataSource property.

IDE properties view

properties view screenshot


The C# class below populates a WinForms ComboBox at runtime by binding its DataSource to a DataTable.

Create a new class file called ComboBoxRenderer.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 ComboBoxRenderer
  {
    ComboBox comboBox;
    DataTable dataTable;
  
    public ComboBoxRenderer(ComboBox comboBox, DataTable dataTable)
    {
      this.comboBox = comboBox;
      this.dataTable = dataTable;
      PopulateControl();
    }
    
    public void PopulateControl()
    {
      comboBox.DataSource = dataTable;
      
      foreach (DataColumn c in dataTable.Columns)
      {
        switch (c.Ordinal) {
          case 0:
            comboBox.ValueMember = c.ColumnName;
            break;
          case 1:
            comboBox.DisplayMember = c.ColumnName;
            break;
          default:
            break;
        }
      }
    }
  }
}

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

ComboBoxRenderer cBr = new ComboBoxRenderer(<yourComboBox>, <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 ComboBoxRenderer class and populate the WinForms ComboBox.


Next Topic