I am trying to write a function that can take three parameters: an SqlDataReader, a DataGridView and a List.
I want to take the contents of the SqlDataReader and create a list of Objects, then bind this to the DataGridView.
With a few pointers from another Stack Overflow user I came up with the following:
public void FillArrayList<T>(DataGridView grid, SqlDataReader reader, List<T> list)
{
//Fill the list with the contents of the reader
while (reader.Read())
{
Object obj = new Object();
Type type = typeof(T);
FieldInfo[] fields = type.GetFields(); // Get the fields of the assembly
int i = 0;
foreach(var field in fields)
{
field.SetValue(obj, reader[i]); // set the fields of T to the reader's value
i++;
}
list.Add((T)obj);
}
grid.DataSource = list;
}
When I run the code, I get an error when casting the object to type T:
Unable to cast object of type ‘System.Object’ to type
‘TestHarness.Organisation’.
I was under the impression that an Object could store anything. Can anyone advise me on why this cast cannot be performed?
Thanks,
Andy
With a little help from the link posted by MMK, in the comment below my question, I have devised a solution:
Seems to do exactly what I need. It’s possible I may come across some obvious error as I use this in more and more situations, but, this is life.
Thanks for your help, guys!