Populating WinForms Controls at Runtime with C#


Populate a DataTable from a Database using C#

The C# method below fills and returns a DataTable from an SQL database table. Paste this method into the form's code body. Replace the ConnectionString property with a connection string to your own database:

DataTable GetData(string sql)
{
  string connectionString = "<yourConnectionString>";
  
  //Example SQL Server connectionstring format:
  //@"Server=<yourServerAddress>;Database=<yourDataBase>;Integrated Security=True;"

  DataTable dataTable = new DataTable();
  SqlConnection connection = new SqlConnection(connectionString);
  SqlCommand command = new SqlCommand(sql, connection);
  connection.Open();
  dataTable.Load(command.ExecuteReader());
  return dataTable;
}

The GetData() method can now be called as the DataTable argument when instantiating the rendering classes, as discussed elsewhere on this site. The method takes a string as an argument. The string should be an SQL SELECT query containing the fields to be displayed in the control. 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):

string sql = "<yourSELECTQuery>";
ComboBoxRenderer cBr = new ComboBoxRenderer(<yourComboBox>, GetData(sql));

Or this (for a ListView):

string sql = "<SELECT QUERY>";
ListViewRenderer lvR = new ListViewRenderer(<yourListView>, GetData(sql));

Next Topic