Populating WinForms Controls at Runtime with C#


Populate a DataTable with Explicit Values using C#

The C# method below fills a DataTable with explicit values. Paste this method into the form's code body:

DataTable FillTableWithValues() {
   DataTable dataTable = new DataTable();
   //sample values
   dataTable.Columns.Add("Mountain_States");
   dataTable.Rows.Add("Arizona");
   dataTable.Rows.Add("Colorado");
   dataTable.Rows.Add("Idaho");
   dataTable.Rows.Add("Montana");
   dataTable.Rows.Add("Nevada");
   dataTable.Rows.Add("New Mexico");
   dataTable.Rows.Add("Utah");
   dataTable.Rows.Add("Wyoming");
   return dataTable;
  }

The FillTableWithValues() method can now be called as the DataTable argument when instantiating the control classes, as discussed elsewhere on this site. With the rendering classes added to your project, call the method within the form's constructor, load event or other method, like this (for a ComboBox):

ComboBoxRenderer cBr = new ComboBoxRenderer(<yourComboBox>, FillTableWithValues());

Or this (for a ListView):

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

Next Topic