Refactor your code to move the long-running part to a background thread, and keep the parts that access the UI on the UI thread:
private static DataTable LoadInstitutions(string selectedValue)
{
ConnectionClass connectionClass = new ConnectionClass();
const string sql = "A query to gather data";
DataTable result = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(sql, connectionClass.Connection(selectedValue));
da.Fill(result);
DataRow dr = result.NewRow();
dr["hello1"] = "";
result.Rows.InsertAt(dr, 0);
return result;
}
private async Task LoadInstitutions()
{
try
{
string selectedValue = cmbEnviroment.SelectedItem.ToString().Trim();
DataTable table = await Task.Run(() => LoadInstitutions(selectedValue));
cmbInstitution.DataSource = table4;
cmbInstitution.DisplayMember = "hello1";
cmbInstitution.ValueMember = "hello1";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private async void cmbEnviroment_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox senderComboBox = (ComboBox)sender;
if (senderComboBox.SelectedIndex > 0)
{
LoadingScreen ls = new LoadingScreen();
ls.TopMost = true;
ls.Show();
try
{
await LoadInstitutions();
}
finally
{
ls.Close();
}
}
}