Sam

Sam

  • NA
  • 166
  • 0

foreach problem

Mar 2 2013 11:39 PM
Hi all,

I initialized 6 datatables and I wish to make their columns identical.

I use a foreach loop to do the work, but I keep getting a cast error in the foreach line:
"Unable to cast object of type 'System.Windows.Forms.RadioButton' to type 'System.Data.DataTable'."

Seems like although I specify in the loop the type DataTable, the foreach loop tries to act on all controls, even such that is not a DataTable, and when it encounters another control it will issue an error.
Am I doing something wrong or is this a bug?

Can someone suggest a workaround?

The code snippet:
  foreach (DataTable dataTable in Controls)
  {
  dataTable.Columns.Add("#", typeof(int));
  dataTable.Columns.Add("weekday", typeof(decimal));
  dataTable.Columns.Add("halfday", typeof(decimal));
  dataTable.Columns.Add("weekend", typeof(decimal));
  //
  // Add 24 DataRows, first cell in first column is index (i)
  //
  for (int i = 0; i < 24; i++)
  {
  dataTable.Rows.Add(i);
  }

  //Add the table to the dataSet
  MyDataSet.Tables.Add(dataTable);
  }

Answers (6)