適切な使用方法は、次のようになります。
- はBindingListViewを作成します。後で、表示/並べ替え/フィルタリングする項目で埋められます。
- BindingSourceを作成します。
- DataGridViewを作成します。
- あなたは
後者の3つの手順は、Visual Studioデザイナーで行うことができます表示したいプロパティに列を追加します。それを行うと、コードはInitializeComponents
になります。
はあなたがあなたのフォームは次のようになりますMyType
の/ソート/フィルタエレメントを表示したいとしましょう:あなたはBindingSource
せずに行うことができます
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);
...
}
、あなたはDataGridView
のDataSource
に直接BindingListView
を割り当てることができます。並べ替えとフィルタリングは引き続き機能します。ただし、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();
(私は最新の情報に更新()を適用したりした後に必要とされているかどうかわからないんだけどフィルタを削除する
'?.Object' - 私のために構文エラーをスローする –
MyObject?.Mypropertyはnull条件付き演算子(C#6で新機能)を使用します。https://docs.microsoftを参照してください。 .com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operato rs何も選択されていなければ、MyBindingSource、Currentはnullを返し、その場合null返されたオブジェクトが必要なので、null条件演算子を使用しました。また、プロパティMyBindingSource.Current.Objectにアクセスする前に、MyBindingSource.Currentがnullに等しくないかどうかを確認することもできます –