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);
}
Loading
VulpesPosted Mar 3, 2013, 5:49 AM
You can then use foreach to iterate through each DataTable in the array or List.
SamPosted Mar 4, 2013, 9:53 AM
I add up my tables into a dataset, but I do it after I add properties.
In any case, as I wrote, as you suggested, a simple table array solved the problem.
To add all tables to the dataset, I anyhow need to itterate through the table, thus the array solves it perfectly, enabling me to do all I need in one foreach pass (set columns and rows and other properties, add to dataset, etc.).
VulpesPosted Mar 4, 2013, 7:19 AM
SamPosted Mar 3, 2013, 11:30 PM
Nevertheless, as this is more of a workaround, I found out that the ultimate way is probably by:
IEnumerable <DataTable> Collection { get; set; }
foreach(IEnumerable<DataTable> t in Collection)
{....... }
But unfortunately it does not work for me. I can not get the Collection filled with my DataTables.
Although you gave me a good working solution, I still wonder if you know how to make my suggestion work.
SamPosted Mar 3, 2013, 4:20 AM
I have tried it, but unfortunately, it does not work, and I get the error message that says that there are no DataTables in the Control list.
The reason I found is that the Class Control represents only componenets with visual representation, while a DataTable is not a visual component. (This may also be the reason for my original error!)
Do you know of another class (Instead of Control) that will also include DataTable?
Thanks again.
dapeng zhengPosted Mar 3, 2013, 3:18 AM
foreach (Control c in Controls)
{
if(c is Datatable)
{
Datatable datatable = (Datatable)c;
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);
}
}