49
DataFilter for WinForms 2019.11.28 更新 グレープシティ株式会社 グレープシティ株式会社

DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

  • Upload
    others

  • View
    53

  • Download
    0

Embed Size (px)

Citation preview

Page 1: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

DataFilter for WinForms2019.11.28 更新

グレープシティ株式会社グレープシティ株式会社

Page 2: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

目次

概要 2

主な特長 3

コアクラス 4

クイックスタート 5-8

スマートタグ 9

DataFilter の操作 10

データ連結 10-15

アコーディオンレイアウト 15-17

フィルタ 17-19

カスタムフィルタ 19-24

フィルタの概要 24-25

XML シリアル化・逆シリアル化 25-26

テーマ 26-27

スタイル 27-32

キーボードによる移動 32

チュートリアル 33

FlexGrid との DataFilter の使用 33-39

FlexChart との DataFilter の使用 39-48

  DataFilter for WinForms

1 Copyright © GrapeCity, Inc. All rights reserved.         

Page 3: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

概要

Data filtering refers to setting conditions on data so that only specific data is displayed. Filtered data is easier toanalyze and allows you to focus on specific information in a large set of data.

DataFilter for WinForms (Beta) is a control which allows users to filter data on the basis of filter criterias orconditions. It can be used in conjunction with data-aware controls like grids, lists, treeview, charts or maps includingstandard MS data-aware controls.

For instance, the DataFilter control provides a handy and convenient way to perform desired filtering on a grid thatdoes not have built-in filtering support. The DataFilter control can also be used to build filters similar to the ones yousee in different e-commerce websites where the grid displaying a product listing shows only specific attributes, suchas product name and product image. However, you can set filters for a specific brand, category, price etc using theDataFilter control. Such filters cannot be set from column filters in the data grid controls.

DataFilter for WinForms  

2 Copyright © GrapeCity, Inc. All rights reserved.         

Page 4: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

主な特長

Manage groups using accordion layout

The DataFilter control lays out the filters as a vertically stacked list of items. Corresponding to each filter, anaccordion tab is added to the DataFilter control which contains the controls used to filter the data-awarecontrol by a specific field. Each filter element can have header and can be expanded or collapsed to show orhide the contents associated with it, giving it the look and feel of an accordion control. There's also an optionto expand or collapse all of the filter conditions making it easier to hide the details and navigatethrough different filter headers.

Use different filters to filter distinct data

The DataFilter control provides four different kinds of filters namely, BoolFilter, RangeFilter, DateRangeFilterand ChecklistFilter, to filter different types of data. For example, to filter boolean values, the DataFilter controlautomatically creates a BoolFilter which is represented by a checkbox. Similarly, the control generates filter witha range slider and range editors for filtering range values. Filters can also be added programmatically to theDataFilter control.

Customize appearance

The DataFilter control provides dedicated class for each of its element which makes it easier to customize theappearance of the control and its elements.

Serialize/Deserialize filter expressions

The DataFilter control offers XML serialization by providing the functionality to save the current filterexpressions to an XML file and load them when needed.

Easy integration with controls

The DataFilter control can be easily paired up with any data-aware control like grid, list, treeView, chart or map.

Show tooltip

DataFilter allows you to display tooltip for providing additional information about the filters over the filterheader through ShowToolTips property and specify the tooltip text using ToolTip property of the Filter class.

Navigate using the keyboard

DataFilter control supports filter navigation through the keyboard. This feature allows you to navigate throughthe vertically stacked list of filters and move the focus between different filter conditions.

  DataFilter for WinForms

3 Copyright © GrapeCity, Inc. All rights reserved.         

Page 5: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

コアクラス

The following table lists some of the key classes and their properties. You can click on the cross-references to get tothe API documentation that provides detailed description for the key members.

C1DataFilter

Properties: AutoGenerateFilters, Filters, HeaderText, ShowHeader, Styles

Methods: ApplyFilter, LoadFilterExpression, SaveFilterExpression

DataFilterTheme

Properties: Button, CheckBox, Common, Editor, Filter, FilterCaption, Header, ScrollBar

Other important classes are BoolFilter, ChecklistFilter, DateRangeFilter, and RangeFilter.

DataFilter for WinForms  

4 Copyright © GrapeCity, Inc. All rights reserved.         

Page 6: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

クイックスタート

This quick start will guide you through the steps of adding DataFilter and DataGridView controls to an application,binding DataGridView to a data source and setting the properties of controls.

Complete the steps given below to see how the DataFilter control appears after data binding and setting properties.

1. Setting up the application2. Binding DataGridView to a data source3. Setting the properties of controls

The following image shows filtered values in DataGridView on the basis of filters applied in the DataFilter control.

Step 1: Setting up the application

1. Create a new Windows Forms App.2. Drag and drop the C1DataFilter control from the Toolbox onto your form. Set its Dock property to Left.3. Drag and drop the MS DataGridView control from the Toolbox onto your form. Set its Dock property to Right.

Back to Top

Step 2: Binding DataGridView to a data source

1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right corner of theDataGridView control.

2. In the DataGridView Tasks menu, click the Choose Data Source drop-down arrow and select the Add Project

  DataFilter for WinForms

5 Copyright © GrapeCity, Inc. All rights reserved.         

Page 7: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Data Source link from the drop-down box. The Data Source Configuration Wizard appears.3. On the Choose a Data Source Type page, select Database and click Next.4. On the Choose a Database Model page, leave Dataset selected and click Next.5. Click the New Connection button to create a new connection or choose one from the drop-down list. When

you click New Connection, the Add Connection dialog box appears. Set Microsoft Access Database File asthe Data source.

6. Click the Browse button under Database file name. In the Select Microsoft Access Database File dialog box,browse to the C1NWind.mdb database in the Documents\ComponentOne Samples\Common directory. Selectthe C1NWind.mdb file and click Open.

7. In the Add Connection dialog box, click the Test Connection button to make sure that you have successfullyconnected to the database or server and click OK.

8. Click OK to close the Add Connection dialog box .9. Click the Next button to continue. A dialog box will appear asking if you would like to add the data file to your

project and modify the connection string. Since it is not necessary to copy the database to your project, clickNo.

10. Save the connection string in the application configuration file by checking the Yes, save the connection asbox and entering a name. Click the Next button to continue.

11. On the Choose Your Database Objects page, expand the Tables node, and select the Brand, Model,Category and Price fields of the Cars table.

12. Click Finish.

C1NWindDataSet.xsd is added to your project and DataSource property of the DataGridView is set tocarsBindingSource.

Back to Top

Step 3: Configuring DataFilter

1. Select the DataFilter control and set its AutoGenerateFilters property to true from the Properties window.Note that setting AutoGenerateFilters property to true automatically generates the filters depending on thetype of the fields present in the data source of DataFilter.

2. To customize the auto generated filters for defining the filtering criterias such as the minimum /maximumvalues for the RangeFilter and the checklist items for the CheckListFilter, subscribe to theFilterAutoGenerating event of DataFilter.

3. Add the following code in the event handler of the FilterAutoGenerating event which provides the checklistitems for the two filters namely “Brand”, “Category” and sets the maximum and minimum value for the pricefilter.

Defining these filters allows you to filter the cars listing by a specific brand, category or price which are thebasic criterias used to view a car listing.

'DataFilterのFilterAutoGeneratingイベントを購読して、フィルターの基準を定義しますc1DataFilter1.FilterAutoGenerating = (c1DataFilter1.FilterAutoGenerating + C1DataFilter1_FilterAutoGenerating)

Visual Basic

//DataFilterのFilterAutoGeneratingイベントを購読して、フィルターの基準を定義しますc1DataFilter1.FilterAutoGenerating += C1DataFilter1_FilterAutoGenerating;

C#

Private Sub C1DataFilter1_FilterAutoGenerating(ByVal sender As Object, ByVal e As C1.DataFilter.FilterAutoGeneratingEventArgs) Select Case (e.Property.Name) Case "Brand"

Visual Basic

DataFilter for WinForms  

6 Copyright © GrapeCity, Inc. All rights reserved.         

Page 8: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

4. In the Form Load event handler, set the DataSource property of DataFilter to carsBindingSource.

Dim brandFilter = CType(e.Filter,C1.Win.DataFilter.ChecklistFilter) brandFilter.ItemsSource = c1NWindDataSet.Cars brandFilter.ValueMemberPath = "Brand" brandFilter.SelectAll Case "Category" Dim categoryFilter = CType(e.Filter,C1.Win.DataFilter.ChecklistFilter) categoryFilter.ItemsSource = c1NWindDataSet.Cars categoryFilter.ValueMemberPath = "Category" categoryFilter.SelectAll Case "Price" Dim priceFilter = CType(e.Filter,C1.Win.DataFilter.RangeFilter) priceFilter.Maximum = c1NWindDataSet.Cars.AsEnumerable.Max(() => { }, x.Field(Of Double)("Price")) priceFilter.Minimum = c1NWindDataSet.Cars.AsEnumerable.Min(() => { }, x.Field(Of Double)("Price")) priceFilter.Increment = 1000 priceFilter.Digits = 0 Case Else e.Cancel = true End SelectEnd Sub

private void C1DataFilter1_FilterAutoGenerating(object sender, C1.DataFilter.FilterAutoGeneratingEventArgs e){ switch (e.Property.Name) { //Brandフィルターのチェックリスト項目を設定します case "Brand": var brandFilter = (C1.Win.DataFilter.ChecklistFilter)e.Filter; brandFilter.ItemsSource = c1NWindDataSet.Cars; brandFilter.ValueMemberPath = "Brand"; brandFilter.SelectAll(); break; //Categoryフィルターのチェックリスト項目を設定します case "Category": var categoryFilter = (C1.Win.DataFilter.ChecklistFilter)e.Filter; categoryFilter.ItemsSource = c1NWindDataSet.Cars; categoryFilter.ValueMemberPath = "Category"; categoryFilter.SelectAll(); break; //Priceフィルターの最小値・最大値を設定します case "Price": var priceFilter = (C1.Win.DataFilter.RangeFilter)e.Filter; priceFilter.Maximum = c1NWindDataSet.Cars.AsEnumerable().Max(x => x.Field<double>("Price")); priceFilter.Minimum = c1NWindDataSet.Cars.AsEnumerable().Min(x => x.Field<double>("Price")); priceFilter.Increment = 1000; priceFilter.Digits = 0; break; //すべてのフィルターの作成をキャンセルします default: e.Cancel = true; break; }}

C#

  DataFilter for WinForms

7 Copyright © GrapeCity, Inc. All rights reserved.         

Page 9: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Run the application and observe that filters are automatically applied to the rendered grid because the AutoApplyproperty of the DataFilter control is set to true by default. Use interactive UI of DataFilter to change the filter valuesand observe how the grid gets filtered.

Back to Top

'C1DataFilterのデータソースをDataGridViewに割り当てられているデータソースと同じ値に設定しますc1DataFilter1.DataSource = carsBindingSource

Visual Basic

//C1DataFilterのデータソースをDataGridViewに割り当てられているデータソースと同じ値に設定しますc1DataFilter1.DataSource = carsBindingSource;

C#

DataFilter for WinForms  

8 Copyright © GrapeCity, Inc. All rights reserved.         

Page 10: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

スマートタグ

DataFilter includes a smart tag to provide access to its commonly used properties and tasks at the design-time. Toaccess the C1DataFilter Tasks menu, click the smart tag in the upper-right corner of the DataFilter control.

The C1DataFilter Tasks menu provides the following options:

Edit filtersClicking Edit filters displays a Filter Collection Editor, which allows you to add, edit or remove the supportedfilters currently added to the DataFilter. It also allows you to access or set the properties of the filters added tothe DataFilter control.

Generate filtersOnce the DataFilter control is set to a valid data source, clicking Generate filters generates the supportedfilters for the current items source.

Remove filtersClicking Remove filters deletes all the existing filters from the DataFilter control.

About C1DataFilterClicking About C1DataFilter displays a dialog box, which is helpful in finding the version number of theproduct and other resources.

  DataFilter for WinForms

9 Copyright © GrapeCity, Inc. All rights reserved.         

Page 11: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

DataFilter の操作

This section comprises all the functionalities of the DataFilter control.

データ連結

Learn how to bind DataFilter with a data-aware control and model binding.アコーディオンレイアウト

Learn how to display accordion layout in the DataFilter control.フィルター

Learn about the filters supported in the DataFilter control and how to add these filters.XML シリアル化・逆シリアル化

Learn how to save and load the current filter expressions using DataFilter.テーマ

Learn about the built-in themes and how to apply them on the DataFilter control.スタイル

Learn how to customize the appearance of the DataFilter control and its elements.

データ連結

The DataFilter control can be bound to any data-aware control or to a model/custom collection. You can choose tobind the control using any of the following ways:

Binding with data-aware controlModel binding

Binding with data-aware controlWhen you bind the DataFilter control with a data-aware control, fields are generated. On the basis of these fieldspresent in the data source, different filters are automatically generated in the DataFilter control. These filters areBoolFilter, RangeFilter, DateRangeFilter and ChecklistFilter. However, the filtering criterias are not generated withthese filters, for example, no minimum and maximum values are generated for RangeFilter and empty checklist isgenerated for ChecklistFilter. So, you need to customize the auto generated filters for defining the filtering criteriasusing FilterAutoGenerating event of the C1DataFilter class.

Model bindingTo bind the DataFilter control with a custom collection, follow these steps:

1. Define the custom collection2. Add and bind DataGridView3. Add and configure the DataFilter control

Step 1: Define the custom collection

Create a class named Car which contains a method, GetList, that returns the collection which is to be bound toDataFilter and DataGridView.

Namespace DataFilter_ModelBinding Public Enum brandNames Audi = 0

Visual Basic

DataFilter for WinForms  

10 Copyright © GrapeCity, Inc. All rights reserved.         

Page 12: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Maruti = 1 Lexus = 2 BMW = 3 Infiniti = 4 Tesla = 5 End Enum Class Car Public Property Id As Integer Get End Get Set End Set End Property Public Property Model As String Get End Get Set End Set End Property Public Property Category As String Get End Get Set End Set End Property Public Property Brand As String Get End Get Set End Set End Property Public Property Price As Double Get End Get Set End Set End Property Public Property InStock As Boolean Get End Get Set End Set End Property Public Shared Function GetList() As List(Of Car) Dim carList As List(Of Car) = New List(Of Car) Dim carModels() As String = New String() {"SLK R172 Cabriolet", "Wraith", "XFR-S I", "CTS III", "ES VI Sedan", "IS III"} Dim brands() As String = New String() {"Lexus", "Lexus", "Lexus", "Infiniti", "Audi", "Audi"} Dim categories() As String = New String() {"Sports", "Truck", "Sports", "Truck", "Saloon", "Saloon"} Dim random As Random = New Random Dim i As Integer = 0 Do While (i < 6) carList.Add(New Car) i = (i + 1) Loop Return carList End Function

  DataFilter for WinForms

11 Copyright © GrapeCity, Inc. All rights reserved.         

Page 13: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Back to Top

Step 2: Add and bind DataGridView

1. Drag and drop the MS DataGridView control from the Toolbox onto your form. Set the value of its Locationproperty to 10,10 and Size property to 575, 735.

2. Bind DataGridView with data source using the following code:

End ClassEnd Namespace

namespace DataFilter_ModelBinding{ public enum brandNames { Audi=0, Maruti=1, Lexus=2, BMW=3, Infiniti=4, Tesla=5 } class Car { public int Id { get; set; } public string Model { get; set; } public string Category { get; set; } public string Brand { get; set; } public double Price { get; set; } public bool InStock { get; set; }

public static List<Car> GetList() { List<Car> carList = new List<Car>(); string[] carModels = { "SLK R172 Cabriolet", "Wraith", "XFR-S I", "CTS III", "ES VI Sedan", "IS III" }; string[] brands = { "Lexus", "Lexus", "Lexus", "Infiniti", "Audi", "Audi" }; string[] categories = { "Sports", "Truck", "Sports", "Truck", "Saloon", "Saloon" }; Random random = new Random(); for (int i = 0; i < 6; i++) { carList.Add(new Car() { Id = i + 1, Model = carModels[i], Category = categories[i], Price = Math.Round(random.NextDouble() * 100000, 2), Brand = brands[i], InStock = Convert.ToBoolean(random.Next(0, 2)) }); } return carList; } }}

C#

'_carListは、List<Car>型のグローバル変数です _carList = Car.GetList

Visual Basic

DataFilter for WinForms  

12 Copyright © GrapeCity, Inc. All rights reserved.         

Page 14: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Back to Top

Step 3: Add and configure the DataFilter control

1. Drag and drop the C1DataFilter control from the Toolbox onto your form. Set the value of its Locationproperty to 600,10 and Size property to 290, 735.

2. Set AutoGenerateFilters property to true using the following code.Note that setting AutoGenerateFilters property to true automatically generates the filters depending on thetype of the fields present in the data source of DataFilter.

3. To customize the auto generated filters for defining the filtering criterias such as the minimum /maximumvalues for the RangeFilter and the checklist items for the CheckListFilter, subscribe to theFilterAutoGenerating event of DataFilter class as shown in the following code.

4. Add the following code in the event handler of the FilterAutoGenerating event which provides the checklistitems for the two filters namely “Brand”, “Category” and sets the maximum and minimum value for the pricefilter.Defining these filters allows you to filter the cars listing by a specific brand, category or price which are thebasic criterias used to view a car listing.

dataGridView1.DataSource = _carList

//_carListは、List<Car>型のグローバル変数です _carList = Car.GetList();dataGridView1.DataSource = _carList;

C#

'_carListは、List<Car>型のグローバル変数です _carList = Car.GetListdataGridView1.DataSource = _carList

Visual Basic

c1DataFilter1.AutoGenerateFilters = true;

C#

c1DataFilter1.FilterAutoGenerating = (c1DataFilter1.FilterAutoGenerating + C1DataFilter1_FilterAutoGenerating)

Visual Basic

c1DataFilter1.FilterAutoGenerating += C1DataFilter1_FilterAutoGenerating;

C#

Private Sub C1DataFilter1_FilterAutoGenerating(ByVal sender As Object, ByVal e As C1.DataFilter.FilterAutoGeneratingEventArgs) Select Case (e.Property.Name) Case "Brand" Dim brandFilter = CType(e.Filter,C1.Win.DataFilter.ChecklistFilter) brandFilter.ItemsSource = _carList brandFilter.ValueMemberPath = "Brand" brandFilter.SelectAll Case "Category" Dim categoryFilter = CType(e.Filter,C1.Win.DataFilter.ChecklistFilter) categoryFilter.ItemsSource = _carList

Visual Basic

  DataFilter for WinForms

13 Copyright © GrapeCity, Inc. All rights reserved.         

Page 15: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

5. To update the data of the data-aware control, subscribe to the FilterChanged event of DataFilter as shown inthe following code.Note that the DataFilter control is bound to a data source which does not support filtering like the BindingList,so using FilterChanged event of the C1DataFilter class updates the data of the data-aware control.

categoryFilter.ValueMemberPath = "Category" categoryFilter.SelectAll Case "Price" Dim priceFilter = CType(e.Filter,C1.Win.DataFilter.RangeFilter) priceFilter.Maximum = _carList.AsEnumerable.Max(() => { }, x.Price) priceFilter.Minimum = _carList.AsEnumerable.Min(() => { }, x.Price) priceFilter.Increment = 1000 priceFilter.Digits = 0 Case Else e.Cancel = true End Select End Sub

private void C1DataFilter1_FilterAutoGenerating(object sender, C1.DataFilter.FilterAutoGeneratingEventArgs e){ switch(e.Property.Name) { //Brandフィルターのチェックリスト項目を設定します case "Brand": var brandFilter = (C1.Win.DataFilter.ChecklistFilter)e.Filter; brandFilter.ItemsSource = _carList; brandFilter.ValueMemberPath = "Brand"; brandFilter.SelectAll(); break; //Categoryフィルターのチェックリスト項目を設定します case "Category": var categoryFilter = (C1.Win.DataFilter.ChecklistFilter)e.Filter; categoryFilter.ItemsSource = _carList; categoryFilter.ValueMemberPath = "Category"; categoryFilter.SelectAll(); break; //Priceフィルターの最小値・最大値を設定します case "Price": var priceFilter = (C1.Win.DataFilter.RangeFilter)e.Filter; priceFilter.Maximum = _carList.AsEnumerable().Max(x => x.Price); priceFilter.Minimum = _carList.AsEnumerable().Min(x => x.Price); priceFilter.Increment = 1000; priceFilter.Digits = 0; break; //すべてのフィルターの作成をキャンセルします default: e.Cancel = true; break; }}

C#

c1DataFilter1.FilterChanged = (c1DataFilter1.FilterChanged + C1DataFilter1_FilterChanged)

Visual Basic

C#

DataFilter for WinForms  

14 Copyright © GrapeCity, Inc. All rights reserved.         

Page 16: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

6. Add the following code in the event handler of the FilterChanged event which reassigns data source to theFlexGrid control through View property of the C1DataFilter class which contains the result of filteringthe C1DataFilter.DataSource to the DataSource property of FlexGrid.

Back to Top

c1DataFilter1.FilterChanged += C1DataFilter1_FilterChanged;

Private Sub C1DataFilter1_FilterChanged(ByVal sender As Object, ByVal e As EventArgs) dataGridView1.DataSource = c1DataFilter1.View.Cast(Of Car).ToListEnd Sub

Visual Basic

private void C1DataFilter1_FilterChanged(object sender, EventArgs e){ dataGridView1.DataSource=c1DataFilter1.View.Cast<Car>().ToList();}

C#

アコーディオンレイアウト

The DataFilter control enables you to create an interactive user interface by organizing the filter conditions (or filters)as a vertically stacked list of items, which gives it the look and feel of an accordion layout. You can easily toggle thedisplay of the conditions associated with each filter separately using expand and collapse icons.

In addition, you can also expand and collapse all of the filter conditions at once using ExpandAll and CollapseAllmethods in C1DataFilter class. This makes it convenient to navigate through different filter headers as a group whenrequired.

The following GIF demonstrates the use of ExpandAll and CollapseAll feature.

  DataFilter for WinForms

15 Copyright © GrapeCity, Inc. All rights reserved.         

Page 17: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

In DataFilter, you can customize the header text of filters using HeaderText property of the C1DataFilter class.

The following image shows the customized header text on using the HeaderText property.

The following code example demonstrates the use of HeaderText property to change the header text:

Private Sub C1DataFilter1_FilterAutoGenerating(ByVal sender As Object, ByVal e As C1.DataFilter.FilterAutoGeneratingEventArgs) If (e.Property.Name = "Category") Then Dim categoryFilter = CType(e.Filter,C1.Win.DataFilter.ChecklistFilter) categoryFilter.HeaderText = "Categories"

Visual Basic

DataFilter for WinForms  

16 Copyright © GrapeCity, Inc. All rights reserved.         

Page 18: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

End If End Sub

private void C1DataFilter1_FilterAutoGenerating(object sender, C1.DataFilter.FilterAutoGeneratingEventArgs e){ if (e.Property.Name=="Category") { var categoryFilter = (C1.Win.DataFilter.ChecklistFilter)e.Filter; categoryFilter.HeaderText = "Categories"; }}

C#

フィルタ

The DataFilter control supports five different kinds of filters namely, BoolFilter, RangeFilter, DateRangeFilter,ChecklistFilter and CalendarFilter, to filter different types of data. Corresponding to each filter, an accordion tab isadded to the DataFilter control which contains the controls used to filter the data-aware control by a specific field. Forexample,

BoolFilter - The DataFilter control generates a BoolFilter for a boolean data field, which is represented by acheckbox.RangeFilter - The DataFilter control generates a RangeFilter for a numeric data field, which provides rangeeditors and a range slider to filter values in the specified range.DateRangeFilter - The DataFilter control generates a DateRangeFilter for a DateTime type of data field, whichprovides range editors and a range slider to filter values in the specified date range.ChecklistFilter - This filter is autogenerated for textual data. But it can also be used for any other data type.For example, if you need to allow selecting among several numeric values, CheckListFilter is a better optionthan RangeFilter.CalendarFilter - The filter can be used for a DateTime type of data field and is represented by a calendar tofilter dates.

When the AutoGenerateFilters property of the C1DataFilter class is set to true, filters are automatically generateddepending on the type of the fields present in the DataSource. These filters are added to the FilterCollection and canbe accessed using Filters property of the C1DataFilter class.

The following code demonstrates how filters can be automatically generated in the DataFilter control:

To add filters programmatically to the DataFilter control, follow these steps:

1. Create an instance of one of the different filter types, namely BoolFilter, RangeFilter, ChecklistFilter orDateRangeFilter. The instance accepts a parameter that is the name of the data field for which the filter is beingdefined.

'AutoGenerateFiltersをtrueに設定すると、フィルタが自動的に生成しますc1DataFilter1.AutoGenerateFilters = truec1DataFilter1.DataSource = _tablec1DataFilter1.ShowToolTips = true

Visual Basic

//AutoGenerateFiltersをtrueに設定すると、フィルタが自動的に生成しますc1DataFilter1.AutoGenerateFilters = true; c1DataFilter1.DataSource = _table;c1DataFilter1.ShowToolTips = true;

C#

  DataFilter for WinForms

17 Copyright © GrapeCity, Inc. All rights reserved.         

Page 19: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

2. Specify the important properties related to the filter class.3. Finally, add the filter instance to the FilterCollection.

The following code demonstrates how to add a RangeFilter to the DataFilter control through code:

Reset FiltersDataFilter also supports filter reset feature. This enables you to the reset the filter selection to its default value on theclick of a button. You can use reset method to implement this feature on the filters.

'RangeFilterを追加しますDim rangeFilter As RangeFilter = New RangeFilter("UnitPrice") 'ヘッダーのテキストを設定しますrangeFilter.HeaderText = "Unit Price" 'RangeFilterの最小値・最大値を設定しますrangeFilter.Minimum = 0rangeFilter.Maximum = 100 'エディタの種類を指定しますrangeFilter.EditorsType = C1.DataFilter.EditorsType.SpinEditor 'エディタを表示しますrangeFilter.EditorsVisible = true 'フィルタヘッダーに表示するためToolTipのテキストを設定しますrangeFilter.ToolTip = "Select the price range to perform " + "filtering on the grid" 'DataFilterコントロールにフィルタを追加しますc1DataFilter1.Filters.Add(rangeFilter)

Visual Basic

//Add RangeFilterRangeFilter rangeFilter = new RangeFilter("UnitPrice");

//Set text for the headerrangeFilter.HeaderText = "Unit Price";

//Set minimum and maximum values for the RangeFilterrangeFilter.Minimum = 0;rangeFilter.Maximum = 100;

//Specify the type of editorrangeFilter.EditorsType = C1.DataFilter.EditorsType.SpinEditor;

//Show the editorrangeFilter.EditorsVisible = true;

//Sets text of the ToolTip to appear on the filter headerrangeFilter.ToolTip = "Select the price range to perform " + "filtering on the grid";

//Add filter to the DataFilter controlc1DataFilter1.Filters.Add(rangeFilter);

C#

DataFilter for WinForms  

18 Copyright © GrapeCity, Inc. All rights reserved.         

Page 20: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

As shown in the GIF below, all the filter selections are cleared after clicking on the reset filter button.

To implement this feature, you can use the following code. In this code, reset method is applied on the brand filter.

//ブランドフィールド用に作成されているChecklistFilterをリセットしますprivate void resetbtn_Click(object sender, EventArgs e) { brandFilter.Reset(); }

CS

カスタムフィルタ

The DataFilter control allows you to create custom filters which can replace the default filter editors at runtime. Itprovides CustomFilter class which needs to be inherited for defining a custom filter. Inheriting the CustomFilter classprovides access to its properties and methods which can further be used to create a custom filter.

Following example shows how you can create and add custom filter to the DataFilter control. It demonstrates how youcan filter the car models using the MultiSelect control as a part of the DataFilter control UI.

1. Define a custom filter by creating a new class which inherits the CustomFilter class. In the class constructor, useControl property of the CustomFilter class to specify the custom control that you want to use to performfiltering in the DataFilter control. For example, the following code is used for defining a custom filter,ModelFilter, to filter the data using the MultiSelect control as a filter within the DataFilter control.

'CustomFilterクラスを継承してカスタムフィルタを定義しますPublic Class ModelFilter

Visual Basic

  DataFilter for WinForms

19 Copyright © GrapeCity, Inc. All rights reserved.         

Page 21: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

2. Bind the MultiSelect control with data. In this example, we are binding the control with data using theSetTagList method.

3. Raise the ValueChanged event of the CustomFilter class in the SelectionChanged event of the MultiSelectcontrol which gets fired when the user selects values from the MultiSelect control. This notifies the DataFilter

Inherits CustomFilter

Private _multiSelect As C1MultiSelect

'MultiSelectコントロールの設定をカスタマイズします Public ReadOnly Property MultiSelect As C1MultiSelect Get Return _multiSelect End Get End Property

Public Sub New() 'カスタムフィルタを表すコントロールを「Control」プロパティに設定します Control = (_multiSelect, New C1MultiSelect() With { .Height = 50, .Placeholder = "Model of car", .AutoCompleteMode = AutoCompleteMode.SuggestAppend }) _multiSelect.SelectionChanged += MultiSelect_SelectionChanged

End SubEnd Class

//CustomFilterクラスを継承してカスタムフィルタを定義しますpublic class ModelFilter : CustomFilter{ private C1MultiSelect _multiSelect;

//MultiSelectコントロールの設定をカスタマイズします public C1MultiSelect MultiSelect { get { return _multiSelect; } }

public ModelFilter() { //カスタムフィルタを表すコントロールを「Control」プロパティに設定します Control = _multiSelect = new C1MultiSelect() { Height = 50, Placeholder = "Model of car", AutoCompleteMode = AutoCompleteMode.SuggestAppend }; _multiSelect.SelectionChanged += MultiSelect_SelectionChanged; }}

C#

'MultiSelectコントロールをデータと連結します_multiSelect.BindingInfo.DataSource = tagSource_multiSelect.BindingInfo.DisplayMemberPath = PropertyNameEnd Sub

Visual Basic

public void SetTagList(object tagSource){ //MultiSelectコントロールをデータと連結します _multiSelect.BindingInfo.DataSource = tagSource; _multiSelect.BindingInfo.DisplayMemberPath = PropertyName;}

C#

DataFilter for WinForms  

20 Copyright © GrapeCity, Inc. All rights reserved.         

Page 22: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

control about the change in filter values.

4. Implement the GetExpression abstract method of the CustomFilter class to create and return the filterexpression which is to be used to filter the values in the data aware control.

Private Sub MultiSelect_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs)'カスタムフィルタのValueChangedイベントを発生し、グリッドにフィルタを適用します OnValueChanged()End Sub

Visual Basic

private void MultiSelect_SelectionChanged(object sender, EventArgs e){ //カスタムフィルタのValueChangedイベントを発生し、グリッドにフィルタを適用します OnValueChanged();}

C#

Protected Overrides Function GetExpression() As Expression 'フィルタ式を作成して返します Dim ce = New CombinationExpression() With { .FilterCombination = FilterCombination.[Or] }

For Each item In _multiSelect.SelectedItems ce.Expressions.Add(New OperationExpression() With { .FilterOperation = FilterOperation.Equal, .Value = item.Value, .PropertyName = PropertyName }) Next

Return ce End Function 'このプロパティは、フィルタが適用されるかどうかを決定します Public Overrides ReadOnly Property IsApplied As Boolean Get Return MyBase.IsApplied AndAlso _multiSelect.SelectedItems.Count > 0 End Get End Property

Visual Basic

protected override Expression GetExpression(){ //フィルタ式を作成して返します var ce = new CombinationExpression() { FilterCombination = FilterCombination.Or }; foreach (var item in _multiSelect.SelectedItems) ce.Expressions.Add(new OperationExpression() { FilterOperation = FilterOperation.Equal, Value = item.Value, PropertyName = PropertyName }); return ce;}

//このプロパティは、フィルタが適用されるかどうかを決定しますpublic override bool IsApplied => base.IsApplied && _multiSelect.SelectedItems.Count > 0;

C#

  DataFilter for WinForms

21 Copyright © GrapeCity, Inc. All rights reserved.         

Page 23: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

5. Add the created custom filter, ModelFilter, to the DataFilter control to filter the car models shown in theFlexGrid control.

Dim _carsTable As DataTable

Public Sub New() InitializeComponent() Me.Load += Form1_LoadEnd Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Dim con As OleDbConnection = New OleDbConnection( "provider=microsoft.jet.oledb.4.0;Data Source=" & Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\ComponentOne Samples\Common\C1NWind.mdb") _carsTable = New DataTable() New OleDbDataAdapter("Select * from Cars", con).Fill(_carsTable) c1DataFilter1.DataSource = GetCars().ToList() c1FlexGrid1.DataSource = GetCars().ToList() 'カスタムモデルフィルタを初期化します 'MultiSelectコントロールを使用して自動車のモデルをフィルターできます Dim modelFilter = New ModelFilter() With { .HeaderText = "Model", .PropertyName = "Model" } 'MultiSelectコントロールのデータを設定します modelFilter.SetTagList(GetCars().ToList()) 'MultiSelectコントロールをカスタマイズして、コントロール  'のヘッダーに5個以下の項目を表示します modelFilter.MultiSelect.MaxHeaderItems = 5 'FilterCollectionにカスタムフィルターを追加します c1DataFilter1.Filters.Add(modelFilter) 'FilterChangedイベントに購読します c1DataFilter1.FilterChanged += C1DataFilter1_FilterChangedEnd Sub

Private Sub C1DataFilter1_FilterChanged(ByVal sender As Object, ByVal e As EventArgs) 'データを更新します c1FlexGrid1.DataSource = c1DataFilter1.View.Cast(Of Car)().ToList()End Sub

Public Iterator Function GetCars() As IEnumerable(Of Car) Dim carsTable = _carsTable

For Each row As DataRow In carsTable.Rows Yield New Car With { .Brand = row.Field(Of String)("Brand"), .Category = row.Field(Of String)("Category"), .Description = row.Field(Of String)("Description"), .Liter = row.Field(Of Double)("Liter"), .Model = row.Field(Of String)("Model"), .Picture = row.Field(Of Byte())("Picture"), .Price = row.Field(Of Double)("Price"), .TransmissAutomatic = row.Field(Of String)("TransmissAutomatic"), .ID = row.Field(Of Integer)("ID") }

Visual Basic

DataFilter for WinForms  

22 Copyright © GrapeCity, Inc. All rights reserved.         

Page 24: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

NextEnd Function

DataTable _carsTable;public Form1(){ InitializeComponent(); this.Load += Form1_Load;}

private void Form1_Load(object sender, EventArgs e){ OleDbConnection con = new OleDbConnection( "provider=microsoft.jet.oledb.4.0;Data Source=" + Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\ComponentOne Samples\\Common\\C1NWind.mdb"); _carsTable = new DataTable();

new OleDbDataAdapter("Select * from Cars", con).Fill(_carsTable);

c1DataFilter1.DataSource = GetCars().ToList(); c1FlexGrid1.DataSource = GetCars().ToList();

//カスタムモデルフィルタを初期化します //MultiSelectコントロールを使用して自動車のモデルをフィルタできます var modelFilter = new ModelFilter() { HeaderText = "Model", PropertyName = "Model", };

//MultiSelectコントロールのデータを設定します modelFilter.SetTagList(GetCars().ToList());

//MultiSelectコントロールをカスタマイズして、コントロール //のヘッダーに5個以下の項目を表示します modelFilter.MultiSelect.MaxHeaderItems = 5;

//FilterCollectionにカスタムフィルタを追加します c1DataFilter1.Filters.Add(modelFilter);

//FilterChangedイベントに購読します c1DataFilter1.FilterChanged += C1DataFilter1_FilterChanged;}

private void C1DataFilter1_FilterChanged(object sender, EventArgs e){ //データを更新します c1FlexGrid1.DataSource = c1DataFilter1.View.Cast<Car>().ToList();}

public IEnumerable<Car> GetCars(){ var carsTable = _carsTable; foreach (DataRow row in carsTable.Rows) { yield return new Car { Brand = row.Field<string>("Brand"), Category = row.Field<string>("Category"), Description = row.Field<string>("Description"),

C#

  DataFilter for WinForms

23 Copyright © GrapeCity, Inc. All rights reserved.         

Page 25: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Similarly, you can create any other custom filters.

Liter = row.Field<double>("Liter"), Model = row.Field<string>("Model"), Picture = row.Field<byte[]>("Picture"), Price = row.Field<double>("Price"), TransmissAutomatic = row.Field<string>("TransmissAutomatic"), ID = row.Field<int>("ID") }; }}

フィルタの概要

DataFilter control allows you to configure the Checklist filter to implement the filter summaries using AggregateTypeproperty by assigning AggregateType Enum. The feature makes it easier for you to analyze the count, sum, maximumand minimum values of the filter items.

Let us take a use case to display count and maximum values of the filter items in a checklist filter. In the image andexample below, count of the individual filter items of the Brand filter are listed and maximum price values for the filteritems in the Category filter are listed.

You can use the follwing code to display the count of the filter items and the maximum value of a filter itemcorresponding to the data as shown in the above example using AggregateType property.

CS

DataFilter for WinForms  

24 Copyright © GrapeCity, Inc. All rights reserved.         

Page 26: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

private void c1DataFilter1_FilterAutoGenerating(object sender, C1.DataFilter.FilterAutoGeneratingEventArgs e) { switch (e.Property.Name) { //Brandフィルターのチェックリスト項目を設定します case "Brand": brandFilter = (C1.Win.DataFilter.ChecklistFilter)e.Filter; brandFilter.ItemsSource = c1NWindDataSet.Cars; brandFilter.ValueMemberPath = "Brand";

//Brandフィールドに対して定義されているChecklistフィルタの概要を定義します //この概要には、各ブランドで利用可能な車の数が表示されます brandFilter.FilterSummary.AggregateType = AggregateType.Count; brandFilter.FilterSummary.Label = "Count"; brandFilter.FilterSummary.PropertyName = "Brand"; //すべてのフィルター項目を選択します brandFilter.SelectAll(); break;

//Categoryフィルタのチェックリスト項目を設定します case "Category": var categoryFilter = (C1.Win.DataFilter.ChecklistFilter)e.Filter; categoryFilter.ItemsSource = c1NWindDataSet.Cars; categoryFilter.ValueMemberPath = "Category";

//Categoryフィールドに対して定義されているChecklistフィルタの概要を定義します //この概要には、特定のカテゴリの車の最高価格が表示されます categoryFilter.FilterSummary.AggregateType = AggregateType.Max; categoryFilter.FilterSummary.Label = "Max"; categoryFilter.FilterSummary.PropertyName = "Price";

//すべてのフィルター項目を選択します categoryFilter.SelectAll(); break;

//Priceフィルタの最小/最大値を設定します case "Price": var priceFilter = (C1.Win.DataFilter.RangeFilter)e.Filter; priceFilter.Maximum = c1NWindDataSet.Cars.AsEnumerable().Max(x => x.Field<double>("Price")); priceFilter.Minimum = c1NWindDataSet.Cars.AsEnumerable().Min(x => x.Field<double>("Price")); priceFilter.Increment = 1000; priceFilter.Digits = 0; break; //他のすべてのフィルターの作成をキャンセルします default: e.Cancel = true; break; } }

XML シリアル化・逆シリアル化

The DataFilter control supports serialization through SaveFilterExpression and LoadFilterExpression methods of theC1DataFilter class. The SaveFilterExpression method saves the current filter expressions fromC1.Win.DataFilter.C1DataFilter.Filters collection to an XML file. The LoadFilterExpression method loads the saved

  DataFilter for WinForms

25 Copyright © GrapeCity, Inc. All rights reserved.         

Page 27: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

filter expressions from an XML file.

The following GIF demonstrates serialization and deserialization support in the DataFilter control.

The following code shows an example of saving filter expressions to an XML file:

The following code shows an example of loading filter expressions from an XML file:

'現在のフィルター式をxmlファイルに保存しますc1DataFilter1.SaveFilterExpression("SavedFilters.xml");MessageBox.Show("Filter state saved.");

Visual Basic

//現在のフィルター式をxmlファイルに保存しますc1DataFilter1.SaveFilterExpression("SavedFilters.xml");MessageBox.Show("Filter state saved.");

C#

'xmlファイルから現在のフィルター式をロードしますc1DataFilter1.LoadFilterExpression("SavedFilters.xml")MessageBox.Show("Loaded saved Filter state.")

Visual Basic

//xmlファイルから現在のフィルター式をロードしますc1DataFilter1.LoadFilterExpression("SavedFilters.xml");MessageBox.Show("Loaded saved Filter state.");

C#

DataFilter for WinForms  

26 Copyright © GrapeCity, Inc. All rights reserved.         

Page 28: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

テーマ

You can customize the appearance of the DataFilter control using C1Themes. C1Themes makes it easy to style yourcontrols with many built-in themes which can be set using the c1ThemeController component and an easy to usetheme designer, c1ThemeDesigner, that lets you create your own themes or modify the existing ones.

C1Themes allows you to style DataFilter control using the c1ThemeController component. The component loads andmanages visual themes and applies them to forms and controls. You can simply drag and drop the c1ThemeControlleron your form and use the built-in themes to style your control. For example, Material,MaterialDark, Office2016Green, etc. are some available built-in themes. In addition, C1Themes also allows you tocreate custom theme using c1ThemeDesigner and apply it on your control.

The following GIF shows different themes getting applied on the DataFilter control.

To apply a built-in theme to the DataFilter control, follow these steps:

1. Drag and drop the c1ThemeController and C1DataFilter controls on the form.Observe: c1ThemeController is added to the Component tray.

2. Right-click the C1DataFilter control and select Properties from the context menu.3. In the Properties window, click the dropdown next to the Theme on c1ThemeController1 property and select

a theme from the ComponentOne themes list.

You can also create custom themes and modify the existing themes using the C1ThemeDesigner app that getsinstalled on installing ComponentOne WinForms Edition. For more information on loading and applying themes toyour control, see Themes for WinForms.

スタイル

The C1DataFilter class provides Styles property that can be used to customize the appearance of the DataFiltercontrol and its elements. It is of type DataFilterTheme class. Styling is applied to DataFilter control using differentclasses for different elements of the control. The following image depicts several UI elements of the DataFiltercontrol such as buttons, filters, checkboxes, editors, header, filter captions and scrollbars and the classes used to stylethese elements.

  DataFilter for WinForms

27 Copyright © GrapeCity, Inc. All rights reserved.         

Page 29: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

The DataFilterTheme class provides several properties to handle styling of the DataFilter control and the abovementioned elements. Each of these properties is of a specific class type and is used to style a specific element of theDataFilter control. These properties are described below:

Property Description

Common This property is of the type DataFilterCommonStyle class. The appearance of the DataFilter control,such as its background color, padding, margins, border thickness and the border color can bechanged using Common property of the DataFilterTheme class.

The following code shows an example of DataFilter control styling:

Header This property is of type DataFilterHeaderStyle class. It can be used to customize the appearance ofthe control’s header.

The following code shows an example of control header styling:

'DataFilterをスタイルします

c1DataFilter1.Styles.Common.BackColor = Color.LightCyanc1DataFilter1.Styles.Common.Border = 5c1DataFilter1.Styles.Common.Padding = New C1.Framework.Thickness(10, 10)

Visual Basic

//DataFilterをスタイルします

c1DataFilter1.Styles.Common.BackColor = Color.LightCyan;c1DataFilter1.Styles.Common.Border = 5;c1DataFilter1.Styles.Common.Padding = new C1.Framework.Thickness(10, 10);

C#

'DataFilterコントロールのヘッダーをスタイルします

c1DataFilter1.Styles.Header.Font = New Font(FontFamily.GenericSerif, 10!, FontStyle.Bold)

Visual Basic

DataFilter for WinForms  

28 Copyright © GrapeCity, Inc. All rights reserved.         

Page 30: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Filter In the DataFilter control, corresponding to each filter, an accordion tab is added which contains thecontrols used to filter the data-aware control by a specific field. This accordion tab is referred to as aFilter element. The appearance of these filter elements can be customized using this property whichis of type DataFilterFilterStyle class.

The following code shows an example of filter element styling:

FilterCaption The FilterCaption element consists of the filter’s caption (filter’s header text) and the expand/collapseglyph which is shown next to it to show/hide the filter’s contents. This property is of typeDataFilterCaptionStyle class and can be used to customize appearance of the filter header text andthe expand/collapse glyphs.

The following code shows an example of FilterCaption elements styling.

c1DataFilter1.Styles.Header.BackColor = Color.Grayc1DataFilter1.Styles.Header.ForeColor = Color.GhostWhitec1DataFilter1.Styles.Header.BorderColor = Color.Blackc1DataFilter1.Styles.Header.Border = 1

//DataFilterコントロールのヘッダーをスタイルします

c1DataFilter1.Styles.Header.Font = new Font(FontFamily.GenericSerif, 10f, FontStyle.Bold);c1DataFilter1.Styles.Header.BackColor = Color.Gray;c1DataFilter1.Styles.Header.ForeColor = Color.GhostWhite;c1DataFilter1.Styles.Header.BorderColor = Color.Black;c1DataFilter1.Styles.Header.Border = 1;

C#

'フィルターをスタイルします

c1DataFilter1.Styles.Filter.BackColor = Color.LightBluec1DataFilter1.Styles.Filter.ForeColor = Color.Tomato

Visual Basic

//フィルタをスタイルします

c1DataFilter1.Styles.Filter.BackColor = Color.LightBlue;c1DataFilter1.Styles.Filter.ForeColor = Color.Tomato;

C#

'フィルターキャプションをスタイルします c1DataFilter1.Styles.FilterCaption.BackColor = Color.Pinkc1DataFilter1.Styles.FilterCaption.Font = New Font(FontFamily.GenericSansSerif, 10!, FontStyle.Italic)c1DataFilter1.Styles.FilterCaption.Glyph.Collapsed.Hot.BackColor = Color.LightPinkc1DataFilter1.Styles.FilterCaption.Glyph.Expanded.Hot.BackColor = Color.HotPinkc1DataFilter1.Styles.FilterCaption.Glyph.Collapsed.Pressed.BorderColor = Color.LightBluec1DataFilter1.Styles.FilterCaption.Glyph.Expanded.Pressed.BorderColor = Color.Blue

Visual Basic

  DataFilter for WinForms

29 Copyright © GrapeCity, Inc. All rights reserved.         

Page 31: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

CheckBox The CheckBox element consists of a checkbox and a text which is displayed next to it. This property isof type DataFilterCheckBoxStyle class and allows you to customize general appearance of theCheckBox element (background color, foreground color, border thickness etc) and the appearance ofthe checked, unchecked and indeterminate glyphs (which represents the three states of a checkbox)when the mouse cursor is not on them, when the mouse cursor is hovered over them and when themouse button is pressed.

The following code shows an example of CheckBox element styling:

Button The buttons present in the DataFilter control, such as the buttons which represent the upper and thelower thumbs of the range sliders in the RangeFilter and the “More” button appearing in theChecklistFilter when the value of the DisplayedItems property is less than the count of items in its

//フィルタキャプションをスタイルします c1DataFilter1.Styles.FilterCaption.BackColor = Color.Pink;c1DataFilter1.Styles.FilterCaption.Font = new Font(FontFamily.GenericSansSerif, 10f, FontStyle.Italic);c1DataFilter1.Styles.FilterCaption.Glyph.Collapsed.Hot.BackColor = Color.LightPink;c1DataFilter1.Styles.FilterCaption.Glyph.Expanded.Hot.BackColor = Color.HotPink;c1DataFilter1.Styles.FilterCaption.Glyph.Collapsed.Pressed.BorderColor = Color.LightBlue;c1DataFilter1.Styles.FilterCaption.Glyph.Expanded.Pressed.BorderColor = Color.Blue;

C#

'チェックボックスをスタイルします

c1DataFilter1.Styles.CheckBox.Glyph.Checked.BorderColor = Color.Bluec1DataFilter1.Styles.CheckBox.Glyph.Checked.Hot.BackColor = Color.LightBluec1DataFilter1.Styles.CheckBox.Glyph.Unchecked.BorderColor = Color.DarkGreenc1DataFilter1.Styles.CheckBox.Glyph.Unchecked.Pressed.BackColor = Color.Greenc1DataFilter1.Styles.CheckBox.Glyph.Indeterminate.BorderColor = Color.Orange

Visual Basic

//チェックボックスをスタイルします

c1DataFilter1.Styles.CheckBox.Glyph.Checked.BorderColor = Color.Blue;c1DataFilter1.Styles.CheckBox.Glyph.Checked.Hot.BackColor = Color.LightBlue;c1DataFilter1.Styles.CheckBox.Glyph.Unchecked.BorderColor = Color.DarkGreen;c1DataFilter1.Styles.CheckBox.Glyph.Unchecked.Pressed.BackColor = Color.Green;c1DataFilter1.Styles.CheckBox.Glyph.Indeterminate.BorderColor = Color.Orange;

C#

DataFilter for WinForms  

30 Copyright © GrapeCity, Inc. All rights reserved.         

Page 32: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

ItemSource property, can be styled with this property. This property is oftype DataFilterButtonStyle class. Different styles can be applied to button depending on whetherthe mouse cursor is outside the button, over it or mouse button is in pressed state.

The following code shows an example of button styling:

ScrollBar If the height of the ChecklistFilter is exhausted and all the checklist items are not able to fit into theavailable space, a scrollbar is shown in order to view all the checklist items. You can use the ScrollBarproperty to style the scrollbar buttons (the up and down arrows) and the scrollbar thumb (themovable bar).This property is of type DataFilterScrollBarStyle class.

The following code shows an example of scrollbar styling:

Editor The range editors and the search box editor can be styled using Editor property of theDataFilterTheme class and is of type DataFilterEditorStyle class.

The following code shows an example of editor styling in the DataFilter control.

'ボタンをスタイルします

c1DataFilter1.Styles.Button.BackColor = Color.DarkSlateBluec1DataFilter1.Styles.Button.ForeColor = Color.Whitec1DataFilter1.Styles.Button.Hot.BackColor = Color.LightBluec1DataFilter1.Styles.Button.Pressed.BackColor = Color.BlueViolet

Visual Basic

//ボタンをスタイルします

c1DataFilter1.Styles.Button.BackColor = Color.DarkSlateBlue;c1DataFilter1.Styles.Button.ForeColor = Color.White;c1DataFilter1.Styles.Button.Hot.BackColor = Color.LightBlue;c1DataFilter1.Styles.Button.Pressed.BackColor = Color.BlueViolet;

C#

'スクロールバーをスタイルします

c1DataFilter1.Styles.ScrollBar.BackColor = Color.LightSteelBluec1DataFilter1.Styles.ScrollBar.BorderColor = Color.Orangec1DataFilter1.Styles.ScrollBar.Buttons.BackColor = Color.LightPinkc1DataFilter1.Styles.ScrollBar.Thumb.BackColor = Color.MediumPurplec1DataFilter1.Styles.ScrollBar.Thumb.Hot.BackColor = Color.Purple

Visual Basic

//スクロールバーをスタイルします

c1DataFilter1.Styles.ScrollBar.BackColor = Color.LightSteelBlue;c1DataFilter1.Styles.ScrollBar.BorderColor = Color.Orange;c1DataFilter1.Styles.ScrollBar.Buttons.BackColor = Color.LightPink;c1DataFilter1.Styles.ScrollBar.Thumb.BackColor = Color.MediumPurple;c1DataFilter1.Styles.ScrollBar.Thumb.Hot.BackColor = Color.Purple;

C#

'エディタをスタイルします

Visual Basic

  DataFilter for WinForms

31 Copyright © GrapeCity, Inc. All rights reserved.         

Page 33: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

c1DataFilter1.Styles.Editor.BackColor = Color.LightGoldenrodYellowc1DataFilter1.Styles.Editor.Hot.BackColor = Color.LightGray

//エディタをスタイルします

c1DataFilter1.Styles.Editor.BackColor = Color.LightGoldenrodYellow;c1DataFilter1.Styles.Editor.Hot.BackColor = Color.LightGray;

C#

キーボードによる移動

Keyboard navigation support provides an effective way to navigate through the filters, simply by using the definedkeys when required.

In DataFilter control, this feature allows you to navigate through the vertically stacked list and move the focusbetween different filter conditions. It makes the process to drill-down the list and find the filters much more easierand convenient through the keyboard.

The following table describes the actions and their associated keys to use when navigating through the list of filterconditions:

Keyboard Command Action

Page Up Moves focus one level up in the list

Page Down Moves focus one level down in the list

Home Moves focus to the first filter condition in the list

End Moves focus to the last filter condition in the list

The following GIF demonstrates navigating filters in the DataFilter control using the keyboard.

DataFilter for WinForms  

32 Copyright © GrapeCity, Inc. All rights reserved.         

Page 34: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

チュートリアル

The walkthrough topics in this section are created with the assumption that you are familiar with the DataFilter controland know how to use it in general.

FlexGrid との DataFilter の使用

Learn how to use the DataFilter control with the FlexGrid control.

FlexGrid との DataFilter の使用

FlexGrid provides built-in filtering support with the help of column filters. However, consider a scenario where you want a filtering UI similarto the one seen in different e-commerce websites where a grid displaying the product listing shows only few attributes such as the productimage, product name and product price. Although, the user is allowed to filter the product listing by many other attributes such as brand,category, price etc. It is not possible to set such kind of filters from column filters in data grid controls. Hence, this walkthrough explains howyou can use the DataFilter control to filter FlexGrid content using a filtering UI similar to any online store’s website.

To create an application for filtering a car list by brand, category, and price, complete the following steps:

1. Setting up the application UI2. Creating data source for FlexGrid and DataFilter3. Configuring FlexGrid control4. Configuring DataFilter control

The following image shows a list of cars filtered by a specific brand, category and price in FlexGrid using the DataFilter control.

Step 1: Setting up the application UI

1. Create a new Windows Forms App.2. To create separate panels for placing controls, drag and drop the MS SplitContainer from the Toolbox onto your form.3. To add an icon or a logo representing a company or business, drag and drop the MS PictureBox control from the Toolbox onto

Panel1 of the SplitContainer control. Set its Dock property to Top and add an image to the control using its Image property.4. To show different filtering criterias such as brand, category, etc., drag and drop the DataFilter control from the Toolbox onto Panel1

of the SplitContainer control. Set its Dock property to Bottom.5. To display a list of cars, drag and drop the FlexGrid control from the Toolbox onto Panel2 of the SplitContainer control. Set its

Dock property to Fill.

Back to Top

Step 2: Creating data source for FlexGrid and DataFilter

1. Define a method, for example CreateDataSource, to create datasource for the FlexGrid and DataFilter controls.

  DataFilter for WinForms

33 Copyright © GrapeCity, Inc. All rights reserved.         

Page 35: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Note that _carsTable is declared as a global variable of type DataTable.

2. Invoke the method from the Form’s Load event handler to generate the data for FlexGrid and DataFilter controls.

Back to Top

Step 3: Configuring FlexGrid control

1. To bind the FlexGrid control to a data source and set its properties, add the following code to the Form Load event handler.

Private Sub CreateDataSource() Dim con As OleDbConnection = New OleDbConnection(("provider=microsoft.jet.oledb.4.0;Data Source=" _ + (Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\ComponentOne Samples\Common\C1NWind.mdb"))) _carsTable = New DataTable (New OleDbDataAdapter("Select * from Cars", con) + Fill(_carsTable))End Sub

Visual Basic

private void CreateDataSource(){ OleDbConnection con = new OleDbConnection( "provider=microsoft.jet.oledb.4.0;Data Source=" + Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\ComponentOne Samples\\Common\\C1NWind.mdb"); _carsTable = new DataTable(); new OleDbDataAdapter("Select * from Cars", con).Fill(_carsTable);}

C#

Private Sub CreateDataSource() Dim con As OleDbConnection = New OleDbConnection(("provider=microsoft.jet.oledb.4.0;Data Source=" _ + (Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\ComponentOne Samples\Common\C1NWind.mdb"))) _carsTable = New DataTable (New OleDbDataAdapter("Select * from Cars", con) + Fill(_carsTable))End Sub

Visual Basic

private void CreateDataSource(){ OleDbConnection con = new OleDbConnection( "provider=microsoft.jet.oledb.4.0;Data Source=" + Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\ComponentOne Samples\\Common\\C1NWind.mdb"); _carsTable = new DataTable(); new OleDbDataAdapter("Select * from Cars", con).Fill(_carsTable);}

C#

'FlexGridを構成しますc1FlexGrid1.AutoGenerateColumns = falsec1FlexGrid1.DataSource = _carsTable'列名を表示している一番上の行を非表示にしますc1FlexGrid1.Rows.Fixed = 0'デフォルトで追加された列を削除しますc1FlexGrid1.Cols.Count = 0'グリッドの追加プロパティを設定しますc1FlexGrid1.Styles.Normal.Font = New Font(FontFamily.GenericSansSerif, 10!, FontStyle.Regular)c1FlexGrid1.Rows.DefaultSize = 208c1FlexGrid1.Cols.DefaultSize = 263

Visual Basic

//FlexGridを構成します

C#

DataFilter for WinForms  

34 Copyright © GrapeCity, Inc. All rights reserved.         

Page 36: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Note that in order to filter the data-aware control, FlexGrid, using the DataFilter control, both the controls must share a common datasource.

2. To display the car image and information in a cell, add unbound columns to the FlexGrid control, for example, we have added threeunbound columns to the FlexGrid control and subscribed the GetUnboundValue event to populate these columns with data.

Note that _colCount is defined as a global variable with value equal to 3.

3. To populate the unbound columns with car data along with the images, add the following code to the GetUnboundValue eventhandler.

c1FlexGrid1.AutoGenerateColumns = false;c1FlexGrid1.DataSource = _carsTable;

//列名を表示している一番上の行を非表示にしますc1FlexGrid1.Rows.Fixed = 0;

//デフォルトで追加された列を削除しますc1FlexGrid1.Cols.Count = 0;

//グリッドの追加プロパティを設定しますc1FlexGrid1.Styles.Normal.Font = new Font(FontFamily.GenericSansSerif, 10f, FontStyle.Regular);c1FlexGrid1.Rows.DefaultSize = 208;c1FlexGrid1.Cols.DefaultSize = 263;

'FlexGridに非連結列を追加しますc1FlexGrid1.Cols.Add(_colCount)'非連結セルのデータを取得しますc1FlexGrid1.GetUnboundValue = (c1FlexGrid1.GetUnboundValue + _flex_GetUnboundValue)

Visual Basic

//FlexGridに非連結列を追加しますc1FlexGrid1.Cols.Add(_colCount);

//非連結セルのデータを取得しますc1FlexGrid1.GetUnboundValue += _flex_GetUnboundValue;

C#

Private Sub _flex_GetUnboundValue(ByVal sender As Object, ByVal e As UnboundValueEventArgs)'自動車のIDを返すUserDataプロパティ値を取得するためにセルスタイルを取得します Dim cs As CellStyle = c1FlexGrid1.Styles(("CellStyle" _ + (e.Row + ("," + e.Col))))'上記で取得した自動車のIDに応じてセルに自動車の画像と情報を表示します If ((Not (cs) Is Nothing) _ AndAlso (Not (cs.UserData) Is Nothing)) Then Dim carId As Integer = (Convert.ToInt32(cs.UserData) - 1) c1FlexGrid1.SetCellImage(e.Row, e.Col, GetImagesFromByteArray(CType(_carsTable.Rows(carId)("Picture"),Byte()))) e.Value = ("Model: " _ + (_carsTable.Rows(carId)("Model") + (""& vbLf&"Brand:" _ + (_carsTable.Rows(carId)("Brand") + (""& vbLf&"Price:" + _carsTable.Rows(carId)("Price"))))))End IfEnd Sub

Visual Basic

private void _flex_GetUnboundValue(object sender, UnboundValueEventArgs e){ //自動車のIDを返すUserDataプロパティ値を取得するためにセルスタイルを取得します CellStyle cs = c1FlexGrid1.Styles["CellStyle" + e.Row + "," + e.Col];

//上記で取得した自動車のIDに応じてセルに自動車の画像と情報を表示します if (cs != null && cs.UserData != null) { int carId = Convert.ToInt32(cs.UserData) - 1; c1FlexGrid1.SetCellImage(e.Row, e.Col, GetImagesFromByteArray((Byte[])_carsTable.Rows[carId]["Picture"]));

C#

  DataFilter for WinForms

35 Copyright © GrapeCity, Inc. All rights reserved.         

Page 37: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Note that the GetUnboundValue event handler uses the ‘GetImagesFromByteArray’ method to retrieve the car images stored as OLEobjects in the Access database.

4. Define the GetImagesFromByteArray’ method using the following code.

Back to Top

Step 4: Configuring DataFilter control

1. To automatically generate the filters, set the AutoGenerateFilters property of DataFilter to true in the Form Load event handler.

2. To define the filtering criterias such as the minimum /maximum values for the RangeFilter and the checklist items for theCheckListFilter, subscribe to the FilterAutoGenerating event in the Form_Load event.

e.Value = "Model: " + _carsTable.Rows[carId]["Model"] + "\nBrand:" + _carsTable.Rows[carId]["Brand"] + "\nPrice:" + _carsTable.Rows[carId]["Price"]; }}

Private Function GetImagesFromByteArray(ByVal picData() As Byte) As Image'バイト配列として保存された画像データを使用して自動車の画像を生成します If (picData Is Nothing) Then Return Nothing End If Dim bmData As Integer = 78

((picData(0) = 21) _ AndAlso (picData(1) = 28)) 0 Dim ms As System.IO.MemoryStream = New System.IO.MemoryStream(picData, bmData, (picData.Length - bmData)) Return Image.FromStream(ms)End Function

Visual Basic

private Image GetImagesFromByteArray(byte[] picData){ //バイト配列として保存された画像データを使用して自動車の画像を生成します if (picData == null) { return null; } int bmData = (picData[0] == 0x15 && picData[1] == 0x1c) ? 78 : 0; System.IO.MemoryStream ms = new System.IO.MemoryStream(picData, bmData, picData.Length - bmData); return Image.FromStream(ms);}

C#

'フィルターを自動的に生成しますc1DataFilter1.AutoGenerateFilters = true

Visual Basic

//フィルターを自動的に生成しますc1DataFilter1.AutoGenerateFilters = true;

C#

'自動的に生成されたフィルターを変更しますc1DataFilter1.FilterAutoGenerating = (c1DataFilter1.FilterAutoGenerating + C1DataFilter1_FilterAutoGenerating)

Visual Basic

//自動的に生成されたフィルターを変更します

C#

DataFilter for WinForms  

36 Copyright © GrapeCity, Inc. All rights reserved.         

Page 38: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

3. Add the following code to the FilterAutoGenerating event handler to customize the automatically generated filters.

c1DataFilter1.FilterAutoGenerating += C1DataFilter1_FilterAutoGenerating;

Private Sub C1DataFilter1_FilterAutoGenerating(ByVal sender As Object, ByVal e As C1.DataFilter.FilterAutoGeneratingEventArgs) '自動的に生成されたフィルターを変更します Select Case e.[Property].Name 'Categoryフィルターのチェックリスト項目を設定します Case "Category" Dim categoryFilter = CType(e.Filter, C1.Win.DataFilter.ChecklistFilter) categoryFilter.ItemsSource = _carsTable categoryFilter.ValueMemberPath = "Category" categoryFilter.SelectAll() 'Brandフィルターのチェックリスト項目を設定します Case "Brand" Dim brandFilter = CType(e.Filter, C1.Win.DataFilter.ChecklistFilter) brandFilter.ItemsSource = _carsTable brandFilter.ValueMemberPath = "Brand" brandFilter.SelectAll() 'Literフィルターの最小値・最大値を設定します Case "Liter" Dim literFilter = CType(e.Filter, C1.Win.DataFilter.RangeFilter) literFilter.Maximum = _carsTable.AsEnumerable().Max(Function(x) x.Field(Of Double)("Liter")) literFilter.Minimum = _carsTable.AsEnumerable().Min(Function(x) x.Field(Of Double)("Liter")) literFilter.Increment = 0.01 literFilter.Digits = 3 'Priceフィルターの最小値・最大値を設定します Case "Price" Dim priceFilter = CType(e.Filter, C1.Win.DataFilter.RangeFilter) priceFilter.Maximum = _carsTable.AsEnumerable().Max(Function(x) x.Field(Of Double)("Price")) priceFilter.Minimum = _carsTable.AsEnumerable().Min(Function(x) x.Field(Of Double)("Price")) priceFilter.Increment = 1000 priceFilter.Digits = 0 Case Else e.Cancel = True End SelectEnd Sub

Visual Basic

private void C1DataFilter1_FilterAutoGenerating(object sender, C1.DataFilter.FilterAutoGeneratingEventArgs e){ //自動的に生成されたフィルターを変更します switch (e.Property.Name) { //Categoryフィルターのチェックリスト項目を設定します case "Category": var categoryFilter = (C1.Win.DataFilter.ChecklistFilter)e.Filter; categoryFilter.ItemsSource = _carsTable; categoryFilter.ValueMemberPath = "Category"; categoryFilter.SelectAll(); break; //Brandフィルターのチェックリスト項目を設定します case "Brand": var brandFilter = (C1.Win.DataFilter.ChecklistFilter)e.Filter; brandFilter.ItemsSource = _carsTable; brandFilter.ValueMemberPath = "Brand"; brandFilter.SelectAll(); break; //Literフィルターの最小値・最大値を設定します case "Liter": var literFilter = (C1.Win.DataFilter.RangeFilter)e.Filter; literFilter.Maximum = _carsTable.AsEnumerable().Max(x => x.Field<double>("Liter")); literFilter.Minimum = _carsTable.AsEnumerable().Min(x => x.Field<double>("Liter"));

C#

  DataFilter for WinForms

37 Copyright © GrapeCity, Inc. All rights reserved.         

Page 39: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

4. To handle the FilterChanged event and reset the FlexGrid to display the car information appropriately, subscribe to the FilterChangedevent.Note that on applying the filter to the FlexGrid, the grid is rendered with the default settings. So, the FilterChanged event needs to behandled.

5. Add the following code to the FilterChanged event handler to reset FlexGrid to display the car information.

literFilter.Increment = 0.01; literFilter.Digits = 3; break; //Priceフィルターの最小値・最大値を設定します case "Price": var priceFilter = (C1.Win.DataFilter.RangeFilter)e.Filter; priceFilter.Maximum = _carsTable.AsEnumerable().Max(x => x.Field<double>("Price")); priceFilter.Minimum = _carsTable.AsEnumerable().Min(x => x.Field<double>("Price")); priceFilter.Increment = 1000; priceFilter.Digits = 0; break; default: e.Cancel = true; break; }}

'このイベントはフィルターが変更されたときに発生します'フィルターした行に関する関連情報を取得するために使用しますc1DataFilter1.FilterChanged += C1DataFilter1_FilterChanged

Visual Basic

//このイベントはフィルターが変更されたときに発生します//フィルターした行に関する関連情報を取得するために使用しますc1DataFilter1.FilterChanged += C1DataFilter1_FilterChanged;

C#

Private Sub C1DataFilter1_FilterChanged(ByVal sender As Object, ByVal e As EventArgs) 'FlexGridを再構成します c1FlexGrid1.Styles.Clear c1FlexGrid1.Row = -1 'FlexGridからデフォルトの選択をクリアします Dim col As Integer = 0 Do While (col < _colCount) c1FlexGrid1.Cols(col).ImageAlign = ImageAlignEnum.CenterTop c1FlexGrid1.Cols(col).TextAlign = TextAlignEnum.CenterBottom col = (col + 1) Loop 'フィルターした行のリストを取得します Dim filteredCars As List(Of DataRowView) = c1DataFilter1.View.Cast(Of DataRowView).ToList 'CellStyleのUserDataプロパティを使用して自動車のIdを保存します Dim row As Integer = 0 Do While (row < filteredCars.Count) Dim cs As CellStyle = c1FlexGrid1.Styles.Add(("CellStyle" _ + ((row / _colCount) + ("," _ + (row Mod _colCount))))) cs.UserData = filteredCars(row).Row("ID") row = (row + 1) Loop 'フィルターされた行のデータは3列にレンダリングされるので、 'FlexGridで余分な行を非表示にします Dim rowCount As Integer = CType(Math.Ceiling((filteredCars.Count / CType(_colCount,Double))),Integer) Dim i As Integer = rowCount Do While (i < c1FlexGrid1.Rows.Count) c1FlexGrid1.Rows(i).Visible = false i = (i + 1) Loop

Visual Basic

DataFilter for WinForms  

38 Copyright © GrapeCity, Inc. All rights reserved.         

Page 40: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

6. In the Form_Load event, bind the DataFilter control to the same datasource which was assigned to the FlexGrid control.

7. Run the application and observe how the cars data with image appear in the FlexGrid control while all the car attribute filters areadded to the DataFilter control.Now, you can change the filter values in the DataGrid UI and see how the FlexGrid renders the filtered data.

Back to Top

End Sub

private void C1DataFilter1_FilterChanged(object sender, EventArgs e){ //FlexGridを再構成します c1FlexGrid1.Styles.Clear(); c1FlexGrid1.Row = -1; // FlexGridからデフォルトの選択をクリアします for (int col = 0; col < _colCount; col++) { c1FlexGrid1.Cols[col].ImageAlign = ImageAlignEnum.CenterTop; c1FlexGrid1.Cols[col].TextAlign = TextAlignEnum.CenterBottom; }

//フィルターした行のリストを取得します List<DataRowView> filteredCars = c1DataFilter1.View.Cast<DataRowView>().ToList();

//CellStyleのUserDataプロパティを使用して自動車のIdを保存します for (int row = 0; row < filteredCars.Count; row++) { CellStyle cs = c1FlexGrid1.Styles.Add("CellStyle" + row / _colCount + "," + row % _colCount); cs.UserData = filteredCars[row].Row["ID"]; }

//フィルターされた行のデータは3列にレンダリングされるので、 //FlexGridで余分な行を非表示にします int rowCount = (int)Math.Ceiling(filteredCars.Count / (double)_colCount); for (int i = rowCount; i < c1FlexGrid1.Rows.Count; i++) c1FlexGrid1.Rows[i].Visible = false;}

C#

c1DataFilter1.DataSource = _carsTable

Visual Basic

c1DataFilter1.DataSource = _carsTable;

C#

FlexChart との DataFilter の使用

DataFilter allows you to add different controls as custom filters. The custom filters can be added to DataFilter forfiltering data using complex data visualization controls, such as FlexChart and Maps. This walkthrough uses FlexChartas a custom filter in DataFilter to filter FlexGrid data.

To create a custom filter using FlexChart, complete the following steps:

1. Set up the Application UI2. Create the View3. Create a Custom Filter4. Use the Custom Filter with DataFilter

The following GIF shows FlexGrid data getting filtered based on the category selection in the custom filter "Category-wise Sales" from the DataFilter UI:

  DataFilter for WinForms

39 Copyright © GrapeCity, Inc. All rights reserved.         

Page 41: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Step 1: Setting up the Application UI

1. Create a new Windows Forms App.2. Drag and drop the MS SplitContainer from the Toolbox onto your form to create separate panels for placing

controls.3. Drag and drop the DataFilter control from the Toolbox onto Panel1 of the SplitContainer control to display

the custom filter. Set its Dock property to Fill.4. Drag and drop the FlexGrid control from the Toolbox onto Panel2 of the SplitContainer control to display

sales data. Set its Dock property to Fill.

Back to Top

Step 2: Create the View

1. Create a class named FlexChartFilterView to be used as a View for using FlexChart as a Filter and update theclass constructor using the following code.

Private _selectedIndices As List(Of Integer) Private _items As IEnumerable(Of Object) Private _chbClear As CheckBox Protected FlowLayoutPanel _pnlControlOptions

Public ReadOnly Property Chart As FlexChart Get Return _chart End Get End Property

Public ReadOnly Property IsFilterApplied As Boolean Get Return Not _chbClear.Checked End Get End Property

Public Event SelectionChanged As EventHandler

Visual Basic

DataFilter for WinForms  

40 Copyright © GrapeCity, Inc. All rights reserved.         

Page 42: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Public Sub FlexChartFilterView(ByVal items As IEnumerable(Of Object), ByVal bindingX As String, ByVal binding As String, ByVal Optional chartType As ChartType = ChartType.Column) InitializeComponent() _selectedIndices = New List(Of Integer)() Me._items = items _chart = New FlexChart() With { .ChartType = chartType, .DataSource = items, .BindingX = bindingX, .Binding = binding, .BackColor = Color.White, .Dock = DockStyle.Fill, .Margin = New Padding(0, 30, 0, 0) } Dim ser = New Series() Me.Chart.Series.Add(ser) Me.Chart.SelectionStyle.Stroke = Brushes.DarkBlue Me.Chart.SelectionStyle.StrokeWidth = 2 Me.Chart.SelectionStyle.Fill = New SolidBrush(Color.FromArgb(200, Color.CornflowerBlue)) Me.Chart.ToolTip.Content = "X: {x} " & vbLf & "Y: {y}" Me.Chart.AxisX.LabelMax = CSharpImpl.__Assign(Me.Chart.AxisX.LabelMin, True) Me.Chart.MouseClick += OnChartMouseClick ser.SymbolRendering += OnSeriesSymbolRendering _pnlControlOptions = New FlowLayoutPanel() With { .FlowDirection = FlowDirection.LeftToRight, .Dock = DockStyle.Top, .Height = 30, .AutoScroll = True } _chbClear = New CheckBox() With { .Text = "Clear", .Checked = True, .Enabled = False, .AutoSize = True } _chbClear.CheckedChanged += Function(s, e) OnClearChanged() _pnlControlOptions.Controls.Add(_chbClear) Controls.Add(_pnlControlOptions) Controls.Add(Chart) End Sub

private List <int> _selectedIndices;private IEnumerable <object> _items;private CheckBox _chbClear;protected FlowLayoutPanel _pnlControlOptions;

public FlexChart Chart { get { return _chart; }}public bool IsFilterApplied { get { return !_chbClear.Checked; }}

C#

  DataFilter for WinForms

41 Copyright © GrapeCity, Inc. All rights reserved.         

Page 43: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

2. Use the MouseClick event on FlexChart for allowing user to filter the rendered data by the clicked items, i.e,data-points.

public event EventHandler SelectionChanged;

public FlexChartFilterView(IEnumerable>object< items, string bindingX, string binding, ChartType chartType = ChartType.Column){ InitializeComponent(); _selectedIndices = new List>int<(); this._items = items;

//チャートを初期化します _chart = new FlexChart() { ChartType = chartType, DataSource = items, BindingX = bindingX, Binding = binding, BackColor = Color.White, Dock = DockStyle.Fill, Margin = new Padding(0, 30, 0, 0) };

var ser = new Series(); this.Chart.Series.Add(ser);

this.Chart.SelectionStyle.Stroke = Brushes.DarkBlue; this.Chart.SelectionStyle.StrokeWidth = 2; this.Chart.SelectionStyle.Fill = new SolidBrush(Color.FromArgb(200, Color.CornflowerBlue)); this.Chart.ToolTip.Content = "X: {x} \nY: {y}"; this.Chart.AxisX.LabelMax = this.Chart.AxisX.LabelMin = true;

//チャートのMouseClickイベントを処理し、選択/フィルター済みアイテムを更新します this.Chart.MouseClick += OnChartMouseClick; //SelectionStyleでSelected/Filteredアイテム(データポイント)をレンダリングするための系列のSymbolRenderingイベントを処理します ser.SymbolRendering += OnSeriesSymbolRendering;

_pnlControlOptions = new FlowLayoutPanel() { FlowDirection = FlowDirection.LeftToRight, Dock = DockStyle.Top, Height = 30, AutoScroll = true, };

_chbClear = new CheckBox() { Text = "Clear", Checked = true, Enabled = false, AutoSize = true, }; _chbClear.CheckedChanged += (s, e) =< OnClearChanged(); _pnlControlOptions.Controls.Add(_chbClear);

Controls.Add(_pnlControlOptions); Controls.Add(Chart);}

DataFilter for WinForms  

42 Copyright © GrapeCity, Inc. All rights reserved.         

Page 44: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

3. Use SymbolRendering event on the series for rendering the selected or filtered items as highlighted.

Private Sub OnChartMouseClick(ByVal sender As Object, ByVal e As MouseEventArgs) Dim hitTest = Chart.HitTest(e.Location)

If hitTest.Item IsNot Nothing AndAlso hitTest.Distance = 0 Then Dim currentSelected = hitTest.PointIndex

If Not _selectedIndices.Contains(currentSelected) Then _selectedIndices.Add(currentSelected) Else _selectedIndices.Remove(currentSelected) End If

OnSelectedPointsChanged() End IfEnd Sub

Visual Basic

private void OnChartMouseClick(object sender, MouseEventArgs e) { //クリックの場所でアイテム/データポイントを確認し、それに応じて選択を変更します var hitTest = Chart.HitTest(e.Location); if (hitTest.Item != null && hitTest.Distance == 0) { var currentSelected = hitTest.PointIndex; if (!_selectedIndices.Contains(currentSelected)) _selectedIndices.Add(currentSelected); else _selectedIndices.Remove(currentSelected); OnSelectedPointsChanged(); }}

C#

Private Sub OnSeriesSymbolRendering(ByVal sender As Object, ByVal e As RenderSymbolEventArgs) If _selectedIndices.Contains(e.Index) Then If Chart.SelectionStyle.Stroke IsNot Nothing Then e.Engine.SetStroke(Chart.SelectionStyle.Stroke) If Chart.SelectionStyle.StrokeWidth > 0 Then e.Engine.SetStrokeThickness(Chart.SelectionStyle.StrokeWidth) If Chart.SelectionStyle.Fill IsNot Nothing Then e.Engine.SetFill(Chart.SelectionStyle.Fill) End IfEnd Sub

Visual Basic

private void OnSeriesSymbolRendering(object sender, RenderSymbolEventArgs e) { if (_selectedIndices.Contains(e.Index)) { if (Chart.SelectionStyle.Stroke != null) e.Engine.SetStroke(Chart.SelectionStyle.Stroke); if (Chart.SelectionStyle.StrokeWidth > 0) e.Engine.SetStrokeThickness(Chart.SelectionStyle.StrokeWidth); if (Chart.SelectionStyle.Fill != null) e.Engine.SetFill(Chart.SelectionStyle.Fill); }}

C#

  DataFilter for WinForms

43 Copyright © GrapeCity, Inc. All rights reserved.         

Page 45: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

4. Raise the SelectionChanged event on this view whenever selected or filtered items change.

Back to Top

Step 3: Create a Custom Filter

1. Create a class named FlexChartFilter, inheriting CustomFilter class, to be used as a custom filter, initializeFlexChartFilterView and use a control for FlexChartFilter.

2. Subscribe the SelectionChanged event on the view to create/update the FilterExpression.

Private Sub OnSelectedPointsChanged() _chbClear.Checked = If(_selectedIndices.Count = 0, True, False) Chart.Refresh() RaiseEvent SelectionChanged(Me, Nothing)End Sub

Visual Basic

private void OnSelectedPointsChanged() { _chbClear.Checked = _selectedIndices.Count == 0 ? true : false; Chart.Refresh(); if (SelectionChanged != null) SelectionChanged(this, null);}

C#

Public Sub New(ByVal items As IEnumerable(Of Object), ByVal xProperty As String, ByVal yProperty As String, ByVal Optional chartType As ChartType = ChartType.Column, ByVal Optional filterUsingXY As Boolean = False) filterView = New FlexChartFilterView(items, xProperty, yProperty, chartType) With { .Height = 250 } Control = filterView propertyX = xProperty propertyY = yProperty Me.filterUsingXY = filterUsingXY End Sub

Visual Basic

public FlexChartFilter(IEnumerable <object> items, string xProperty, string yProperty, ChartType chartType = ChartType.Column, bool filterUsingXY = false) { //このフィルターのUIを提供するFlexChartFilterViewインスタンスを作成します filterView = new FlexChartFilterView(items, xProperty, yProperty, chartType) { Height = 250 };

//FlexChartFilterViewをフィルタリングに使用するコントロールとして設定します Control = filterView;

propertyX = xProperty; propertyY = yProperty; this.filterUsingXY = filterUsingXY;}

C#

Visual Basic

DataFilter for WinForms  

44 Copyright © GrapeCity, Inc. All rights reserved.         

Page 46: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

3. Use the selected items provided by the view for creating the FilterExpression.

//選択したアイテムが変更されたときに新しいフィルター式を作成するためのフィルタービューでSelectionChangedイベントを処理しますfilterView.SelectionChanged += Function(s, e) OnValueChanged()

//選択したアイテムが変更されたときに新しいフィルター式を作成するために、フィルタービューでSelectionChangedイベントを処理しますfilterView.SelectionChanged += (s, e) => OnValueChanged();

C#

Class SurroundingClass Protected Overrides Function GetExpression() As Expression Dim selectedItems = filterView.GetSelectedValues() Return CreateExpression(selectedItems) End Function

Public Overrides ReadOnly Property IsApplied As Boolean Get Return filterView.IsFilterApplied End Get End Property

Private Function CreateExpression(ByVal selectedItems As IEnumerable(Of Object)) As Expression Dim exp As CombinationExpression = New CombinationExpression() exp.FilterCombination = C1.CollectionView.FilterCombination.[Or]

For Each item In selectedItems Dim comboExp = New CombinationExpression() With { .FilterCombination = C1.CollectionView.FilterCombination.[And] } comboExp.Expressions.Add(New OperationExpression With { .PropertyName = propertyX, .Value = GetPropertyValue(propertyX, item), .FilterOperation = C1.CollectionView.FilterOperation.Equal })

If filterUsingXY Then

For Each [property] In propertyY.Split(","c) comboExp.Expressions.Add(New OperationExpression With { .PropertyName = [property].Trim(), .Value = GetPropertyValue([property].Trim(), item), .FilterOperation = C1.CollectionView.FilterOperation.Equal }) Next End If

exp.Expressions.Add(comboExp) Next

Return exp End Function

Protected Function GetPropertyValue(ByVal name As String, ByVal obj As Object) As Object Dim propInfo = obj.[GetType]().GetProperty(name)

Visual Basic

  DataFilter for WinForms

45 Copyright © GrapeCity, Inc. All rights reserved.         

Page 47: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Back to Top

Step 4: Use the Custom Filter with DataFilter

1. Bind the FlexGrid control to a data source and update data source when filter condition or expression getschanged.

Return propInfo.GetValue(obj) End FunctionEnd Class

protected override Expression GetExpression() { var selectedItems = filterView.GetSelectedValues(); return CreateExpression(selectedItems);}

public override bool IsApplied { get { return filterView.IsFilterApplied; }}

private Expression CreateExpression(IEnumerable < object > selectedItems) { CombinationExpression exp = new CombinationExpression(); exp.FilterCombination = C1.CollectionView.FilterCombination.Or;

//選択した各アイテムの式を作成します foreach(var item in selectedItems) { var comboExp = new CombinationExpression() { FilterCombination = C1.CollectionView.FilterCombination.And }; //X-Valueに一致する式。 comboExp.Expressions.Add(new OperationExpression { PropertyName = propertyX, Value = GetPropertyValue(propertyX, item), FilterOperation = C1.CollectionView.FilterOperation.Equal, }); if (filterUsingXY) { //対応するY値に一致する式 foreach(var property in propertyY.Split(',')) { comboExp.Expressions.Add(new OperationExpression { PropertyName = property.Trim(), Value = GetPropertyValue(property.Trim(), item), FilterOperation = C1.CollectionView.FilterOperation.Equal, }); } } exp.Expressions.Add(comboExp); } return exp;}protected object GetPropertyValue(string name, object obj) { var propInfo = obj.GetType().GetProperty(name); return propInfo.GetValue(obj);}

C#

Private salesData As ObservableCollection(Of Sales)

Visual Basic

DataFilter for WinForms  

46 Copyright © GrapeCity, Inc. All rights reserved.         

Page 48: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

2. Set the AutoGenerateFilters property of DataFilter to false in the Form Load event handler for using customfilters.

3. Create an instance of the FlexChartFilter and add it to the Filters collection of DataFilter.

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) salesData = New ObservableCollection(Of Sales)(DataService.GetSalesData(500)) 'FlexGridの設定 c1FlexGrid1.DataSourceChanged += AddressOf C1FlexGrid1_DataSourceChanged c1FlexGrid1.DataSource = salesData 'DataFilterのソースを設定します c1DataFilter1.DataSource = salesData c1DataFilter1.FilterChanged += Function(s, args) 'フィルター条件/式に変更があるたびにFlexGridのデータソースをリセットします c1FlexGrid1.DataSource = c1DataFilter1.View.ToList() End FunctionEnd Sub

Private Sub C1FlexGrid1_DataSourceChanged(ByVal sender As Object, ByVal e As EventArgs) For i As Integer = 1 To c1FlexGrid1.Cols.Count - 1 c1FlexGrid1.Cols(i).StarWidth = "*" NextEnd Sub

private ObservableCollection <Sales> salesData;

private void Form1_Load(object sender, EventArgs e) { salesData = new ObservableCollection <Sales> (DataService.GetSalesData(500)); //FlexGridの設定 c1FlexGrid1.DataSourceChanged += C1FlexGrid1_DataSourceChanged; c1FlexGrid1.DataSource = salesData; //DataFilterのソースを設定しますc1DataFilter1.DataSource = salesData;c1DataFilter1.FilterChanged += (s, args) =>{ //フィルター条件/式に変更があるたびにFlexGridのデータソースをリセットします c1FlexGrid1.DataSource = c1DataFilter1.View.ToList();};} private void C1FlexGrid1_DataSourceChanged(object sender, EventArgs e) { for (int i = 1; i < c1FlexGrid1.Cols.Count; i++) c1FlexGrid1.Cols[i].StarWidth = "*";}

C#

c1DataFilter1.AutoGenerateFilters = false

Visual Basic

c1DataFilter1.AutoGenerateFilters = false;

C#

'カスタムフィルターの初期化:FlexChartFilterを作成し、DataFilterのFiltersコレクションに追加します

Visual Basic

  DataFilter for WinForms

47 Copyright © GrapeCity, Inc. All rights reserved.         

Page 49: DataFilter for WinForms - docs.grapecity.com · Step 2: Binding DataGridView to a data source 1. Open the DataGridView Tasks menu by clicking on the smart tag glyph on the upper-right

Run the application and observe how the data appearing in FlexGrid gets filtered based on the categoriesselected from the custom filter used in the DataFilter control.Now, you can change the filter values in the DataFilter UI and see how the FlexGrid renders the filtered data.

Back to Top

Dim categoryWiseSales = salesData.GroupBy(Function(s) s.Category).[Select](Function(grp) New With {Key .Category = grp.Key, Key .Amount = grp.Sum(Function(item) item.Amount) }) Dim categoryFilter = New FlexChartFilter(categoryWiseSales, "Category", "Amount") categoryFilter.HeaderText = "Category-wise Sales" categoryFilter.FlexChart.AxisX.LabelAngle = 45 c1DataFilter1.Filters.Add(categoryFilter)

//カスタムフィルターの初期化:FlexChartFilterを作成し、DataFilterのFiltersコレクションに追加しますvar categoryWiseSales = salesData.GroupBy(s => s.Category).Select(grp => new { Category = grp.Key, Amount = grp.Sum(item => item.Amount)});var categoryFilter = new FlexChartFilter(categoryWiseSales, "Category", "Amount");categoryFilter.HeaderText = "Category-wise Sales";categoryFilter.FlexChart.AxisX.LabelAngle = 45;c1DataFilter1.Filters.Add(categoryFilter);

C#

DataFilter for WinForms  

48 Copyright © GrapeCity, Inc. All rights reserved.