-2

The question is how to dynamically add properties and values to a dynamically created object

Previously asked

I want to add multiple field to an object dynamically, i am using the following code but with each loop it remove the previous and add the latest, but i want the object to hold all values.

SqlDataReader sdr = cmd.ExecuteReader();
var columns = Enumerable.Range(0, sdr.FieldCount).Select(sdr.GetName).ToList();
if (sdr.HasRows)
{
    allRows = new ArrayList();
    while (sdr.Read())
    {
        dynamic obj = new ExpandoObject();
        foreach (string item in columns)
        {                           
           obj.item = sdr[item];
        }                        
        allRows.Add(obj);
     }                    
}

1 Answers1

2

A DataTable does precisely what you're looking for. Instead of doing such common tasks using primitives, use the built-in DataAdapter to fetch all values for you from the database in one function call. Even if you're looking for named property members, strongly-typed DataSets will solve that for you.

dotNET
  • 33,414
  • 24
  • 162
  • 251