2017-02-17 33 views
0

我將此DataBindingComplete事件設置爲我的datagridview。我希望每個綁定到datagridview的數據源都可以通過單擊列進行排序。如何將datagridview數據源轉換爲BindingListView(Equin.ApplicationFramework.BindingListView)

void MakeColumnsSortable_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) 
    { 

     DataGridView dataGridView = sender as DataGridView; 
     foreach (DataGridViewColumn column in dataGridView.Columns) 
       column.SortMode = DataGridViewColumnSortMode.Automatic; 

    } 

我所有的數據源是名單當我的名單是由.ToList 結束現在的BindingSource那種亙古不變的。我如何將datagridview.datasource轉換爲Equin.ApplicationFramework.BindingListView,並將其重新設置爲數據源,以便使任何datagridview可排序?

回答

1

Equin.ApplicationFramework.BindingListView的正確使用情況如下

在創建您的形式:

  • 創建BindingListView。稍後將填充要顯示/排序/過濾的項目
  • 創建一個BindingSource。
  • 創建一個DataGridView。
  • 添加列要顯示

後三個步驟可以在Visual Studio的設計師來完成的屬性。如果你這樣做,代碼將在InitializeComponents

假設你要顯示的MyType您的表單/排序/過濾元件將是這樣的:

public class MyForm : Form 
{ 
    private BindingListView<MyType> MyItems {get; set;} 

    public MyForm() 
    { 
     InitializeComponent(); 

     this.MyItems = new BindingListView<MyType>(this.components); 
     // components is created in InitializeComponents 
     this.MyBindingSource.DataSource = this.MyItems; 
     this.MyDataGridView.DataSource = this.MyBindingSource; 

     // assigning the DataPropertyNames of the columns can be done in the designer, 
     // however doing it the following way helps you to detect errors at compile time 
     // instead of at run time 
     this.columnPropertyA = nameof(MyType.PropertyA); 
     this.columnPropertyB = nameof(MyType.PropertyB); 
     ... 
    } 

你可以不BindingSource做,你可以直接分配BindingListViewDataGridViewDataSource。排序和篩選仍然有效。但BindingSource將幫助您訪問當前選定的項目。

private MyType SelectedItem 
{ 
    get {return ((ObjectView<MyType>)this.MyBindingSource.Current)?.Object; } 
} 

private void DisplayItems (IEnumerable<MyType> itemsToDisplay) 
{ 
    this.MyItems.DataSource = itemsToDisplay.ToList(); 
    this.MyItems.Refresh(); // this will update the DataGridView 
} 

private IEnumerable<MyType> DisplayedItems 
{ 
    get {return this.MyItems; } 
    // BindingListview<T> implements IEnumerable<T> 
} 

這就是全部。您不需要創建特殊功能來對鼠標點擊進行排序。排序將自動完成,包括決定排序順序並顯示正確的排序字形。如果你想以編程方式進行排序:

// sort columnPropertyA in descending order: 
this.MyDataGridView.Sort(this.columnPropertyA.ListsortDirection.Descending); 

一個關於BindingListView的好處之一是過濾選項:

// show only items where PropertyA not null: 
this.MyItems.ApplyFilter(myItem => myItem.PropertyA != null); 

// remove the filter: 
this.MyItems.RemoveFilter(); 

(我如果申請或以後需要刷新()不知道刪除過濾器

+0

什麼是'?.Object' - 爲我引發語法錯誤。沒有'?'工作 –

+1

MyObject?.Myproperty使用空條件運算符(C#6中的新增功能)?請參見https://docs.microsoft .COM/EN-US/DOTNET/CSHARP /語言參考/運營/空有條件operato rs我使用了null條件運算符,因爲如果沒有選擇任何東西,那麼MyBindingSource,Current返回null,在這種情況下我想要一個返回null的對象。或者,您可以在訪問屬性MyBindingSource.Current.Object之前檢查MyBindingSource.Current是否等於null –