Sorting Datagridview datasource on List where T is anonymous

后端 未结 2 1606
旧时难觅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:10

    In order to be able to sort the data automatically in the DataGridView, you need a collection that implements IBindingListView. In the BCL, the only classes that implement this interface are DataView and BindingSource (but the latter only supports sorting if the underlying datasource supports it too).

    So, you have several options:

    • create a DataTable to hold the data, and bind it to the DataGridView (it will actually bind to the DefaultView of the DataTable)
    • create your own collection class that implements IBindingListView
    • use an existing implementation, like the AdvancedList class posted by Marc Gravell in this post. You will also need to add a constructor to build the list from the result of your query:

      public AdvancedList(IEnumerable collection)
      {
          foreach (var item in collection)
          {
              Add(item);
          }
      }
      

    Since the result of your query is an anonymous type, you won't be able to call the constructor directly. The easiest way to work around the issue is to take advantage of type inference, by creating a generic method that will create the list. For convenience, you can create it as an extension method:

    public static AdvancedList ToAdvancedList(this IEnumerable source)
    {
        return new AdvancedList(source);
    }
    

    You can then use it like that:

    dataGridView1.DataSource = _markets.Select(market => 
        new { _cities[market.Location].Name, market.Value}).ToAdvancedList();
    

提交回复
热议问题