I have the following code that accepts an SQL (string) statement, loads the results into an ArrayList (organizationList), which is a collection of organizations:
public void FillDataGridView(DataGridView grid, string SQLCommand)
{
SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.CommandType = CommandType.Text;
dataCommand.CommandText = SQLCommand;
SqlDataReader dataReader = dataCommand.ExecuteReader();
while (dataReader.Read())
{
Organisation org = new Organisation();
org.OrganisationId = (int)dataReader["OrganisationId"];
org.OrganisationName = (string)dataReader["OrganisationName"];
organisationList.Add(org);
}
grid.DataSource = organisationList;
dataReader.Close();
}
I would like to adapt this method so that I can populate the ArrayList array passed to it.
Is it possible to pass a list to a method and have something like:
public void FillArrayList(DataGridView grid, SqlDataReader reader, ArrayList list)
{
while (reader.Read())
{
Object obj = new Object
for(int i; i = 0; i < obj.NoOfProperties)
{
obj.Property[i] = reader[i];
}
list.Add(obj);
}
}
Sorry if this is a little vague, I'm brand new to OOP and a little lost!
Edit: Based on Darren Davis's advice, I changed the method as follows:
public void FillArrayList<T>(DataGridView grid, SqlDataReader reader, List<T> list)
{
while (reader.Read())
{
Object obj = new Object();
Type type = typeof(T);
FieldInfo[] fields = type.GetFields();
int i = 0;
foreach(var field in fields)
{
field.SetValue(obj, reader[i]);
i++;
}
list.Add((T)obj);
}
grid.DataSource = list;
}
When I run the code, I get an error when I click on an object of type T:
Cannot overlay object of type 'System.Object' on type 'TestHarness.Organisation'.
, . - , ?
,
Andy