Search code examples
c#datagridviewfastmemberdisplayname-attribute

Can FastMember.ObjectReader take DisplayName into account?


I'm using FastMember.ObjectReader to copy a list of structs to a DataTable, which I then use as the DataSource of a gridview:

struct Foo {
    [DisplayName("title1")]
    public string Bar { get; set; }
}
...
var rows = new List<Foo>();
rows.Add(new Foo { Bar = "somethingsomething" });
DataTable table = new DataTable();
using (var reader = ObjectReader.Create(rows)) {
    table.Load(reader);
}
grid.DataSource = table.DefaultView;

If I select the list itself as the DataSource, the DisplayNames are used as column titles instead of the struct member name:

enter image description here

How can I recreate that when using FastMember.ObjectReader?


Solution

  • Oh, I see what you mean; you want the IDataReader to expose the [DisplayName] in the metadata; however, the primary way that is exposed is via GetSchemaTable(), and AFAIK there is no recognised key to represent [DisplayName]. It would be incorrect to pass that as the name, IMO.

    Running a quick test:

    var table = new DataTable();
    table.Columns.Add("foo").Caption = "bar";
    var schema = table.CreateDataReader().GetSchemaTable();
    
    foreach(DataRow row in schema.Rows)
    {
        foreach(DataColumn col in schema.Columns)
        {
            Console.WriteLine($"{col.ColumnName}={row[col]}");
        }
        Console.WriteLine();
    }
    

    shows that indeed it is unlikely to expect it there:

    ColumnName=foo
    ColumnOrdinal=0
    ColumnSize=-1
    NumericPrecision=
    NumericScale=
    DataType=System.String
    ProviderType=
    IsLong=False
    AllowDBNull=True
    IsReadOnly=False
    IsRowVersion=False
    IsUnique=False
    IsKey=False
    IsAutoIncrement=False
    BaseCatalogName=
    BaseSchemaName=
    BaseTableName=
    BaseColumnName=foo
    AutoIncrementSeed=0
    AutoIncrementStep=1
    DefaultValue=
    Expression=
    ColumnMapping=1
    BaseTableNamespace=
    BaseColumnNamespace=
    

    this means that there isn't really anything I can suggest other than to manually populate the .Caption, perhaps use fast-member to get the data.