Search code examples
c#structdatatablepropertiesdatacolumn

C# Dynamically add columns to DataTable for each Object Property


When I try to use this accepted answer to dynamically add columns to my DataTable, the if condition is never true. I have tried changing the struct to a class and I have tried with and without the BindingFlags on the GetProperties. What am I missing?

public partial class mainForm : Form
{
    public DataTable DeviceDataTable;
    public mainForm()
    {
        InitializeComponent();
        AttachToTable(new TestObject());
    }
    public void AttachToTable(params object[] data)
    {
        for (int i = 0; i < data.Length; i++)
        {
            if (data[i].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Length > DeviceDataTable.Columns.Count)
                foreach (PropertyInfo info in data[i].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    DeviceDataTable.Columns.Add(info.Name, data[i].GetType());
                }
        }
        DeviceDataTable.Rows.Add(data);
    }
    public struct TestObject
    {
        public static readonly string Porperty_One = "First property";
        public static readonly string Porperty_Two = "Second property";
        public static readonly string Porperty_Three = "Third property";
    }
}

Solution

  • Your sample struct is bad because it has no properties, not even instance but only static fields. So Type.GetProperties won't return them. This should work as intended:

    public class TestObject
    {
        public string PorpertyOne   => "First property";
        public string PorpertyTwo   => "Second property";
        public string PorpertyThree => "Third property";
    }