Populating WinForms Controls at Runtime with C#


Populate a DataTable with an Array using C#

The method below fills a DataTable with values from an array. Paste this method into the form's code body:

DataTable FillTableWithArray()
{
  object[] dataArray = {<yourArrayValues>};
  
  DataTable dataTable = new DataTable();
  for(int c = 0; c < dataArray.Rank; c++) {
    dataTable.Columns.Add("Mountain_States");
  }
  for(int r = 0; r < dataArray.Length; r++) {
    dataTable.Rows.Add(dataArray[r].ToString());
  }
  return dataTable;
}

The FillTableWithArray() method can now be called as the DataTable argument when instantiating the rendering 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>, FillTableWithArray());

Or this (for a ListView):

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

Next Topic