Sorting Datagridview datasource on List where T is anonymous

后端 未结 2 1605
旧时难觅i
旧时难觅i 2021-02-09 10:33

A relatively simple question. I have a datagridview, which all it does is displays statistics. There is no editing/adding/deleting of rows. The datagridview is bound to a Lis

2条回答
  •  误落风尘
    2021-02-09 11:16

    This is what I did base on Thomas Levesque (https://stackoverflow.com/a/4702631/1720085) and Mary Hamlin (https://stackoverflow.com/a/5805044/1720085) answers:

    1) Added an extension method to my static class called Funcs

    static class Funcs
    {
        public static DataTable ToDataTable(this IList data)
        {
            PropertyDescriptorCollection properties = 
                TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                     row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;
        }
    }
    

    2) And use it like:

    var query = _markets.Select(market => 
        new { _cities[market.Location].Name, market.Value}).ToList();
    dataGridView1.DataSource = Funcs.ToDataTable(query);
    

提交回复
热议问题