214
FlexGrid for WinForms 2021.08.27 更新 グレープシティ株式会社 グレープシティ株式会社

FlexGrid for WinForms

  • Upload
    others

  • View
    25

  • Download
    1

Embed Size (px)

Citation preview

Page 1: FlexGrid for WinForms

FlexGrid for WinForms20210827 更新

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

目次

FlexGrid for WinForms 4

主な特長 5-6

機能比較 7

FlexGrid の比較 7-9

WinFormsグリッドの比較 9-12

クイックスタート 13-19

設計時サポート 20

タスクメニュー 20-23

エディタ 23-26

データ 27

非連結モード 27

連結モード 27-30

連結モードでの操作 30-35

列 36

基本操作 36-39

ユーザー操作 40-45

エディタ 45-48

チェックボックス 48-50

数値 50-52

日付 52-56

コンボボックス 56-62

マスク 62-63

マップリスト 63-65

セルボタン 65-67

検証 67-70

データ注釈 70-72

スパークライン 72-73

ヘッダとフッタ 73-76

サイズ変更 76-78

行 79

基本操作 79-83

FlexGrid for WinForms

1 Copyright copy GrapeCity Inc All rights reserved

ユーザー操作 83-85

ヘッダ 85-88

行の詳細 88-93

サイズ変更 93-95

セル 96

基本操作 96-99

セルの書式設定 100-104

グリッド 105

基本操作 105-107

キーボードによる移動 107-109

パフォーマンスの向上 109-114

スクロールバー 115-116

選択 117-119

編集 120

編集モード 120-121

編集の無効化 121-122

並べ替え 123

並べ替えの操作 123-127

並べ替えのインジケータ 127

フィルタ 128

フィルタの操作 128-132

フィルタの種類 132-139

フィルタUI 139-141

検索 142-143

マージ 144

自動マージ 144-147

はみ出して表示されるセルの処理 147-149

カスタムのマージ 149-151

グループ 152-155

集計 156-159

ツリーグリッド 160-172

ノードの操作 172-179

データの操作 179-181

FlexGrid for WinForms

2 Copyright copy GrapeCity Inc All rights reserved

ツリーグリッドのカスタマイズ 181-188

クリップボード 189-192

保存ロードと印刷 193

保存 193-195

ロード 195-197

印刷 197-199

外観とスタイル設定 200

組み込みオプション 200-202

カスタムのスタイル 202-203

グリッドのカスタマイズ 203-204

境界線のカスタマイズ 204-206

テキストのカスタマイズ 206-208

カスタムのグリフ 209

永続的な状態 210-211

NET 5 リファレンス 212

NET 452 リファレンス 213

FlexGrid for WinForms

3 Copyright copy GrapeCity Inc All rights reserved

FlexGrid for WinForms

FlexGrid for WinForms is one of the fastest datagrids available in the market that renders and displays large data sets quicker than any other NET datagrid It is a powerfulgrid packed with basic as well as advanced features like in-cell editing sorting filtering merging grouping and much more Moreover it displays the hierarchical dataefficiently using tree grids with multiple columns aggregates subtotals and row details Not just this the control offers robust API and extensive design-time support sothat you can give your end-users a familiar Excel-like experience

The FlexGrid control binds with any of the NET data sources such as ADONET data source objects and custom business objects It also lets you work in the unbound modegiving you the power to manually add each row or column and set the cell values

One of the main strengths of FlexGrid is the ability to customize almost every aspect of appearance of the entire grid and individual cells In addition to standard formatstrings and cell styling FlexGrid goes above and beyond most NET datagrid components by providing complete control over the cell drawing using its OwnerDrawCell event

Besides the main C1FlexGrid control FlexGrid for WinForms also contains a C1FlexGridClassic control derived from C1FlexGrid It provides an object model that is virtuallyidentical to the VSFlexGrid ActiveX control and is mainly targeted for customers who want to migrate their existing VSFlexGrid projects from ActiveX to the latest technology

Not just this if you are developing your own custom grid control you can use C1FlexGridClassic as a reference The C1FlexGridClassic control is a perfect example of customgrid control created with C1FlexGrid control as base class We ship its source code as a product sample named Classic

Release Notes Product Samples

See the version-wise updates for all controls here Product samples are located at DocumentsComponentOne SamplesWinFormsvxxxC1FlexGridCS onyour system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

Documentation Blogs

Create your First Application with FlexGrid

FlexGrid at Design-time

Work with Columns and Editors

Filter Grid Data

Enable Merging in FlexGrid

Create Groups

Create a Tree Grid

Financial Data Displays using FlexGrid

FlexGrid Performance Compare WinForms WPF UWP

Creating Custom Styles for FlexGrid

Add Dynamic Grouping to your WinForms Data Grid

Implement responsive columns in a WinForms data grid

Creating a Derived Accordion Control with FlexGrid

Show RadioButton in a ComponentOne FlexGrid Tree

Videos Demo Samples

Meet FlexGrid WinForms and WPF Grid Demo

Note ComponentOne FlexGrid for WinForms is compatible with both NET 452 and NET 5

API Reference

C1WinFlexGrid452 Assembly C1WinFlexGrid5 Assembly

FlexGrid for WinForms

4 Copyright copy GrapeCity Inc All rights reserved

主な特長

Code-free Development

Why write code when a click is enough With rich design-time options beginning from binding to styling whichare accessible through the tasks menu and various editors FlexGrid lets you do a lot even without writing a single lineof code

Advanced Cell Editing

Choose from a variety of built-in editors or just create one for yourself FlexGrid offers various built-in cell editors sothat you can choose from simple text editing drop-down lists combo lists cell buttons masks and so on Not justthis with an option to create your own custom cell editors you can change your cells to accept or display almostany type of data

Work in Bound Mode or Unbound Mode

Bound grid or unbound populate the data seamlessly FlexGrid lets you bind the grid with any of the NET datasources such as ADONET and DataObjects for NET You can also work in unbound mode and let FlexGrid manage thedata itself

Present Hierarchical Data

View data the way that is best for you and your users When FlexGrid is bound to a hierarchical data source eachmaster record can be expanded or collapsed to show or hide the details in child grids which may contain moredetails The result is a data tree similar to the type of grid presented by Microsoft Access when displayinghierarchical data When bound the control detects subordinate data sources and creates additional instances of itselfto display child tables

Summarize Data and Show Aggregates

Get a quick outline of your grid data by summarizing it FlexGrid allows you to summarize data by adding a subtotalrow and display aggregates such as sum average count and so on for the specified column

Make it a Tree

Easily display your hierarchical data by converting your grid into a tree FlexGrid lets you represent your bound orunbound hierarchical data in Tree Grid which is similar to a TreeView control and gives a clean yet accessible structureto the data

Built-in Data Filtering

Let your users filter the data by value by condition or just give them both the options to choose from FlexGridprovides advanced built-in filtering with column filter value filter and condition filter already in place Still does notwork for you Create your own custom filter using rich FlexGrid API

Grouping

Group programmatically or at run-time With FlexGrid both are possible FlexGrid lets you group either through codeand even give your users an option to group at run-time using the FlexGridGroupPanel control or through contextmenu

Instant Search

Search the entire grid in one go and locate entries among millions of records instantly FlexGridprovides FlexGridSearchPanel control which lets the user type in the search box filters the records that match thetyped text and also highlights the search results

Merge Cells

Give your grid a tidy look by merging the cells with the same values FlexGrid lets you merge the contiguous cells withthe same values the way you want With free and restricted auto-merge options the grid can intelligently decidewhich cells to merge

Save and Load Multiple Formats

Back up the grid data or load it back in a jiffy FlexGrid lets you save the grid in your favorite format be it a text fileexcel file or XML You can even load content from these formats Not just this you can also load grid data from a

FlexGrid for WinForms

5 Copyright copy GrapeCity Inc All rights reserved

database using DataReader objects

Show Sparklines

Perk up your grid with the tiny charts FlexGrid allows you to add sparklines to grid columns so that you can easilydisplay trends and fluctuations in a single cell and make your grid data more useful and attractive at the same time

Perform Clipboard Operations

Move your text easily with Ctrl+C and Ctrl+V FlexGrid lets you perform clipboard operations on the grid data andheaders using your favorite keys

Assign Field Names to Columns

No need to remember the index of columns just call them by name FlexGrid automatically assigns column keysto field names when the grid is data-bound or you may assign them through code You can refer to a column using aColIndex(ColKey) syntax later which will retrieve the column you want even if your user has moved it to a differentposition on the grid

Use Data Annotations

Hint the user with data annotations FlexGrid lets you add data annotations in the form of metadata tags to theclasses and other objects to display messages and tips for the users

UI Automation and Support

Enable accessible and rich client applications through UI Automation (UIA) FlexGrid control supports UI Automationusing frameworks such as TestStackWhite You can enable applications such as screen readers coded UI testing toexamine user-interface elements and even simulated user interaction through code

Note UI Automation works only for the 452 version of C1FlexGrid and NET framework 47 or above applicationtarget frameworks

Add Special Drawing Effects

Make your grid look different and attractive with special drawing effects FlexGrid lets you paint special drawingeffects such as lines bitmaps and icons in the grid cells Additionally you can even scale images and addtransparency to them

Display Images in Cells

Need to display images in columns not an issue at all With FlexGrid you can display images along with data You caneven bind grid columns to image lists an easy and efficient way to display graphical information from data sources

Integrated Printing

Print the grid with a single statement FlexGrid gives you control over paper orientation margins header and footertext as well as the dialog boxes to set up the printer or see a preview You can even implement advanced printingoptions such as adding page breaks or custom elements to each page by using printing events

Styling

Use the visual styles or create your own custom styling use the designer or write your own code FlexGrid gives youenormous options to customize the appearance of the grid to match your requirements You can customize everyelement of the FlexGrid starting from headers and icons to borders and subtotal rows

FlexGrid for WinForms

6 Copyright copy GrapeCity Inc All rights reserved

機能比較

This section compares the features of various FlexGrids available across different platforms as well as shows acomparison with MS DataGridView

Topic Content

ComparingFlexGrids

Lists the difference between ActiveX version(VSFlexGrid control) and NET version of the FlexGridcontrol making it easy to migrate your grid from AciveX to NET

VSFlexGrid (ActiveX) and C1FlexGrid (NET)

ComparingWinForms Grids

Shows comparison between features of grids available in ComponentOne WinForms Edition andMS DataGridView

FlexGrid or True DBGridComparing ComponentOne Grids with MS DataGridView

FlexGrid の比較

VSFlexGrid (ActiveX) and C1FlexGrid (NET)ComponentOne provides ActiveX as well as NET version of the FlexGrid control While the ActiveX version is known asVSFlexGrid the NET version is shipped in the name of C1FlexGrid Being a NET version C1FlexGrid came laterinto the picture and instead of porting from the already existing VSFlexGrid we decided to create a brand new gridcontrol written from the ground up in C with the same design principles but with a new object model that is moremodern clean and powerful than the one in the ActiveX control

This section caters to original users of the VSFlexGrid control who want to migrate their applications from ActiveX tothe NET version that is the C1FlexGrid control To facilitate the hassle-free migration and a smooth learning curvethe NET version provides the C1FlexGridClassic control that derives from the C1FlexGrid class and provides an objectmodel that is virtually identical to the VSFlexGrid control The C1FlexGridClassic control is available in the form of aproduct sample Classic so that you may know exactly how to use the new object model This sample can also beused as a reference for creating the custom grid controls based on the C1FlexGrid class

Note The Classic sample is located at DocumentsComponentOne SamplesWinFormsv452C1FlexGridCS onyour system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

For users creating new applications we recommend using the new C1FlexGrid control However for the users who areporting their existing applications from ActiveX to NET we recommend using the C1FlexGridClassic control tominimize the programming effort Following table highlights some of the key differences between VSFlexGrid andC1FlexGrid

VSFlexGrid (ActiveX) C1FlexGrid (NET)

RowsCols1 Rows and Cols properties are used to

get or set the number of rows andcolumns

2 VSFlexGrid uses the TextMatrixproperty to represent the rows andcolumns

1 In C1FlexGrid Rows and Cols propertiesreturn the rows and column collectionsThe collections have readwriteproperties that return the number ofelements and fixed elements in eachcollection

FlexGrid for WinForms

7 Copyright copy GrapeCity Inc All rights reserved

For instance in ActiveX you would write

Dim r c c = 1

For r = c1FlexGrid1FixedRows To

c1FlexGrid1Rows - 1

DebugPrint

c1FlexGrid1TextMatrix(rc)

Next

2 C1FlexGrid uses indexers to representrows and columns

For instance in NET you would write

Dim r c c = 1

For r = c1FlexGrid1RowsFixed To

c1FlexGrid1RowsCount - 1

DebugPrint(c1FlexGrid1(r c))

Next

CellCell range The Cell property is one of the mostpowerful elements of the VSFlexGrid objectmodel It allows you to get or set anyproperty of any cell or cell range with asingle command Using a single propertymeans using variants and this prevents thecompiler from catching many subtleproblems in case you make mistakes whilecoding

For instance in ActiveX you would write

flexCell(flexcpPicture 5 5

10 10)

= theImage

In C1FlexGrid CellRange object has replacedthe Cell property to expose type-safeproperties and methods for accessing cellrange So if variable theImage contained astring instead of an image you get a compilererror and not a runtime error Also you getcommand-completion when writing the codebecause the types for each property are known

For instance in NET you would write

Dim rg As CellRange

rg =

c1FlexGrid1GetCellRange(551010)

rgImage = theImage

Typed Columns In the ActiveX version the ColDataTypeproperty allows you to set the type of datathat each column contains This informationis used mainly for sorting columns thatcontain dates or numbers

In the NET version Cols[i]DataType propertydetermines the type of data the column holdsBy default the DataType property for allcolumns is set to object that is you can storeany type of data in any column You can set thedata type to specific types however the gridtries to coerce any data stored in the grid tothe proper type

For instance in NET you would write

c1FlexGrid1Cols(2)DataType =

GetType(Integer)

Sets the value to 12

c1FlexGrid1(1 2) = 12

Can not convert hello string to

integer

Fires the GridError event

Retains the original value

c1FlexGrid1(2 2) = hello

Styles In VSFlexGrid you can customize theappearance of individual cells or cell rangesusing the Cell property

For instance in ActiveX you would write

Set the backcolor of second row

c1FlexGrid1Cell(flexcpBackColor

In C1FlexGrid cell appearance can becustomized using the CellStyle object

For instance in NET you would write

Create a cell style

Dim redStyle As CellStyle =

c1FlexGrid1Styles

FlexGrid for WinForms

8 Copyright copy GrapeCity Inc All rights reserved

2 0 2

c1FlexGrid1Cols-1) = vbRed

Demerit

To change the appearance of all red cellsyou need to clear all styles and start again oryou need to scan for red cells and thenchange their appearance

Add(Red)

redStyleBackColor = ColorRed

Set the backcolor of second row

c1FlexGrid1Rows(2)Style =

redStyle

Merit

The main advantage of this approach is that thenew style is an object that can be changed orassigned to new ranges For instance tochange the fore-color and text font of red cellsyou would write

c1FlexGrid1Styles(Red)ForeColor

= ColorWhite

c1FlexGrid1Styles(Red)Font =

new Font(Arial 9)

The VSFlexGrid control had many propertiesthat affected the way the grid was displayed(eg BackColor BackColorAlternateBackColorBkg BackColorFixedBackColorFrozen BackColorSel and so on)

The C1FlexGrid control replaces all theseproperties with a collection of CellStyle objectsso you can write something likeStylesFixedBackColor orStylesHighlightForeColor This makes theobject model simpler more consistent andmore powerful You can change the built-instyles or define your own and assign them torows columns or arbitrary cell ranges

WinFormsグリッドの比較

FlexGrid or True DBGridComponentOne offers two grid components in WinForms Edition FlexGrid and True DBGrid While both of these are robust and easy-to-usegrids allowing you to browse edit add delete and manipulate tabular data they still have their own strengths and capabilities

Both ComponentOne WinForms Edition grids can be used in bound as well as unbound mode but C1FlexGrid allows you to work more easilyin unbound mode With C1FlexGrid you can customize trees and make use of its cell merging capabilities FlexGrid is also apt for deriving acustomized grid

If you are planning to develop or migrate to NET 5 or higher it is recommended to use C1FlexGrid While we will continue to supportC1TrueDBGrid in NET 5 it no longer receives new enhancements and features like C1FlexGrid

Comparing ComponentOne Grids with MS DataGridViewThis section gives you a quick comparison between the two ComponentOne WinForms Edition grids and the standard MS DataGridViewavailable for WinForms platform For easy navigation we have broadly divided these features into different categories Click on thecorresponding category in the right hand pane or scroll down to know more about availability of a particular feature

Data Binding

Features FlexGrid TrueDBGrid MS DataGridView

Binding Data Sources

Binding Data Sources with hierarchical datarelations

With custom code

Unbound data storage and manipulations

Data Presentation

FlexGrid for WinForms

9 Copyright copy GrapeCity Inc All rights reserved

Features FlexGrid TrueDBGrid MS DataGridView

Hierarchical Styles With custom code

TreeView-like Styles

MultiLine Data View

Grouping

Built-in Drag And Drop

Horizontal and Vertical Interactive Splits

Child grids within master grid support

Drop-Down Objects Support

Drop-Down Multicolumn Object support

Drop-Down Multicolumn Bindable and SortableObject support

Data Exchange

Features FlexGrid TrueDBGrid MS DataGridView

Export Data (Delimited Text XLS and XLSX)

Export Data in other formats (PDF HTML RTFJPG and other)

Load data from Excel files

Enhanced Printing data from grid and PrintPreview support

Cell Manipulations

Features FlexGrid TrueDBGrid MS DataGridView

In-Cell Objects

Enhanced Cell Editing with Custom Editors

Merging Cells and Rows

Customize Cells Merging

Drag And Drop Columns and rows

Automatic Cell Sizing

Fixed Non-scrolling Columns

Excel-style Cell Selection

Customize each Cell Rendering

Zooming Cells

Run-Time CellTips

Data Manipulations with Cell Ranges

Layout and Styling

Features FlexGrid TrueDBGrid MS DataGridView

Visual Styles Support

Dynamic Support of 38 Decoration Themes

Office 2007 and 2010 Styling

Alternating Row Colors

Customizable Cell Border Style

FlexGrid for WinForms

10 Copyright copy GrapeCity Inc All rights reserved

Add Special Drawing Effects

Data-Sensitive Display

Input and Navigation

Features FlexGrid TrueDBGrid MS DataGridView

Input Masking

Simplify Data Input

Automatic Data Translation

Spell Checking support

Customizable Keyboard Navigation and keysbehavior

Right-To-Left navigation

Touch Support

Clipboard support

Rich Scrolling Capabilities

Data Manipulations

Features FlexGrid TrueDBGrid MS DataGridView

Sorting

Multi-column Sorting

Built-in Data Filtering

Extended and Conditional Filtering

Customizable filter form

Additional Filter Bar row

Multi-language Filtering

AutoSearch

Range Aggregates

Localization

Features FlexGrid TrueDBGrid MS DataGridView

Right-To-Left support

Net localization support

Regional settings support

Other Features

Features FlexGrid TrueDBGrid MS DataGridView

Optimize performance for displaying largeamount of data in bound and unbound mode

Just-In-Time Data Loading

Server-side Data Virtualization withC1DataSource

Automatic Lookup Columns with C1DataSource

Design-time extended support

Assembly size 1508 K 2108 K Part of

FlexGrid for WinForms

11 Copyright copy GrapeCity Inc All rights reserved

SystemWindowsForms

FlexGrid for WinForms

12 Copyright copy GrapeCity Inc All rights reserved

クイックスタート

This quick start will guide you through the steps of creating a simple grid application using the FlexGrid control Follow thesteps below to get started

FlexGrid for WinForms

13 Copyright copy GrapeCity Inc All rights reserved

This section demonstrates how to create a FlexGrid application in NET 452 by binding it to an externaldatasource You can also create a class to supply data to the grid as shown in the NET 5 tab Similarly you can usebelow steps to bind FlexGrid to a datasource in NET 5 However note that some design-time steps may vary in caseof NET 5

Set Up the Application1 Create a new Windows Forms app(NET Framework)2 Configure your project and set the Framework property3 Drag and drop the FlexGrid control from the Visual Studio toolbox onto the form

Observe An empty grid is added to the form at design time

Bind FlexGrid to a Data SourceThere are two ways to bind data with the FlexGrid control either choose to bind at design time or through code atrun time

Binding at Design Time

1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Click the Choose Data Source drop down button and select Add Project Data Source option to open the

Data Source Configuration Wizard3 On Choose a Data Source Type page select Database and click Next4 On Choose a Database Model page select Dataset and click Next5 On Choose Your Data Connection page click New Connection to open the Add Connection dialog6 Against the DataSource field click Change button to open the Change Data Source dialog7 Select Microsoft Access Database File and click OK to return to the Add Connection dialog8 Against the Database file name field click Browse and navigate to the database file Provide the User name

and Password if required to connect to the database file This example uses C1NWindmdb file located atthe following location by defaultDocumentsComponentOne SamplesCommon

9 Click Test Connection to make sure that you have successfully connected to the database or server and clickOK

NET 452

FlexGrid for WinForms

14 Copyright copy GrapeCity Inc All rights reserved

10 Click OK again to close the Add Connection dialog box11 Click Next 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 Choose the appropriate option as per your requirement12 Save the connection string in the application configuration file by checking the Yes save the connection as

box and entering a name13 Click Next to switch to the Choose Your Database Objects page14 Choose a table say Products from the Tables node and click Finish15 The above steps add a dataset and connection string to your project Also Visual Studio automatically creates

the following code to fill the datasetC

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて

移動または削除できます

thisproductsTableAdapterFill(thisc1NWindDataSetProducts)

VBNET

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移

動または削除できます

MeProductsTableAdapterFill(Mec1NWindDataSetProducts)

Binding at Run Time

To bind the grid through code first we need to create a database connection string Then use an object of dataadapter (in this case OleDbDataAdapter) to create a query to fetch products from the data table and fill it in thedata table which is assigned to the DataSource property of C1FlexGrid class

C

グリッドをデータソースに連結します

string conn = GetConnectionString()OleDbDataAdapter da = new OleDbDataAdapter(select from products conn)DataTable dt = new DataTable(Products)daFill(dt)c1FlexGrid1DataSource = dt

VBNET

グリッドをデータソースに連結します

Dim conn As String = GetConnectionString()Dim da As OleDbDataAdapter = New OleDbDataAdapter(select from products conn)Dim dt As DataTable = New DataTable(Products)daFill(dt)c1FlexGrid1DataSource = dt

Note that the above sample code uses a custom method named GetConnectionString to create a connection stringwith database

C

static string GetConnectionString() string path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) + ComponentOne SamplesCommon string conn = provider=microsoftjetoledb40data source=0c1nwindmdb return stringFormat(conn path)

VBNET

Private Shared Function GetConnectionString() As String Dim path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) amp

FlexGrid for WinForms

15 Copyright copy GrapeCity Inc All rights reserved

ComponentOne SamplesCommon Dim conn = provider=microsoftjetoledb40data source=0c1nwindmdb Return StringFormat(conn path)End Function

Configure the FlexGrid controlThis section walks you through the design-time and run-time steps to configure the grid with some basic settingsThese settings and features are explained in detail in the topics below

Configuring Grid at Design Time

Click smart tag to open the C1FlexGrid Tasks MenuClick the Styles option to open C1FlexGrid Styles EditorSelect Fixed from Built-in Styles pane customize some settings such as Backcolor Font and ForeColor andclick OKTo fit the grid to the form click the Dock in Parent Container optionFor customizing a column click the column (say Unit Price column) to open C1FlexGrid Column TasksMenuClick the ellipsis alongside Format field to open the Format String dialogSelect Currency as Format Type and click OK

Configuring Grid at Run Time

Add following code to configure the grid and its columns at run time

C

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = new Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols[6]Format = c

VBNET

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = New Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols(6)Format = c

FlexGrid for WinForms

16 Copyright copy GrapeCity Inc All rights reserved

This section demonstrates how to create a FlexGrid application in NET 5 by populating its data from a custom classYou can also use an external datasource to supply data to the grid as shown in NET 452 tab However note thatsome design-time steps given in the aforementioned tab may vary in case of NET 5 Similarly you can use belowsteps to bind FlexGrid to an internal datasource in NET 452

Set Up the Application1 Create a new Windows Forms app(NET Framework)2 Configure your project and set the Framework property3 Initialize the FlexGrid control and add it to the form

C

コントロールを初期化します

C1FlexGrid flexGrid = new C1FlexGrid() フォームにコントロールを追加します

thisControlsAdd(flexGrid)

VBNET

コントロールを初期化します

Dim flexGrid As C1FlexGrid = New C1FlexGrid() フォームにコントロールを追加します

MeControlsAdd(flexGrid)

Bind FlexGrid to a Data Source1 Create a custom class Product to be used as a data source

C

カスタムクラスProductを作成します

public class Product static Random _rnd = new Random()

NET 5

FlexGrid for WinForms

17 Copyright copy GrapeCity Inc All rights reserved

static string[] _names = Macko|Surfair|Pocohey|StudebySplit(|) static string[] _lines = Computers|Washers|Stoves|CarsSplit(|) static string[] _colors = Red|Green|Blue|WhiteSplit(|) public Product() Name = _names[_rndNext() _namesLength] Line = _lines[_rndNext() _linesLength] Color = _colors[_rndNext() _colorsLength] Price = 30 + _rndNextDouble() 1000 Cost = 3 + _rndNextDouble() 300 Discontinued = _rndNextDouble() lt 2 Introduced = DateTimeTodayAddDays(_rndNext(-600 0)) public string Name get set public string Color get set public string Line get set public double Price get set public double Cost get set public DateTime Introduced get set public bool Discontinued get set

VBNET

カスタムクラスProductを作成します

Public Class Product Private Shared _rnd As Random = New Random() Private Shared _names As String() = Macko|Surfair|Pocohey|StudebySplit(|c) Private Shared _lines As String() = Computers|Washers|Stoves|CarsSplit(|c) Private Shared _colors As String() = Red|Green|Blue|WhiteSplit(|c)

Public Sub New() Name = _names(_rnd[Next]() Mod _namesLength) Line = _lines(_rnd[Next]() Mod _linesLength) Color = _colors(_rnd[Next]() Mod _colorsLength) Price = 30 + _rndNextDouble() 1000 Cost = 3 + _rndNextDouble() 300 Discontinued = _rndNextDouble() lt 2 Introduced = DateTodayAddDays(_rnd[Next](-600 0)) End Sub

Public Property Name As String Public Property Color As String Public Property Line As String Public Property Price As Double Public Property Cost As Double Public Property Introduced As Date Public Property Discontinued As BooleanEnd Class

2 Initialize a list of type ProductC

Productがクラス型であるProduct型のリストを初期化します

ListltProductgt _products = new ListltProductgt()

FlexGrid for WinForms

18 Copyright copy GrapeCity Inc All rights reserved

VBNET

Productがクラス型であるProduct型のリストを初期化します

Dim _products As List(Of Product) = New List(Of Product)()

3 Initialize a For loop and add products to the list

C

forループを初期化し製品をリストに追加します

for (int i = 0 i lt100 i++) _productsAdd(new Product())

VBNET

forループを初期化し製品をリストに追加します

For i As Integer = 0 To 100 - 1 _productsAdd(New Product())Next

4 Bind FlexGrid to the created data sourceC

FlexGridにデータを連結します flexGridDataSource = _products

VBNET

FlexGridにデータを連結します flexGridDataSource = _products

Configure the FlexGrid controlAdd following code to configure the grid and its columns at run time

C

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = new Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols[6]Format = c

VBNET

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = New Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols(6)Format = c

FlexGrid for WinForms

19 Copyright copy GrapeCity Inc All rights reserved

設計時サポート

FlexGrid for WinForms comes with various design time options to make your programming tasks a lot easier In addition to smart tag context menu andproperty grid FlexGrid provides tasks menus and editors as well While C1FlexGrid Tasks menu lets you work on the entire grid in design time the ColumnTasks menu provides options to set some common properties for each column of the grid At the same time various editors such as C1FlexGrid ColumnEditor and C1FlexGrid Style Editor provide detailed properties to customize the columns and styles

This section discusses about various design-time options available in the FlexGrid control

Topic Snapshot Content

Tasks Menus Discusses about the C1FlexGrid Tasks menu the Column Tasks menu and their options

C1FlexGrid Tasks MenuC1FlexGrid Column Tasks Menu

Editors Discusses about the various editors and how to access them

C1FlexGrid Column EditorC1FlexGrid Style EditorCaption Style EditorColumn Style Editor

タスクメニュー

C1FlexGrid Tasks MenuC1FlexGrid Tasks menu provides you an easy access to the commonly used properties of FlexGrid It also providesoptions to open various editors such as C1FlexGrid Column Editor C1FlexGrid Style Editor

To access the C1FlexGrid Tasks menu click the smart tag ( ) in the upper right corner of the grid Following tableexplains various options available through the C1FlexGrid Tasks menu

Option Description

ChooseDataSource

The dropdown opens the list of available data sourcesand gives you Add Project Data Source option to openData Source Configuration Wizard

For more information on how to add a new data sourceto the project see Bound Mode

EnableAddingRows

The checkbox toggles the AllowAddNew propertywhich allows users to add new row to the grid at runtime When checked ON it displays a template row withstar at the bottom of the grid to enter the new record

EnableDeletingRows

The checkbox toggles the AllowDelete property whichallows users to delete the selected rows by pressing theDelete key

EnableEditing

The checkbox toggles the AllowEditing property whichallows users to edit the grid

Enable Column Reordering The checkbox sets the AllowDragging property toColumns which allows users to re-order the columns by draggingthe column headers

Enable Column Filtering The checkbox toggles the FlexGridAllowFiltering property to

FlexGrid for WinForms

20 Copyright copy GrapeCity Inc All rights reserved

enable or disable the filtering on grid columns

VisualStyle The dropdown lets you choose the built-in visual styles availablein the grid By default the value is set to Custom

Designer The option opens C1FlexGrid Column Editor which allows you toset the properties of each column of the grid

Styles The option opens C1FlexGrid Style Editor which allows youto customize the various pre-defined styles or create the newstyles at design time

Display Hidden Columns The checkbox lets you display or hide grid columns in the designview Note that this option is NOT associated with the run-timevisibility of columns Hence even if this checkbox is checked ONcolumns with Visible property set to False still remain hiddenwhen the application is run

Column Tasks The option switches the task menu to C1FlexGrid Column Tasksmenu which provides options to set the properties for theselected column

About C1FlexGrid The option displays a dialog box displaying the information suchas version of the FlexGrid control

Dock in Parent Container This option sets the Dock property of the grid to Fill which resizesthe grid to occupy the whole form space Clicking the option alsoswitches the text and provides option to Undock in ParentContainer which restores the grid to its original size

C1FlexGrid Column Tasks MenuC1FlexGrid Column Tasks menu provides you an easy access to the commonly used properties of grid columns Italso provides options to open editors named Caption Style and Column Style

To access the C1FlexGrid Column Tasks menu double-click header of the column to be configured at design-timeAnother way to open C1FlexGrid Column Tasks menu is to click on the smart tag ( ) in the upper right corner of thegrid and then navigate to the Column Tasks option Following table explains various options available through theC1FlexGrid Column Tasks menu

FlexGrid for WinForms

21 Copyright copy GrapeCity Inc All rights reserved

Option Description

ColumnCaption

The field allows you to specify the value of Captionproperty which sets text in header cell of the column

DataField

The dropdown opens a list of available fields in the datasource to choose from and sets value of Name property ofthe column

DataType

The dropdown opens a list of available data types and letsyou set the data type of the selected column This fieldcorresponds to the DataType property of the column

EditMask

The field lets you specify value of EditMask property whichsets mask for the selected column The ellipsis button onthe right side of the field opens the Input Mask dialog boxwhere you can select from the list of pre-defined masks

FormatString

The field lets you specify the value of Format propertywhich sets format string to display data value from source

ComboList

The field lets you specify the list of multiple values fromwhich user can choose The ellipsis button on the right sideof the field lets you open the Combo List dialog box whereyou can specify the value options

Allow Sorting The checkbox toggles the AllowSorting property to enable ordisable sorting in the column By default sorting is enabled for allcolumns

Allow Editing The checkbox toggles the AllowEditing property to make thecolumn read-only or editable By default editing is enabled for allcolumns

Allow Resizing The checkbox toggles the AllowResizing property which allows usersto adjust the size of column at run time By default resizing isenabled for all columns

Allow Dragging The checkbox toggles the AllowDragging property to enable ordisable re-ordering of the column at run time By default dragging isenabled for all columns

Allow Merging The checkbox toggles the AllowMerging property to enable ordisable merging two adjacent column cells having same values Bydefault merging is disabled for all columns

Allow Filtering The dropdown lets you specify the value of ColumnAllowFilteringproperty and choose the type of filter for each column The availableoptions are Default ByValue ByCondition Custom or None

Visible The checkbox lets you set the visibility of the column in the grid atrun time by toggling value of its Visible property

FlexGrid for WinForms

22 Copyright copy GrapeCity Inc All rights reserved

Caption Style The option opens the Caption Style editor which gives you options tostyle the text alignment background and border for the header cellof column

Column Style The option opens the Column Style editor which gives you options tostyle the text alignment background and border for the column text

C1FlexGrid Tasks The option switches the task menu to C1FlexGrid Tasks menu whichprovides options to set the properties for the entire grid

Dock in Parent Container The option sets the Dock property of the grid to Fill which resizes thegrid to occupy the whole form Clicking the option also switches thetext and provides option to Undock in Parent Container whichrestores the grid to its original size by setting the Dock property toNone

エディタ

Apart from the tasks menu FlexGrid also provides various editors that help you set a number of properties related togrid its columns and their styles

C1FlexGrid Column EditorFlexGrid provides the C1FlexGrid Column Editor making it easy to work with columns at design-time instead ofwriting code The editor lets you set various properties related to columns such as Caption DataTypeAllowFiltering and AllowMerging through its property pane on left hand side Toolbar on the top of this editorgives you options such as reloading data from the data source adding removing and resizing columns You can evenstyle the column text using the options given in this toolbar For further customization of column text you can usethe Column Style editor to access more specific properties

FlexGrid for WinForms

23 Copyright copy GrapeCity Inc All rights reserved

There are three ways in which you can access the C1FlexGrid Column Editor at design time

Smart Tag Click the smart tag ( ) in the upper right corner of the grid and select Designer from theC1FlexGrid Tasks menuProperty Window Select the grid go to the Properties window and click the ellipsis button (hellip) next to theCols propertyContext Menu Right-click the grid and select Designer from the context menu

C1FlexGrid Style EditorFlexGrid provides the C1FlexGrid Style editor which lets you style the grid at design time by customizing the built-instyles and creating the new ones The editor offers a list of styles for specific types of cell on left hand side and aproperty window on right hand side to customize these styles The list of styles is divided into two sections thedefault Built-in Styles and Custom Styles Towards the bottom there are Add and Remove buttons to add anddelete the custom styles and a Clear button to revert the editor to default settings The AutoFormat button in theend opens a secondary dialog C1FlexGrid Auto Format which lists the pre-defined set of styles and also shows apreview in the Preview pane

FlexGrid for WinForms

24 Copyright copy GrapeCity Inc All rights reserved

There are three ways in which you can access the C1FlexGrid Style Editor at design-time

Smart Tag Click the smart tag ( ) in the upper right corner of the grid and select Styles from theC1FlexGrid Tasks menuProperty Window Select the grid go to the Properties window and click the ellipsis button (hellip) next to theStyles propertyContext Menu Right-click the grid and select Styles from the context menu

Caption Style EditorFlexGrid provides the Caption Style editor which allows you to set styling related properties of the column header celland its text The editor comprises of four tabs Text Alignment Border and Background for customizing variousaspects of the header cells

To access the Caption Style editor click smart tag ( ) click the C1FlexGrid Column Tasks option on the task menu toopen column tasks and then go to Caption Style option

FlexGrid for WinForms

25 Copyright copy GrapeCity Inc All rights reserved

Column Style EditorSimilar to Caption Style editor FlexGrid provides another editor the Column Style editor for styling the column textThe editor has got the same options as that of Caption Style editor The only difference is that Caption Style editorcustomizes the column header text while this editor works on the general text in the column cells

To access the Column Style editor click smart tag ( ) click the C1FlexGrid Column Tasks option on the task menu toopen column tasks and then go to Column Style option

FlexGrid for WinForms

26 Copyright copy GrapeCity Inc All rights reserved

データ

This section discusses about various ways to populate data in the FlexGrid control

Topic Snapshot Content

Unbound Mode Discusses how to populate data in the unbound grid

Bound Mode Discusses ways of populating data in the grid through data binding and various operations on bound grid

Binding at design timeBinding at run time using DataSource propertyBinding at run time using SetDataBinding methodOperations in Bound Mode

非連結モード

As the name suggests in unbound mode grid is not bound to any data source and data is stored in the control itselfIn this case you need to provide data by adding rows and columns either at design time or programmatically throughrow and column collections You can also create an empty grid to let user enter the data

An unbound grid is not a very common scenario as grid does not store the data and hence user needs to manage itmanually However unbound grids suits better to some business scenarios like creation and maintenance of recordsFor instance you can use the grid in unbound mode for recording the date-wise sales data or to maintain the dailyinventory changes Below example demonstrates a grid with data populated through code

In C1FlexGrid you can add empty rows or columns by setting the Count property of row or column objects Also youcan use the Add method of these collections to add the empty rows and columns to a grid To set data in the cellsyou can either use the familiar index notation(Item property) or the SetData method For more information on settingdata in the cells see Storing and Retrieving Data

Use the code below to populate data in unbound FlexGrid for WinForms

連結されていない列を追加しますColumn col = _flexColsAdd()colName = colCaption = Unbound_flex[1 Unbound] = 123

C

連結されていない列を追加しますDim col As Column = C1FlexGrid1ColsAdd()colName = UnboundcolCaption = Unbound

VBNET

FlexGrid for WinForms

27 Copyright copy GrapeCity Inc All rights reserved

連結モード

Bound mode as the name suggests refers to a state where grid fetches its data from an underlying data source Databinding also allows multiple data consumers to be connected to a data provider in the synchronized manner

FlexGrid supports data binding to most of the commonly used data sources such as ObservableCollection IListltTgtListltTgt Array BindingSource ADONET objects such as DataSet DataTable etc

There are three ways of binding FlexGrid to a data source

Binding at design timeBinding at run time using DataSource propertyBinding at run time using SetDataBinding method

Binding at Design Time1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Click the Choose Data Source drop down button and select Add Project Data Source option to open the

Data Source Configuration Wizard3 On Choose a Data Source Type page select Database and click Next4 On Choose a Database Model page select Dataset and click Next5 On Choose Your Data Connection page click New Connection to open the Add Connection dialog6 Against the DataSource field click Change button to open the Change Data Source dialog7 Select Microsoft Access Database File and click OK to return to the Add Connection dialog8 Against the Database file name field click Browse and navigate to the database file Provide the User name

and Password if required to connect to the database file This example uses C1NWindmdb file located at thefollowing location by defaultDocumentsComponentOne SamplesCommon

FlexGrid for WinForms

28 Copyright copy GrapeCity Inc All rights reserved

9 Click Test Connection to make sure that you have successfully connected to the database or server and clickOK

10 Click OK again to close the Add Connection dialog box11 Click Next 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 Choose the appropriate option as per your requirement12 Save the connection string in the application configuration file by checking the Yes save the connection as

box and entering a name13 Click Next to switch to the Choose Your Database Objects page14 Choose a table say Products from the Tables node and click Finish15 The above steps add a dataset and connection string to your project Also Visual Studio automatically creates

the following code to fill the dataset

Binding at Run Time Using DataSource PropertyFlexGrid provides the DataSource property to bind the FlexGrid control to a data source at run time You need toassign a data source object to the DataSource property of FlexGrid If the data source object contains more than onetable you can set the DataMember property to table name to specify the target table

Following code uses DataSource property to bind data to the WinForms FlexGrid

Note that the above sample code uses a custom method named GetData to supply data You can set up the datasource as per your requirements Following code shows an example of creating data for WinForms FlexGrid

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移動または削除できます thisproductsTableAdapterFill(thisc1NWindDataSetProducts)

C

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移動または削除できます MeProductsTableAdapterFill(Mec1NWindDataSetProducts)

VBNET

c1FlexGrid1BeginUpdate()C1DataCollectionltCustomergt c1DataCollection = new C1DataCollectionltCustomergt(GetData())c1FlexGrid1DataSource = new C1DataCollectionBindingList(c1DataCollection)c1FlexGrid1EndUpdate()

C

c1FlexGrid1BeginUpdate()Dim c1CollectionView As C1DataCollectionC1DataCollection(Of Customer) = New C1DataCollectionC1DataCollection(Of Customer)(GetData())c1FlexGrid1DataSource = New C1DataCollectionBindingListC1DataCollectionBindingList(c1CollectionView)c1FlexGrid1EndUpdate()

VBNET

ObservableCollectionltCustomergt GetData() var data = new ObservableCollectionltCustomergt() for (int i = 0 i lt 25 i++)

C

FlexGrid for WinForms

29 Copyright copy GrapeCity Inc All rights reserved

Binding at Run Time Using SetDataBinding MethodFlexGrid also provides the SetDataBinding method using which you can set DataSource and DataMember propertiesboth using a single call The following code demonstrates an example of rendering a parent table and its child tablesin different grids with the help of the SetDataBinding method

Below code demonstrates how to bind data to WinForms FlexGrid using SetDataBinding method

dataAdd(new Customer()) return data

Private Function GetData() As ObservableCollection(Of Customer) Dim data = New ObservableCollection(Of Customer)()

For i = 0 To 25 - 1 dataAdd(New Customer()) Next

Return dataEnd Function

VBNET

グリッドにデータセットを連結します_flexCustomersBeginUpdate()_flexCustomersSetDataBinding(ds Customers)_flexCustomersEndUpdate()

_flexOrdersBeginUpdate()_flexOrdersSetDataBinding(ds CustomersCustomerOrders)_flexOrdersEndUpdate()

_flexOrderDetailsBeginUpdate()_flexOrderDetailsSetDataBinding(ds CustomersCustomerOrdersOrderDetails)_flexOrderDetailsEndUpdate()

C

グリッドにデータセットを連結します_flexCustomersBeginUpdate()_flexCustomersSetDataBinding(ds Customers)_flexCustomersEndUpdate() _flexOrdersBeginUpdate()_flexOrdersSetDataBinding(ds CustomersCustomerOrders)_flexOrdersEndUpdate() _flexOrderDetailsBeginUpdate()_flexOrderDetailsSetDataBinding(ds CustomersCustomerOrdersOrderDetails)_flexOrderDetailsEndUpdate()

VBNET

連結モードでの操作

Adding Unbound Column in Bound ModeIn the bound mode grid fetches the data from data source and display it as records and bound columns To add a column to

FlexGrid for WinForms

30 Copyright copy GrapeCity Inc All rights reserved

display data that does not exist in the data source you need to add unbound columns at design time or through code

Adding unbound column at design time

1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Bind the grid control with a data source For detailed steps about how to bind FlexGrid to a data source see Bound

Mode3 Click the Designer option to open the C1FlexGrid Column Editor4 In the right hand side pane select an existing column from the grid preview5 Click Insert Column options in the toolbar to add a column before or after the selection

Adding unbound column through code

FlexGrid provides Add Insert and InsertRange method of the ColumnCollection class to add an unbound column to the gridWhile Add method adds a column at the end the Insert method lets you specify the position where you want to add a newcolumn Similarly you can add multiple columns at a specified position by using the InsertRange method

Use the code below to add unbound column in a bound WinForms FlexGrid

連結されていない列を追加しますColumn col = _flexColsAdd()colName = colCaption = Unbound_flex[1 Unbound] = 123

C

連結されていない列を追加しますDim col As Column = C1FlexGrid1ColsAdd()colName = UnboundcolCaption = Unbound

VBNET

FlexGrid for WinForms

31 Copyright copy GrapeCity Inc All rights reserved

Set Values in Unbound ColumnTo define values in the unbound column of bound grid you need to usethe SetUnboundValue and GetUnboundValue events of the C1FlexGrid class First create a hash table to store the enteredvalues then use the SetUnboundValue event to set unbound value in the hash table using a unique key to identify therecord and use GetUnboundValue event to get the value stored in the hash table using its unique key and set unboundvalue to be displayed in the cell

Following code shows how to set values in an unbound column added to a bound WinForms FlexGrid

Displaying Data in Fixed ColumnTo set values in the fixed columns you need to set DrawMode property of the C1FlexGrid class to OwnerDraw in the formload event and then create the OwnerDrawCell event to set values in the fixed column cells In this example we are settingrow numbers in the fixed column of a bound WinForms FlexGrid

get value from hashtable using ProductID as keyvoid _flex_GetUnboundValue(object sender C1WinC1FlexGridUnboundValueEventArgs e) DataRowView drv = (DataRowView)_flexRows[eRow]DataSource eValue = _hash[drv[ProductID]]

store value in hashtable using ProductID as keyvoid _flex_SetUnboundValue(object sender C1WinC1FlexGridUnboundValueEventArgs e) DataRowView drv = (DataRowView)_flexRows[eRow]DataSource _hash[drv[ProductID]] = eValue

C

Private Sub C1FlexGrid1_GetUnboundValue(sender As Object e As C1WinC1FlexGridUnboundValueEventArgs) Handles C1FlexGrid1GetUnboundValue Dim drv As DataRowView = DirectCast(C1FlexGrid1Rows(eRow)DataSource DataRowView) eValue = _hash(drv(ProductID))End Sub

Private Sub C1FlexGrid1_SetUnboundValue(sender As Object e As C1WinC1FlexGridUnboundValueEventArgs) Handles C1FlexGrid1SetUnboundValue Dim drv As DataRowView = DirectCast(C1FlexGrid1Rows(eRow)DataSource DataRowView) _hash(drv(ProductID)) = eValueEnd Sub

VBNET

FlexGrid for WinForms

32 Copyright copy GrapeCity Inc All rights reserved

Auto-adjust Column WidthFlexGrid provides AutoResize property of the C1FlexGrid class to adjust the width of columns automatically according tothe text length You need to set the property to true before binding it to the data source to load the grid with appropriatecolumn width You can also call AutoSizeCol method to adjust the width of the specified column

Use the code below auto-adjust the column width according to the text in WinForms FlexGrid

Display Bitmap Image in FieldIn most of the scenarios grid directly fetches the images from the data source However if the grid is bound to a databasewhich stores images as OLE objects such as Microsoft Access a little bit of extra processing is required to fetch bitmapimages In such case you need to convert the image data stored as byte array to a memory stream and then usethe OwnerDrawCell event to load the image In the form load event you need to set the DrawMode property toOwnerDraw Also adjust the height of row to display the image properly

Following code demonstrates how to display bitmap image in fields of WinForms FlexGrid

private void C1FlexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if ((eRow gt= thisc1FlexGrid1RowsFixed) amp (eCol == (thisc1FlexGrid1ColsFixed - 1))) eText = eRowToString() または任意のテキスト

C

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If eRow gt= Mec1FlexGrid1RowsFixed And eCol Is Mec1FlexGrid1ColsFixed - 1 Then eText = eRowToString() または任意のテキスト End IfEnd Sub

VBNET

すべての列の幅を自動的に調整します c1FlexGrid1AutoResize = true

4列目の幅を自動調整します c1FlexGrid1AutoSizeColumns(3)

C

すべての列の幅を自動的に調整します c1FlexGrid1AutoResize = True

4列目の幅を自動調整します c1FlexGrid1AutoSizeColumns(3)

VBNET

private void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) if(eMeasuring ampamp eRowgt=c1FlexGrid1RowsFixed ampamp eCol gt=

C

FlexGrid for WinForms

33 Copyright copy GrapeCity Inc All rights reserved

Note that the above sample code uses a custom method LoadImage method to convert the images from byte array to amemory stream

c1FlexGrid1ColsFixed) 「Photo」はblob(byte [])に保存された画像です if (c1FlexGrid1Cols[eCol]Name == Picture) mdbからロードしてみてください eImage = LoadImage(c1FlexGrid1[eRow eCol] as byte[])

画像が表示された場合はテキストを入力しないでください if (eImage = null) eText = null

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) If Not eMeasuring AndAlso eRow gt= c1FlexGrid1RowsFixed AndAlso eCol gt= c1FlexGrid1ColsFixed Then

「Photo」はblob(byte [])に保存された画像です If c1FlexGrid1Cols(eCol)Name Is Picture Then mdbからロードしてみてください eImage = LoadImage(TryCast(c1FlexGrid1(eRow eCol) Byte()))

画像が表示された場合はテキストを入力しないでください If eImage IsNot Nothing Then eText = Nothing End If End IfEnd Sub

VBNET

Image LoadImage(byte[] picData) static Image LoadImage(byte[] picData) これが埋め込みオブジェクトであることを確認してください const int bmData = 78 if (picData == null || picDataLength lt bmData + 2) return null if (picData[0] = 0x15 || picData[1] = 0x1c) return null

現在点ではビットマップのみを処理します if (picData[bmData] = B || picData[bmData + 1] = M) return null

画像をロードします Image img = null try MemoryStream ms = new MemoryStream(picData bmData picDataLength - bmData) img = ImageFromStream(ms) catch

画像を返します return img

C

Private Function LoadImageMethod(ByVal picData As Byte()) As Image

VBNET

FlexGrid for WinForms

34 Copyright copy GrapeCity Inc All rights reserved

Private Shared Function LoadImage(ByVal picData As Byte()) As Image これが埋め込みオブジェクトであることを確認してください Const bmData As Integer = 78 If picData Is Nothing OrElse picDataLength lt bmData + 2 Then Return Nothing If picData(0) ltgt ampH15 OrElse picData(1) ltgt ampH1c Then Return Nothing

現在点ではビットマップのみを処理します If picData(bmData) ltgt Bc OrElse picData(bmData + 1) ltgt Mc Then Return Nothing

画像をロードします Dim img As Image = Nothing

Try Dim ms As MemoryStream = New MemoryStream(picData bmData picDataLength - bmData) img = ImageFromStream(ms) Catch End Try

画像を返します Return imgEnd Function

FlexGrid for WinForms

35 Copyright copy GrapeCity Inc All rights reserved

A grid control is a collection of rows and columns Columns generally contain a particular type of information through out while rows are used to recorddifferent types of information about a particular item

In FlexGrid the collection of columns is represented by the ColumnCollection class which can be accessed through Cols property of the C1FlexGrid class Thissection discusses the various operations that can be performed on columns

Topic Snapshot Content

BasicOperations

Discusses about how to perform basic column operations

Set Column CountAdd ColumnDelete ColumnInsert ColumnSet Data TypeSet Fixed ColumnSet Frozen Column

UserInteraction

Discusses about operations that can be performed by the end user at run time

Allow EditingAllow DraggingAllow FreezingAllow SortingAllow FilteringAllow Resizing

Editors Discusses about various built-in editors of FlexGrid and operations related to them Also discusses how to use customeditors in the FlexGrid

CheckBoxNumericDateComboBoxMaskMapped ListCell Button

Validation Discusses how to apply validation and show error information on FlexGrid cells

Sparkline Discusses about how to display Sparkline charts in FlexGrid cells

Header andFooter

Discusses about how to set column header and footer

Set Header TextMerge column headerWrap column header textStyle Column HeaderSet Column Footer

Sizing Discusses about various aspects of column sizing

Set Column WidthAuto-adjust Column WidthSet MinMax Column WidthStar Sizing

基本操作

This topic discusses various basic operations which can be performed on a column

FlexGrid for WinForms

36 Copyright copy GrapeCity Inc All rights reserved

Set Column CountWhen grid is bound to a data source the number of columns is determined by the number of fields available in thedata source However in the case of unbound mode you can set any arbitrary value in the Count property ofthe ColumnCollection class to set the number of columns to be displayed in the grid

Use the code below to set the number of columns to be added to WinForms FlexGrid in unbound mode

Add ColumnFlexGrid provides two ways to add a new column using the ColumnCollection class You can either use Add methodor increment the value of Count property provided by the class to add new columns Also note that if a new columnis added to a bound grid using these methods it is added as an unbound column only

Following are the two approaches to add column to a WinForms FlexGrid

Delete ColumnTo delete a particular column from the grid you can use Remove method of the ColumnCollection class and specifythe column you want to delete as its parameter In the unbound grid you can also reduce the number of columns bychanging the value of Count property This removes columns from the end of the column collection TheColumnCollection class also provides RemoveRange method which allows you to remove a range of columns

列数を設定します c1FlexGrid1ColsCount = 4

C

列数を設定しますc1FlexGrid1ColsCount = 4

VBNET

方法1 列コレクションのAddメソッドを使用します C1WinC1FlexGridColumn c c = c1FlexGrid1ColsAdd() cCaption = New Column

方法2 列コレクションのCountプロパティを変更します c1FlexGrid1ColsCount += 1 c1FlexGrid1Cols[c1FlexGrid1ColsCount - 1]Caption = New Column

C

方法1 列コレクションのAddメソッドを使用します Dim c As C1WinC1FlexGridColumn c = c1FlexGrid1ColsAdd() cCaption = New Column

方法2 列コレクションのCountプロパティを変更します c1FlexGrid1ColsCount += 1 c1FlexGrid1Cols(c1FlexGrid1ColsCount - 1)Caption = New Column

VBNET

FlexGrid for WinForms

37 Copyright copy GrapeCity Inc All rights reserved

Below code snippet shows all the three approaches to delete column from the WinForms FlexGrid

Insert ColumnTo insert a column in FlexGrid at a specific location you can use Insert method of the ColumnCollection class whichlets you specify the position where columns are to be inserted You can also insert multiple columns in the grid byusing the InsertRange method These methods add the unbound columns only even if the grid is a bound grid

Use any of the following approaches to insert a column in the WinForms FlexGrid at the specified location

方法1 列コレクションのRemoveメソッドを使用して2番目の列を削除します c1FlexGrid1ColsRemove(2)

方法2 Countプロパティを変更して最後の列を削除します c1FlexGrid1ColsCount -= 1

方法3 RemoveRangeメソッドを使用して2番目から始まる4つの列を削除します c1FlexGrid1ColsRemoveRange(2 4)

C

方法1 列コレクションのRemoveメソッドを使用して2番目の列を削除します c1FlexGrid1ColsRemove(2)

方法2 Countプロパティを変更して最後の列を削除します c1FlexGrid1ColsCount -= 1

方法3 RemoveRangeメソッドを使用して2番目から始まる4つの列を削除します c1FlexGrid1ColsRemoveRange(2 4)

VBNET

C1WinC1FlexGridColumn c

方法1 Insertメソッドを使用して2番目の位置に列を挿入します c = c1FlexGrid1ColsInsert(2) cCaption = Inserted Column

方法2 InsertRangeメソッドを使用して2番目の位置に3つの列を挿入します c1FlexGrid1ColsInsertRange(2 3)

C

Dim c As C1WinC1FlexGridColumn 方法1 Insertメソッドを使用して2番目の位置に列を挿入します c = c1FlexGrid1ColsInsert(2) cCaption = Inserted Column 方法2 InsertRangeメソッドを使用して2番目の位置に3つの列を挿入します c1FlexGrid1ColsInsertRange(2 3)

VBNET

FlexGrid for WinForms

38 Copyright copy GrapeCity Inc All rights reserved

Set Data TypeIn case of a bound FlexGrid data type of each bound column is automatically picked from the data source dependingon the data However in the case of unbound mode you can set the data type of columns by specifyingthe DataType property of Column class You can also set the Data Type property at design time by using theColumn Tasks menu For more information on tasks menus see Tasks Menus Note that when a particular data type isset to a FlexGrid column its cells accept the user input of keys accepted by the data type only For instance you cannot input alphabets in a Numeric type cell

Set the data type of an unbound column in WinForms FlexGrid as shown in the code below

Set Fixed ColumnFixed columns refer to the columns with non-editable cells which are always visible in the left hand side of the grideven if user scrolls the grid horizontally In FlexGrid fixed columns can be set using Fixed property ofthe ColumnCollection class This property accepts an integer value that specifies the number of columns to be fixed

Use the code below to set one column as fixed in the WinForms FlexGrid

Set Frozen ColumnFrozen columns similar to fixed columns are non-scrollable but can be edited by the user In FlexGrid frozen columnscan be set by using Frozen property provided by the ColumnCollection class

To set frozen columns in the WinForms FlexGrid use the code below

最初の列のデータ型を設定します c1FlexGrid1Cols[1]DataType = typeof(int)

C

最初の列のデータ型を設定しますc1FlexGrid1Cols(1)DataType = GetType(Integer)

VBNET

1つの列を固定列として設定しますc1FlexGrid1ColsFixed = 1

C

1つの列を固定列として設定しますc1FlexGrid1ColsFixed = 1

VBNET

最初の4列を静止として設定しますc1FlexGrid1ColsFrozen = 4

C

最初の4列を静止として設定しますc1FlexGrid1ColsFrozen = 4

VBNET

FlexGrid for WinForms

39 Copyright copy GrapeCity Inc All rights reserved

ユーザー操作

This topic discusses how you can let end users interact with the FlexGrid columns

Allow EditingBy default FlexGrid allows to edit all columns of the grid However you can choose to disable editing of a particularcolumn by setting AllowEditing property of the Column object to false You can also disable editing of the whole gridby setting the C1FlexGridAllowEditing property to false For more information on editing see Edit

Following code shows how to disable editing of WinForms FlexGrid while keeping only one column editable

Allow DraggingFlexGrid by default allows user to reorder columns by dragging a column header and dropping it to the targetposition However you can change this behavior by using the FlexGridAllowDragging propertyand ColumnAllowDragging property To disable dragging of a particular column you can set theColumnAllowDragging property of that column to false On the other hand setting the FlexGridAllowDraggingproperty to either Rows or None disables the column reordering at grid level This property accepts the valuesfrom AllowDraggingEnum You can also disable column reordering at design time by checking off the Enable ColumnReordering checkbox in the C1FlexGrid Tasks menu For more information on tasks menus see Tasks Menus

グリッド全体で編集を無効にしますc1FlexGrid1AllowEditing = false

3列目でのみ編集を有効にしますc1FlexGrid1Cols[3]AllowEditing = true

C

グリッド全体で編集を無効にしますc1FlexGrid1AllowEditing = False

3列目でのみ編集を有効にしますc1FlexGrid1Cols(3)AllowEditing = True

VBNET

FlexGrid for WinForms

40 Copyright copy GrapeCity Inc All rights reserved

Below code demonstrates how to enable dragging of columns in WinForms FlexGrid

Allow FreezingTo allow end user to freeze the columns at runtime you can use the AllowFreezing property of the C1FlexGrid classwhich accepts values from AllowFreezingEnum When this property is set to Columns or Both a lock sign appearswhen mouse is hovered over the edge of header column User can click and drag the lock sign to freeze the columns

Following code shows how to allow users to freeze the columns in WinForms FlexGrid

Allow PinningFlexGrid lets you allow your users to pin a particular column or column range at run time by using the AllowPinningproperty of the C1FlexGrid class Setting the property adds a Pin button( ) in the column header which allows usersto pin columns at run-time so they remain in view as the user scrolls the grid horizontally The property accepts itsvalues from AllowPinning enumeration which lets you set pinning for a single column or a column range Whenproperty is set to ColumnRange user can pin or unpin all the columns starting from left till the clicked column in onego

グリッド全体ですべての列のドラッグを許可します c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumColumns

特定の列のドラッグを無効にしますc1FlexGrid1Cols[3]AllowDragging = false

C

グリッド全体ですべての列のドラッグを許可します c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumColumns

特定の列のドラッグを無効にします c1FlexGrid1Cols(3)AllowDragging = False

VBNET

実行時に列のフリーズを許可します c1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumColumns

C

実行時に列のフリーズを許可しますc1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumColumns

VBNET

FlexGrid for WinForms

41 Copyright copy GrapeCity Inc All rights reserved

Use the code below to let user pin multiple columns in the WinForms FlexGrid

Allow SortingIn FlexGrid column sorting is enabled for the whole grid by default and value of AllowSorting property of theC1FlexGrid class is set to Auto In this mode user can sort a single column by clicking the column header andmultiple columns by holding the CTRL key while clicking the column headers On sorting multiple columns the gridshows sort index in the column header next to the sort direction glyph You can also choose to prevent sorting orsimply change the way the columns are sorted through AllowSortingEnum enumeration The AllowSortingEnumenumeration allows you to choose whether to auto sort columns sort single column multiple columns or columnrange or just prevent sorting

You can enable multi-column sorting in the WinForms FlexGrid using the code below When AllowSorting propertyis set to MultiColumn user may sort multiple columns by simply clicking on their headers one after the other

ユーザーが列範囲を固定できるようにしますc1FlexGrid1AllowPinning = C1WinC1FlexGridAllowPinningColumnRange

C

ユーザーが列範囲を固定できるようにしますc1FlexGrid1AllowPinning = C1WinC1FlexGridAllowPinningColumnRange

VBNET

グリッドで複数列の並べ替えを有効にしますc1FlexGrid1AllowSorting = C1WinC1FlexGridAllowSortingEnumMultiColumn

1列のみの並べ替えを無効にしますc1FlexGrid1Cols[1]AllowSorting = false

C

グリッドで複数列の並べ替えを有効にしますc1FlexGrid1AllowSorting = C1WinC1FlexGridAllowSortingEnumMultiColumn

1列のみの並べ替えを無効にしますc1FlexGrid1Cols(1)AllowSorting = False

VBNET

FlexGrid for WinForms

42 Copyright copy GrapeCity Inc All rights reserved

To disable sorting on a particular column you need to set the ColumnAllowSorting property of that column to falseFor more information on sorting see Sort

Allow FilteringFlexGrid doesnt allow filtering at runtime by default However you can enable it by settingthe C1FlexGridAllowFiltering property to true To define the type of filter you want to apply on a particularcolumn you can use the ColumnAllowFiltering property which accepts following values from the AllowFilteringenumeration

AllowFiltering Values Description

Default The grid automatically creates a filter of type ColumnFilter This filteris the combination of a value filter and a condition filter

ByValue The grid automatically creates a filter of type ValueFilter This filteroffers a checkbox list of values to choose from Values that are notchecked in the list are excluded from the filter output

ByCondition The grid automatically creates a filter of type ConditionFilter Thisfilter provides several options such as Equals is Greater thanContains Begins with etc to create conditions You can also combinetwo conditions by using the And and Or operators available in thefilter

Custom The grid does not create a filter automatically and allows you to defineyour own filter and then explicitly assign it to Filter property of theColumn class

None Filtering is disabled for the column

For more information on filtering see Filter

Following code shows how to enable filtering in the WinForms FlexGrid and how to apply filters

Allow ResizingBy default FlexGrid allows resizing of all columns of the grid To change this behavior you can use AllowResizingproperty of the C1FlexGrid class This property accepts values from the AllowResizingEnum enumeration which letsyou resize columns rows both or none The enumeration also gives you options to uniformly resize the rows columnsor both that is if you resize one of the columns or rows the grid automatically resizes rest of the columns or rows as

グリッドレベルでのフィルタリングを許可します c1FlexGrid1AllowFiltering = true

最初の列に条件フィルターを適用します c1FlexGrid1Cols[1]AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

C

グリッドレベルでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = True

最初の列に条件フィルターを適用しますc1FlexGrid1Cols(1)AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

VBNET

FlexGrid for WinForms

43 Copyright copy GrapeCity Inc All rights reserved

well FlexGrid also provides ColumnAllowResizing property which is a Boolean type property and lets you enable ordisable resizing of a particular row or column

Below code shows how to allow users to resize columns of WinForms FlexGrid

Enable Context MenuFlexGrid provides support for column context menu at run-time to facilitate quick actions related to columnoperations To enable the column context menu on right-click you need to set ColumnContextMenuEnabled propertyprovided by the C1FlexGrid class to true By default this property is set to false

The column context menu provides following options

Option Description

Sort Ascending Sorts the column in ascending order

Sort Descending Sorts the column in descending order

Group by This Groups the grid data based on column under mouse pointer

列と行のサイズを均一に変更できますc1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumBoth

最初の列のサイズ変更のみを無効にしますc1FlexGrid1Cols[1]AllowResizing = false

C

列と行のサイズを均一に変更できますc1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumBoth

最初の列のサイズ変更のみを無効にしますc1FlexGrid1Cols(1)AllowResizing = False

VBNET

FlexGrid for WinForms

44 Copyright copy GrapeCity Inc All rights reserved

Column

Ungroup Removes grouping from the grid data The option displays only when grid is in groupedstate

Hide this Column Hides the column under mouse pointer

Auto size Resizes the column according to the length of longest value

Auto size (allcolumns)

Resizes all columns according to the length of longest value in each of them

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = true

C

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = True

VBNET

Option Description

エディタ

This topic discusses various built-in editors of FlexGrid and operations related to them The topic also takes you through thesteps to apply custom editors in the FlexGrid columns

Built-in EditorsFlexGrid provides several built-in editors to enable efficient in-cell editing The grid uses TextBox control as its default editorHowever other built-in editors such as numeric date checkbox and combo box are also supported These editors areautomatically assigned generally based on the value of some specific properties such as DataType property of the column Thetable below summarizes the built-in editors provided by FlexGrid their brief description and the example codes demonstratingthem For more information about built-in editors and their customization click the corresponding hyperlink

Built-inEditor

Snapshot Description Sample Code

Checkbox Gets enabledautomatically whenDataType propertyof the Columnobject is set to

c1FlexGrid1Cols[colIndex]DataType =

typeof(Boolean)

FlexGrid for WinForms

45 Copyright copy GrapeCity Inc All rights reserved

Boolean

Numeric Gets enabledautomatically whenDataType propertyis set to a numericdata type such asInt or Decimal

c1FlexGrid1Cols[colIndex]DataType =

typeof(Int32)

Date Gets enabledautomatically if theDataType propertyof column is set toDate or DateTime

c1FlexGrid1Cols[colIndex]DataType =

typeof(DateTime)

ComboBox Gets enabled bysetting multiplevalues separated bypipe inthe ComboListproperty

c1FlexGrid1Cols[colIndex]ComboList =

Red|Green|Blue|Red|White

Mask Gets enabled whenthe EditMaskproperty of columnis set

c1FlexGrid1Cols[colIndex]EditMask =

(999) 999-9999

Mappedlist

Gets enabled whenthe DataMapproperty is set to anIDictionary objectwhich establishesmapping betweenvalues stored in thegrid and thosevisible to a user

ListDictionary customerNames = new

ListDictionary()

customerNamesAdd(AJK18F Sam

Anders)

customerNamesAdd(BBK21D Daneil)

customerNamesAdd(AEF25N Henry

Hussain)

customerNamesAdd(BZD42S Owen

Romanov)

customerNamesAdd(AKC16G Serena

Nguyen)

c1flexGrid1Cols[Name]DataMap =

customerNames

c1flexGrid1ShowButtons =

ShowButtonsEnumWithFocus

Cell Button Gets enabled whenthe ComboListproperty is set to anellipsis() whichautomaticallydisplays a cellbutton in editmode You can then

c1flexGrid1Cols[colIndex]ComboList

=

c1flexGrid1CellButtonClick +=

C1flexGrid1_CellButtonClick

FlexGrid for WinForms

46 Copyright copy GrapeCity Inc All rights reserved

capturethe CellButtonClickevent either toshow a dialog boxor to perform anyother operation

Custom EditorsFlexGrid control provides most of the commonly used editing options through the above-mentioned built-in editors However inaddition you can also use external controls as editors to meet the specialized editing needs Any control that derives from thebase Control class can be easily used as an editor This can be done at design time as well as through code In the examplebelow we are setting the C1ColorPicker control as a cell editor

At Design Time

1 Add the C1FlexGrid control and C1ColorPicker control to the form2 Select Designer option from the C1FlexGrid Tasks menu to open the C1FlexGrid Column Editor3 Select a column and switch to Properties pane on left hand side4 Navigate to the Editor property and set its value to instance of the C1ColorPicker control

At Run Time

To set an external control as editor through code create an instance of the control and assign it to the Editor property ofthe Column object

See the code below to know how to set an external control as editor in WinForms FlexGrid column

カスタムエディタとして使用するC1ColorPickerコントロールのインスタンスを作成します C1WinC1InputC1ColorPicker customeditor = new C1WinC1InputC1ColorPicker() カスタムエディタにEditorプロパティを割り当てます c1FlexGrid1Cols[1]Editor = customeditor

C

FlexGrid for WinForms

47 Copyright copy GrapeCity Inc All rights reserved

For controls which are not derived from the Control base class it is still possible to use them as editors usingIC1EmbeddedEditor interface You can even use the UITypeEditor classes as grid editors This way the FlexGrid control canuse virtually any control as a cell editor For more information about the implementation see the product sample named CustomEditors

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

カスタムエディタとして使用するC1ColorPickerコントロールのインスタンスを作成します Dim customeditor As C1WinC1InputC1ColorPicker = New C1WinC1InputC1ColorPicker()

カスタムエディタにEditorプロパティを割り当てます c1FlexGrid1Cols(1)Editor = customeditor

VBNET

チェックボックス

Display Checkbox for Boolean ValuesFlexGrid by default uses the checkbox editor for representing the Boolean values That is when the DataTypeproperty of a Row or Column object is set to Bool type a checkbox appears in the cells and user can toggle the valueof an editable cell simply by clicking it

To disable this default behavior and display text value instead of a checkbox in a Bool type you can set the Formatproperty of Row or Column object to string values

Default Checkbox Checkbox with Text Checkbox with Non-Boolean Value Three-state Checkbox

Use the code below to set checkbox type editor in a WinForms FlexGrid column and configure it further

データ型をブール値に設定します(チェックボックスを自動的に表示します)c1FlexGrid1Cols[Verified]DataType = typeof(Boolean)

チェックボックスを表示する代わりに文字列値を表示しますc1flexGrid1Cols[Verified]Format = YesNo ブール列のチェックボックスの横にあるテキストを有効にしますc1flexGrid1Cols[Verified]ImageAndText = true

C

データ型をブール値に設定します(チェックボックスを自動的に表示します)c1FlexGrid1Cols(Verified)DataType = GetType(Boolean)

チェックボックスを表示する代わりに文字列値を表示しますc1flexGrid1Cols(Verified)Format = YesNo

ブール列のチェックボックスの横にあるテキストを有効にしますc1flexGrid1Cols(Verified)ImageAndText = True

VBNET

FlexGrid for WinForms

48 Copyright copy GrapeCity Inc All rights reserved

Display Checkbox for Non-Boolean ValuesIn unbound mode you can display a checkbox along with any non-boolean text as well You can use the SetCellCheckmethod to add checkbox to any kind of cells Along with row and column index this method takes valueof CheckEnum enumeration as one of its parameters to specify the state of checkbox at the time of rendering

Following code demonstrates how you can display checkbox for non-boolean values

Set Checkbox AlignmentTo set position of checkbox in the cell you need to use ImageAlign property of the Row or Column object Thisproperty accepts values from the ImageAlignEnum enumeration which lets you hide tile stretch or position the image

Align the checkbox to display in center of a WinForms FlexGrid column using the code below

Change the Checkbox ImageTo change icon image of different states of checkbox you can use the GlyphEnum which can be accessed usingthe Glyphs property For more information about changing glyphs see Custom Glyphs

You can change the images to be used for various checkbox states in WinForms FlexGrid using the code below

チェックオン状態のセル(32)に2つの状態のチェックボックスを設定します c1flexGrid1SetCellCheck(3 2 CheckEnumChecked)

C

チェックオン状態のセル(32)に2つの状態のチェックボックスを設定しますc1flexGrid1SetCellCheck(3 2 CheckEnumChecked)

VBNET

チェックボックスをセルの右中央に揃えますc1flexGrid1Cols[Verified]ImageAlign = ImageAlignEnumRightCenter

C

チェックボックスをセルの右中央に揃えますc1flexGrid1Cols(Verified)ImageAlign = ImageAlignEnumRightCenter

VBNET

カスタム画像をチェックボックスアイコンとして設定します Image imgChk = new Bitmap(ResourcesImagescheckedpng) Image imgUnchk = new Bitmap(ResourcesImagesuncheckedpng) Image imgGray = new Bitmap(ResourcesImagesnullpng) c1flexGrid1Glyphs[GlyphEnumChecked] = imgChk c1flexGrid1Glyphs[GlyphEnumUnchecked] = imgUnchk c1flexGrid1Glyphs[GlyphEnumGrayed] = imgGray

C

カスタム画像をチェックボックスアイコンとして設定します Dim imgChk As Image = New Bitmap(ResourcesImagescheckedpng) Dim imgUnchk As Image = New Bitmap(ResourcesImagesuncheckedpng)

VBNET

FlexGrid for WinForms

49 Copyright copy GrapeCity Inc All rights reserved

Use Three State CheckboxIn addition to usual two state checkbox FlexGrid lets you create three state checkbox as well The simplest way ofenabling the third state is through the CheckEnum While a Boolean checkbox togglesbetween CheckEnumChecked and CheckEnumUnchecked states the three states of a three state checkbox arerepresented by CheckEnumTSChecked CheckEnumTSUnchecked and CheckEnumTSGrayed However in thiscase by default user can not go back to null after switching to checked or unchecked state once In order to cycle acheckbox between three states you need to handle the ValidateEdit event

Use the code below to create a three state checkbox in the WinForms FlexGrid

Dim imgGray As Image = New Bitmap(ResourcesImagesnullpng) c1flexGrid1Glyphs(GlyphEnumChecked) = imgChk c1flexGrid1Glyphs(GlyphEnumUnchecked) = imgUnchk c1flexGrid1Glyphs(GlyphEnumGrayed) = imgGray

private void c1FlexGrid1_ValidateEdit(object sender ValidateEditEventArgs e) if (c1FlexGrid1Cols[eCol]Name == Done) eCancel = true if (c1FlexGrid1[eRow eCol]Equals(false)) c1FlexGrid1[eRow eCol] = true else if (c1FlexGrid1[eRow eCol]Equals(true)) c1FlexGrid1[eRow eCol] = DBNullValue else if (c1FlexGrid1[eRow eCol]Equals(DBNullValue)) c1FlexGrid1[eRow eCol] = false

C

Private Sub c1FlexGrid1_ValidateEdit(ByVal sender As Object ByVal e As ValidateEditEventArgs) If c1FlexGrid1Cols(eCol)Name Is Done Then eCancel = True

If c1FlexGrid1(eRow eCol)Equals(False) Then c1FlexGrid1(eRow eCol) = True ElseIf c1FlexGrid1(eRow eCol)Equals(True) Then c1FlexGrid1(eRow eCol) = DBNullValue ElseIf c1FlexGrid1(eRow eCol)Equals(DBNullValue) Then c1FlexGrid1(eRow eCol) = False End If End IfEnd Sub

VBNET

数値

FlexGrid by default uses the numeric editor to edit the numeric data that is when the data type is set to any of the numeric types such as Int and Decimal Thisbehavior of FlexGrid is controlled by the EditOptions property which provides various editing options through the EditFlags enumeration One of the flagsprovided is UseNumericEditor As the default value of EditOptions property is All UseNumericEditor flag is always ON and hence grid automatically enablesthe numeric editor while editing the numeric data You can access the EditOptions property at design time as well as through code

FlexGrid for WinForms

50 Copyright copy GrapeCity Inc All rights reserved

Numeric Editor Numeric Editor with Format = C0 Numeric Editor with Spin Button Numeric Editor with Calculator

At Design Time

To enable or disable the numeric editor at design time you can access the EditOptions property from the Properties window

At Run Time

At run-time you need to set the UseNumericEditor flag On in the EditOptions property Use the code below to set EditOptions property in the WinFormsFlexGrid

Format Numeric CellTo format the data in a numeric cell FlexGrid provides the Format property of Column as well as Row object In case of the formats that support decimal valuessuch as numeric currency and exponential FlexGrid displays values up to two decimal places by default However you can specify the number of decimals todisplay by appending the value of Format property with that number For instance in order to display values up to three decimal places in a Number type cellyou specify value of Format property as N3 or n3

Note This property doesnt have any effect on the stored value but only on how value is displayed at the run time You can access the formatted valueof a cell using GetDataDisplay(Int32 Int32) method of the C1FlexGrid class

You can set the Format property at design time as well as through code Following table lists the commonly used formats for numeric cells

Format Value Description

Number N or n Specifies the formatting for simple numeric values

Currency C or c Specifies the formatting for monetary values

Exponential or Scientific E or e Specifies the formatting for values using scientific notations

Percentage P or p Specifies the formatting for percentage values

Custom User-defined Takes the value of format string from user

A custom string might require handling in the code

At Design Time

1 In design view click on the FlexGrid smart tag to open the C1FlexGrid Tasks menu2 Click the Column Tasks option and navigate to Format String property3 Click ellipsis button to open the Format String dialog

すべてのフラグをオンに設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsAll

UseNumericEditorフラグのみを設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsUseNumericEditor

C

すべてのフラグをオンに設定しますc1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsAll

UseNumericEditorフラグのみを設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsUseNumericEditor

VBNET

FlexGrid for WinForms

51 Copyright copy GrapeCity Inc All rights reserved

4 Select the required format from the list box on left say Currency5 Set the format specific properties on the right hand side of the dialog Decimal places in this case

At Run Time

To specify the format of a particular numeric type column set the Format property to any of the above mentioned values In this example we have set theformat of column 3 as currency without decimals

Following code shows how to set the format of a WinForms FlexGrid column

Input using Spin ButtonTo create a numeric editor which uses a spin button for input you need to assign instance of an external control such as NumericUpDown to the Editorproperty

Use the code below to create a numeric editor with spin button in the WinForms FlexGrid

Input using CalculatorTo allow user to give input using a calculator in a numeric editor you can use the C1NumericEdit control of C1Input library as an editor So just add thereference to C1WinC1Input and assign an instance of C1NumericEdit control to the Editor property For more information about using an external controlas editor see Custom Editors

To create a numeric editor with calculator use the code below

小数点なしの通貨形式を設定します c1FlexGrid1Cols[3]Format = C0

C

小数点なしの通貨形式を設定しますc1FlexGrid1Cols(3)Format = C0

VBNET

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols[2]Editor = new NumericUpDown()

C

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols(2)Editor = New NumericUpDown()

VBNET

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols[2]Editor = new C1NumericEdit()ShowUpDownButtons=false

C

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols(2)Editor = New C1NumericEdit() With ShowUpDownButtons = False

VBNET

日付

FlexGrid by default uses the Date editor for all the Date and DateTime type of data The Date editor consists of adropdown which opens a calendar when clicked and user can select the desired date by navigating through it Usercan also change the date month or year by simply selecting the corresponding part in the editor and pressing the upand down arrow keys

FlexGrid for WinForms

52 Copyright copy GrapeCity Inc All rights reserved

Default Date Editor Date Editor Without Calendar Date Editor with Spin Button

Use the code below to create a Date editor in a WinForms FlexGrid column

Input without Displaying CalendarAs mentioned earlier in FlexGrid a DateTime type cell automatically displays a dropdown calendar to receive theinput from user However in order to get a date input from user without displaying a calendar you can set a maskusing the EditMask property and then validate the input value using the ValidateEdit event

Following code demonstrates how to create a Date editor without calendar in WinForms FlexGrid

For more information about cell masks and validation see topics Mask and Validation respectively Another way ofhiding the calendar is to get user input using the spin buttons

Input using Spin ButtonBelow code shows how to create Date editor with spin button

To display spin buttons in a Date editor use the SetupEditor event to convert the editor into DateTimePicker and setits ShowUpDown property to true

Set the data type property to DateTime c1FlexGrid1Cols[1]DataType = typeof(DateTime)

C

Set the data type property to DateTimec1FlexGrid1Cols(1)DataType = GetType(Date)

VBNET

Set a mask on column c1flexGrid1Cols[3]EditMask = 00000000

C

Set a mask on columnc1flexGrid1Cols(3)EditMask = 00000000

VBNET

private void C1flexGrid1_SetupEditor(object sender RowColEventArgs e)

C

FlexGrid for WinForms

53 Copyright copy GrapeCity Inc All rights reserved

Set Date FormatTo set the format in a Date type column you need to set the Format property of the Column object

Following table lists the pre-defined formats

Format Value Example

Short Date d 11192003

Long Date D Friday November 19 2003

Short Time t 1215 AM

Long Time T 121530 AM

You can also create a custom format using the various custom format specifiers supported in the Net framework Fordetails see Custom date and time format strings on Microsoft website

Use the following code to create a custom date format in WinForms FlexGrid column

if (c1flexGrid1Cols[eCol]Name == DOB) Cast FlexGrids current cell editor var dateEditor = c1flexGrid1Editor as DateTimePicker

Show UpDown button (replacing the drop-down button for calendar) dateEditorShowUpDown = true

Private Sub C1flexGrid1_SetupEditor(ByVal sender As Object ByVal e As RowColEventArgs) If c1flexGrid1Cols(eCol)Name Is DOB Then Cast FlexGrids current cell editor Dim dateEditor = TryCast(c1flexGrid1Editor DateTimePicker)

Show UpDown button (replacing the drop-down button for calendar) dateEditorShowUpDown = True End IfEnd Sub

VBNET

Set a pre-defined format c1FlexGrid1Cols[DOB]Format = d Set a custom format c1FlexGrid1Cols[OrderDate]Format = ddMMyyyy

C

Set a pre-defined format c1FlexGrid1Cols(DOB)Format = d

Set a custom format c1FlexGrid1Cols(OrderDate)Format = ddMMyyyy

VBNET

FlexGrid for WinForms

54 Copyright copy GrapeCity Inc All rights reserved

Display Country-specific Date FormatAlthough abovementioned formats are the most commonly used date formats but there are cultures which preferusing their specific calendar and date formats in some cases such as Japan You can display those specific calendarsand date formats by using OwnerDrawCell event of the C1FlexGrid class and the SystemGlobalization namespaceThe namespace provides various classes to define culture related information including calendars and date formatsFor instance to display Japanese calendar and Japanese date format you can leveragethe SystemGlobalizationJapaneseCalendar class Similarly you can also display other calendars such as GregorianHebrew Hijri and Korean

Set the country specific date format in WinForms FlexGrid using the code below

Set MinMax DateTo set a range of valid values you can use the DateTimePicker control as editor and set its MinDate and MaxDate

c1flexGrid1Cols[DOB]Format = ddMMyyyy c1flexGrid1DrawMode = DrawModeEnumOwnerDraw c1flexGrid1OwnerDrawCell += C1flexGrid1_OwnerDrawCell private void C1flexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if (c1flexGrid1Cols[eCol]DataType == typeof(DateTime) ampamp eRow gt= c1flexGrid1RowsFixed) eText = DateTimeParse(eText)ToString(yyyy年MM月dd日(dddd) c)

C

C1FlexGrid1Cols(DOB)Format = ddMMyyyy C1FlexGrid1DrawMode = DrawModeEnumOwnerDraw

AddHandler C1FlexGrid1OwnerDrawCell AddressOf C1flexGrid1_OwnerDrawCell

Private Sub C1flexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If C1FlexGrid1Cols(eCol)DataType = GetType(DateTime) AndAlso eRow gt= C1FlexGrid1RowsFixed Then eText = DateTimeParse(eText)ToString(yyyy年MM月dd日(dddd) c) End If End Sub

VBNET

FlexGrid for WinForms

55 Copyright copy GrapeCity Inc All rights reserved

property

Use the code below to set a range of valid dates in WinForms FlexGrid

DateTimePicker dateTimePicker = new DateTimePicker() dateTimePickerFormat = DateTimePickerFormatShort

Sets Max and Min dates dateTimePickerMinDate = new DateTime(2015 05 01) dateTimePickerMaxDate = DateTimeToday

Assigns DateTimePicker control as editor for FirstOrderDate(date) column c1flexGrid1Cols[FirstOrderDate]Editor = dateTimePicker

C

Dim dateTimePicker As DateTimePicker = New DateTimePicker() dateTimePickerFormat = DateTimePickerFormat[Short]

Sets Max and Min dates dateTimePickerMinDate = New DateTime(2015 05 01) dateTimePickerMaxDate = DateToday

Assigns DateTimePicker control as editor for FirstOrderDate(date) column c1flexGrid1Cols(FirstOrderDate)Editor = dateTimePicker

VBNET

コンボボックス

ComboBox cell is a common way of providing the user with a well-defined list of possible values in the form of a drop-down list FlexGrid providesthis multi-option editor in various forms such as dropdown list dropdown combo ellipsis button or a textbox with ellipsis button

Default ComboBox Multi-column ComboBox ComboBox with custom BackColor ComboBox with Images

Display Dropdown List or ComboIn FlexGrid you can create a dropdown list by creating a string containing all the choices separated by pipe characters (for exampleTrue|False|Dont know) and assign it to the ComboList property of Row or Column object This causes the grid to display a drop-down buttonnext to the cell The user can click the dropdown button (or press F2) to display the list of choices available for that cell

Another common situation is where cells have a list of common values but users should be allowed to type a custom value as well This can beaccomplished with drop-down combos a combination of text box and drop-down list In FlexGrid you can create combos by starting the choicelist with a pipe character (for example |True|False|Dont know) and then assign it to the ComboList property

Following code shows how to create a dropdown list or combo editor in the WinForms FlexGrid

FlexGrid for WinForms

56 Copyright copy GrapeCity Inc All rights reserved

The ComboList property can also be set using the Combo List dialog at design time To access the Combo List dialog

1 Open the Column Tasks menu for column for which editor is to be set2 Go to the Combo List option and click the ellipsis button on the right hand side of the field3 Combo List dialog opens where you can specify the option values each in a new line4 You can also choose whether you want to display these values as a Dropdown List or Dropdown Combo Note that it also lets you create

cell button using Ellipsis Button or Textbox amp Ellipsis Button option

Display Multi-column ComboBoxIn FlexGrid you can also display multiple columns in a ComboBox using the MultiColumnDictionary class This class implementsthe IC1MultiColumnDictionary interface and has multiple overloads These overloads let you specify the data source object the key columncolumns that are to be displayed in multiple columns and the column to be displayed when ComboBox is closed

Display a multi-column combobox in a WinForms FlexGrid column using the code below

Note that the above code uses the data source object dt to supply data to the grid You can set up the data source as per your requirements

ドロップダウンリストとしてCustomerIDを割り当てますc1flexGrid1Cols[CustomerID]ComboList = AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

ドロップダウンコンボボックスとしてCustomerIDを割り当てパイプ文字|でリストを開始します c1flexGrid1Cols[CustomerID]ComboList = |AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

C

ドロップダウンリストとしてCustomerIDを割り当てますc1flexGrid1Cols(CustomerID)ComboList = AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

ドロップダウンコンボボックスとしてCustomerIDを割り当てパイプ文字|でリストを開始します c1flexGrid1Cols(CustomerID)ComboList = |AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

VBNET

string[] columnRange = new string[] City Country c1FlexGrid1Cols[City]DataMap = new MultiColumnDictionary(dt City columnRange 0)

C

Dim columnRange = New String() City Countryc1FlexGrid1Cols(City)DataMap = New MultiColumnDictionary(dt City columnRange 0)

VBNET

DataTable dt = new DataTable() dtColumnsAdd(CustomerID typeof(int)) dtColumnsAdd(ContactName typeof(string)) dtColumnsAdd(Designation typeof(string)) dtColumnsAdd(City typeof(string)) dtColumnsAdd(Country typeof(object))

サンプルデータ

C

FlexGrid for WinForms

57 Copyright copy GrapeCity Inc All rights reserved

Set Mapped Data in the ComboBoxTo set a ComboBox having display values different from the actual values you need to use the C1ComboBox as editor and leverageits ItemsDisplayMember and ItemsValueMember properties For instance the example below uses country names as display values while actualvalue is the dialing code of the corresponding country

Following code shows how to set the mapped data in combobox column of the WinForms FlexGrid

dtRowsAdd(1 Maria Anders Sales Representative Madrid Spain ) dtRowsAdd(2 Ana Trujillo Sales Associate Monterrey Mexico ) dtRowsAdd(3 Antonio Moreno Owner Dublin Ireland) dtRowsAdd(4 Thomas Hardy Sales Representative Bristol UK) dtRowsAdd(5 Patricio Simpson Marketing Manager Munich Germany) dtRowsAdd(6 Paolo Accorti Sales Representative Barcelona Spain) dtRowsAdd(7 Martine Ranceacute Owner Puebla Mexico) dtRowsAdd(8 Elizabeth Brown Marketing Manager London UK) dtRowsAdd(9 Jaime Yorres Order Administrator Vienna Austria) dtRowsAdd(10 Yvonne Moncada Marketing Manager Mexico Mexico) dtRowsAdd(11 Helen Bennett OwnerMarketing Cork Ireland) dtRowsAdd(12 Sergio Gutieacuterrezy Order Administrator Sao Paulo Brazil)

c1FlexGrid1DataSource = dt

Dim dt As DataTable = New DataTable()dtColumnsAdd(CustomerID GetType(Integer))dtColumnsAdd(ContactName GetType(String))dtColumnsAdd(Designation GetType(String))dtColumnsAdd(Country GetType(Object))dtColumnsAdd(City GetType(String))

サンプルデータdtRowsAdd(1 Maria Anders Sales Representative Spain Madrid)dtRowsAdd(2 Ana Trujillo Sales Associate Mexico Monterrey)dtRowsAdd(3 Antonio Moreno Owner Ireland Dublin)dtRowsAdd(4 Thomas Hardy Sales Representative UK Bristol)dtRowsAdd(5 Patricio Simpson Marketing Manager Germany Munich)dtRowsAdd(6 Paolo Accorti Sales Representative Spain Barcelona)dtRowsAdd(7 Martine Ranceacute Owner Mexico Puebla)dtRowsAdd(8 Elizabeth Brown Marketing Manager UK London)dtRowsAdd(9 Jaime Yorres Order Administrator Austria Vienna)dtRowsAdd(10 Yvonne Moncada Marketing Manager Mexico Mexico)dtRowsAdd(11 Helen Bennett OwnerMarketing Ireland Cork)dtRowsAdd(12 Sergio Gutieacuterrezy Order Administrator Brazil Sao Paulo)c1FlexGrid1DataSource = dt

VBNET

private void Form1_Load(object sender EventArgs e) 顧客データを取得します Customers = GetCustomers()

FlexGridにデータを入力します c1FlexGrid1DataSource = Customers

国とその国コードのコレクションを作成します ObservableCollectionltCountrygt countries = new ObservableCollectionltCountrygt() countriesAdd(new Country(1 USA)) countriesAdd(new Country(91 India)) countriesAdd(new Country(7 Russia))

C

FlexGrid for WinForms

58 Copyright copy GrapeCity Inc All rights reserved

Set ComboBox DimensionsTo set the height and width of combo box dropdown you need to assign an instance of ComboBox as an editor and then setthe DropDownHeight and DropDownWidth property of that instance

countriesAdd(new Country(54 Argentina)) countriesAdd(new Country(81 Japan)) countriesAdd(new Country(380 Ukraine)) countriesAdd(new Country(98 Iran)) countriesAdd(new Country(45 Denmark)) countriesAdd(new Country(84 Vietnam)) countriesAdd(new Country(49 Germany)) BindingSource countryBS = new BindingSource() countryBSDataSource = countries

C1Comboboxコントロールをインスタンス化して設定します C1ComboBox countryCodeCombo = new C1ComboBox() countryCodeComboItemsDataSource = countryBS

region Mapped Data using C1Combobox

国コードと国名をマッピングするためにプロパティを設定します countryCodeComboItemsDisplayMember = CountryName countryCodeComboItemsValueMember = CountryCode countryCodeComboTextDetached = true countryCodeComboTranslateValue = true

C1ComboboxをDiallingCode列のエディタとして設定します c1FlexGrid1Cols[DiallingCode]Editor = countryCodeCombo endregion

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) 顧客データを取得します Customers = GetCustomers()

FlexGridにデータを入力します c1FlexGrid1DataSource = Customers

国とその国コードのコレクションを作成します Dim countries As ObservableCollection(Of Country) = New ObservableCollection(Of Country)() countriesAdd(New Country(1 USA)) countriesAdd(New Country(91 India)) countriesAdd(New Country(7 Russia)) countriesAdd(New Country(54 Argentina)) countriesAdd(New Country(81 Japan)) countriesAdd(New Country(380 Ukraine)) countriesAdd(New Country(98 Iran)) countriesAdd(New Country(45 Denmark)) countriesAdd(New Country(84 Vietnam)) countriesAdd(New Country(49 Germany)) Dim countryBS As BindingSource = New BindingSource() countryBSDataSource = countries

C1Comboboxコントロールをインスタンス化して設定します Dim countryCodeCombo As C1ComboBox = New C1ComboBox() countryCodeComboItemsDataSource = countryBS

国コードと国名をマッピングするためにプロパティを設定します countryCodeComboItemsDisplayMember = CountryName countryCodeComboItemsValueMember = CountryCode countryCodeComboTextDetached = True countryCodeComboTranslateValue = True

C1ComboboxをDiallingCode列のエディタとして設定します c1FlexGrid1Cols(DiallingCode)Editor = countryCodeComboEnd Sub

VBNET

FlexGrid for WinForms

59 Copyright copy GrapeCity Inc All rights reserved

Use the code below to specify the height and width of the combobox to be displayed in the WinForms FlexGrid

Change Background Color or Font ColorTo change the background color or font color of the ComboBox list create an instance of ComboBox to assign it as editor Then set the BackColorand ForeColor property of that instance

Customize combobox in the WinForms FlexGrid by using the code below

Display Image in the ListTo display images in the ComboBox list you need to use the C1ComboBox as an editor and leverage its ItemsImageList property This property isof type ImageList class that acts as a container for the images which are stored in its Images collection First access the images stored in theproject resources through the ResourceManagerGetResourceSet method and create a collection of mapping between images and itscorresponding names The collection acts as a data source for ComboBox Now create an instance of the ImageList class add images to itsImages collection from data source and assign that instance of ImageList class to the ItemsImageList property to render images in the ComboBoxlist

Following code shows how to display images in the combobox lists of WinForms FlexGrid

ComboBox cb = (ComboBox)c1flexGrid1Editor cbDropDownWidth = 250 cbDropDownHeight = 200

C

Dim cb As ComboBox = CType(c1flexGrid1Editor ComboBox) cbDropDownWidth = 250 cbDropDownHeight = 200

VBNET

ComboBox comboBox = new ComboBox() comboBoxBackColor = ColorBlack comboBoxForeColor = ColorWhite

C

Dim comboBox As ComboBox = New ComboBox() comboBoxBackColor = ColorBlack comboBoxForeColor = ColorWhite

VBNET

コンボボックスに画像を入力します var itemsSource = new ListltFlaggt() ImageList imgFlag = new ImageList() imgFlagImagesClear() var rsrSet = ResourcesResourceManagerGetResourceSet(CultureInfoCurrentCulture true true)

foreach(DictionaryEntry entry in rsrSet) var img = entryValue as Image itemsSourceAdd(new Flag(entryKeyToString() img)) itemsSourceSort(new CompareFlag())

foreach (Flag entry in itemsSource) imgFlagImagesAdd(entryCountryName entryCountryFlag)

countryComboItemsImageList = imgFlag

C

FlexGrid for WinForms

60 Copyright copy GrapeCity Inc All rights reserved

Set Number of Displayed ItemsTo set the number of items to be displayed in a combo box you can use ComboBoxMaxDropDownItems property

Use the code below to limit the number of items to be displayed in combobox list of the WinForms FlexGrid

Sort the ComboBox ListTo sort the items in the ComboBox dropdown list you can use the C1ComboBox as editor and call the Sort method to sort the dropdown itemsgetting displayed in the ComboBox

To display sorted items in comboboxlist of the WinForms FlexGrid use the code below

countryComboItemMode = ComboItemModeHtmlPattern countryComboHtmlPattern = ltdiv ltdiv style=padding0pxgtltimg src=CountryName style=padding-right14pxgtCountryNameltdivgt

コンボボックスに画像を入力します Dim itemsSource = New List(Of Flag)()Dim imgFlag As ImageList = New ImageList()imgFlagImagesClear()Dim rsrSet = ResourcesResourceManagerGetResourceSet(CultureInfoCurrentCulture True True)

For Each entry As DictionaryEntry In rsrSet Dim img = TryCast(entryValue Image) itemsSourceAdd(New Flag(entryKeyToString() img))Next

itemsSourceSort(New CompareFlag())

For Each entry In itemsSource imgFlagImagesAdd(entryCountryName entryCountryFlag)Next

countryComboItemsImageList = imgFlagcountryComboItemMode = ComboItemModeHtmlPatterncountryComboHtmlPattern = ltdiv ltdiv style=padding0pxgtltimg src=CountryName style=padding-right14pxgtCountryNameltdivgt

VBNET

コンボボックスのドロップダウンに表示する国の数を設定します countryComboMaxDropDownItems = 10

C

コンボボックスのドロップダウンに表示する国の数を設定しますcountryComboMaxDropDownItems = 10

VBNET

C1ComboBox countryCombo = new C1ComboBox() countryComboDropDownStyle = DropDownStyleDropDownList Listltstringgt countries = new Listltstringgt USA Canada India Russia Japan Germany countriesSort() countryComboItemsDataSource = countries

C1ComboboxをCountry列のエディタとして設定します c1FlexGrid1Cols[Country]Editor = countryCombo

C

FlexGrid for WinForms

61 Copyright copy GrapeCity Inc All rights reserved

Get the Selected IndexTo get the selected index or value of the selected item you can use the SelectedIndex property or SelectedItem property of the ComboBoxEditorclass The example below uses the ComboCloseUp event to show a message box displaying the selected index and the selected item

Use the code below to fetch the index and value of selected item in combobox list of the WinForms FlexGrid

Dim countryCombo As C1ComboBox = New C1ComboBox() countryComboDropDownStyle = DropDownStyleDropDownList Dim countries As List(Of String) = New List(Of String) From USA Canada India Russia Japan Germany countriesSort() countryComboItemsDataSource = countries

C1ComboboxをCountry列のエディタとして設定します c1FlexGrid1Cols(Country)Editor = countryCombo

VBNET

private void C1FlexGrid1_ComboCloseUp(object sender C1WinC1FlexGridRowColEventArgs e) MessageBoxShow(Selected Index + c1FlexGrid1ComboBoxEditorSelectedIndex + n + Selected Item + c1FlexGrid1ComboBoxEditorSelectedItem)

C

Private Sub C1FlexGrid1_ComboCloseUp(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) MessageBoxShow(Selected Index amp c1FlexGrid1ComboBoxEditorSelectedIndex amp vbLf amp Selected Item + c1FlexGrid1ComboBoxEditorSelectedItem)End Sub

VBNET

マスク

Mask editor refers to pre-defined templates for getting input from users which also automatically validates the userinput as it is typed Mask strings have two types of characters literal characters and template characters While literalcharacters are the ones which become part of the input the template characters serve as placeholders for charactersbelonging to specific categories (for example digits or alphabets) For example the code below assigns a (999) 999-9999 editing mask to the first column which holds phone numbers Here special characters such as braces (()) andhyphen (-) are the literals and the digit 9 is a placeholder that stands for any digit

FlexGrid for WinForms

62 Copyright copy GrapeCity Inc All rights reserved

The FlexGrid control supports masked editing through the EditMask property which can be used with regular textfields and with drop-down combo fields To apply different masks within the same column you can trap the BeforEditevent and set the EditMask property to appropriate value

You can also set the EditMask property at design time using the Input Mask dialog You can access the dialog byclicking the ellipsis button against Edit Mask field in Column Tasks menu It also means that the Edit Mask field isspecific to the column selected at that time

Note that when the EditMask property is set to a non-empty string the grid uses the masked editor even if thecolumn contains DateTime values Usually grid uses the built-in Date editor to edit DateTime type cells

電話番号の編集マスクを設定します c1FlexGrid1Cols(1)EditMask = (999) 999-9999

C

電話番号の編集マスクを設定します c1FlexGrid1Cols(1)EditMask = (999) 999-9999

VBNET

マップリスト

Mapped lists refer to the mapping of data stored in the grid to the values visible to the user Such mapping is oftenused to display user-friendly values when actual data stored in the grid is either encoded or difficult to understand bythe user For instance in an employee record table it would be more convenient for administrative executive to seenames of the employees while database stores the employee IDs

FlexGrid for WinForms

63 Copyright copy GrapeCity Inc All rights reserved

Display Data MappingIn FlexGrid data mapping can be achieved by using the DataMap property This property contains reference to anIDictionary object that establishes mapping between database values and values to be displayed in the gridHashTable ListDictionary and SortedList are some examples of IDictionary objects which provide valid data maps

Following code demonstrates how to display the data mapped list in the WinForms FlexGrid

There is a difference in how HashTable ListDictionary and SortedList classes order the items So when these tables areused with editable columns the order of items rendering in the mapped list also differs depending upon the keys andclass used to create the list

Note that the keys in the data map must be of the same type as the cells being edited For example if a columncontains short integers (Int16) then any data maps associated with the column should have short integer keys

Display Image MappingTo display image mapping in a FlexGrid column you need to set the ImageMap property of Row or Column object toan IDictionary object that establishes mapping between images and the corresponding text values For example if acolumn contains country names you can use this property to display the corresponding flags You can controlwhether to show only images or images with text by using the ImageAndText property of the object

Create an image mapping in the WinForms FlexGrid using the code below

データマップを作成しますListDictionary customerNames = new ListDictionary()customerNamesAdd(AJK18F Sam Anders)customerNamesAdd(BBK21D Daneil)customerNamesAdd(AEF25N Henry Hussain)customerNamesAdd(BZD42S Owen Romanov)customerNamesAdd(AKC16G Serena Nguyen)

データマップをflexgrid列に割り当てますc1flexGrid1Cols[Name]DataMap = customerNames

C

データマップを作成しますDim customerNames As ListDictionary = New ListDictionary()customerNamesAdd(AJK18F Sam Anders)customerNamesAdd(BBK21D Daneil)customerNamesAdd(AEF25N Henry Hussain)customerNamesAdd(BZD42S Owen Romanov)customerNamesAdd(AKC16G Serena Nguyen)

データマップをflexgrid列に割り当てますc1flexGrid1Cols(Name)DataMap = customerNames

VBNET

Hashtable ht = new Hashtable() foreach (Row row in c1flexGrid1Rows) htAdd(row[CustomerID] LoadImage(row[Photo] as byte[])) ImageMapをPhoto列に割り当てます c1flexGrid1Cols[Photo]ImageMap = ht

C

FlexGrid for WinForms

64 Copyright copy GrapeCity Inc All rights reserved

アスペクト比を維持しながら画像をセルに合わせます c1flexGrid1Cols[Photo]ImageAlign = ImageAlignEnumScale c1flexGrid1Cols[Photo]Width = 80

Dim ht As Hashtable = New Hashtable()

For Each row As Row In c1flexGrid1Rows htAdd(row(CustomerID) LoadImage(TryCast(row(Photo) Byte()))) Next

ImageMapをPhoto列に割り当てます c1flexGrid1Cols(Photo)ImageMap = ht

アスペクト比を維持しながら画像をセルに合わせます c1flexGrid1Cols(Photo)ImageAlign = ImageAlignEnumScale c1flexGrid1Cols(Photo)Width = 80

VBNET

セルボタン

Cell button editor refers to a cell with an ellipsis button This editor comes to use when you need to get an operationdone or open a dialog on a button click Such dialogs generally contain multiple different options or settings for a userto choose from

Default Cell Button Cell Button with Text Cell Button with Custom Image

Display Cell ButtonIn FlexGrid you can display a cell button by setting the ComboList property to an ellipsis character You can alsouse a pipe character before ellipsis button to display an ellipsis with text box to let user enter his inputThe CellButtonClick event is fired when user clicks the cell button You can capture this event to implement thedesired operation or display a dialog of your choice

By default the cell button gets displayed when cell enters the edit mode However you can set the ShowButtonsproperty to Always to display the cell button even in non-edit mode

Use the code below to display cell button in a WinForms FlexGrid column

Mark列のComboListプロパティを設定してセルボタンを表示するようにします c1flexGrid1Cols[Mark]ComboList = セルボタンを常に表示できるようにします c1flexGrid1Cols[Mark]ShowButtons = ShowButtonsEnumAlways

エンドユーザーがセルボタンをクリックしたときに処理します c1flexGrid1CellButtonClick += C1flexGrid1_CellButtonClick

C

Mark列のComboListプロパティを設定してセルボタンを表示するようにしますc1flexGrid1Cols(Mark)ComboList =

VBNET

FlexGrid for WinForms

65 Copyright copy GrapeCity Inc All rights reserved

The ComboList property can also be set using the Combo List dialog at design time To access the Combo List dialog

1 Open the Column Tasks menu for column for which editor is to be set2 Go to the Combo List option and click the ellipsis button on the right hand side of the field3 Combo List dialog opens where you can specify the option values each in a new line4 You can also choose whether you want to display these values as an Ellipsis Button or Textbox amp Ellipsis

Button Note that it also gives you options to create Dropdown List and Dropdown Combo

The example below demonstrates change in back color and fore color of the current row on click of the cell buttonSimilarly you can perform the desired operation in the CellButtonClick event

セルボタンを常に表示できるようにしますc1flexGrid1Cols(Mark)ShowButtons = ShowButtonsEnumAlways

エンドユーザーがセルボタンをクリックしたときに処理しますc1flexGrid1CellButtonClick += C1flexGrid1_CellButtonClick

private void C1flexGrid1_CellButtonClick(object sender RowColEventArgs e) 次のコードは色を変更して現在の行をマークします if (c1flexGrid1Rows[eRow]StyleDisplayBackColor == ColorFromName(Window)) c1flexGrid1Rows[eRow]StyleNewBackColor = ColorGreen c1flexGrid1Rows[eRow]StyleNewForeColor = ColorWhite c1flexGrid1Rows[eRow]StyleNewBackColor = ColorFromName(Window) c1flexGrid1Rows[eRow]StyleNewForeColor = ColorFromName(WindowText)

C

FlexGrid for WinForms

66 Copyright copy GrapeCity Inc All rights reserved

Change Image of Cell ButtonBy default cell button displays an ellipsis However you can change the image of cell button usingthe CellButtonImage property

Set the image of cell button in the WinForms FlexGrid as shown in the code below

Private Sub C1flexGrid1_CellButtonClick(ByVal sender As Object ByVal e As RowColEventArgs) 次のコードは色を変更して現在の行をマークします If c1flexGrid1Rows(eRow)StyleDisplayBackColor Is ColorFromName(Window) Then c1flexGrid1Rows(eRow)StyleNewBackColor = ColorGreen c1flexGrid1Rows(eRow)StyleNewForeColor = ColorWhite End If

If True Then c1flexGrid1Rows(eRow)StyleNewBackColor = ColorFromName(Window) c1flexGrid1Rows(eRow)StyleNewForeColor = ColorFromName(WindowText) End IfEnd Sub

VBNET

CellButtonImageプロパティを設定してセルボタンの画像を定義しますImage imgCellBtn = new Bitmap(ResourcesImagesbuttonpng)c1flexGrid1CellButtonImage = imgCellBtn

C

CellButtonImageプロパティを設定してセルボタンの画像を定義しますDim imgCellBtn As Image = New Bitmap(ResourcesImagesbuttonpng)c1flexGrid1CellButtonImage = imgCellBtn

VBNET

検証

Data validation lets you control the data that a user can enter into a column cell There are various ways in which adata can be validated such as restricting invalid input keys showing the error or warning information or revert thevalue to original on getting an invalid input from the user

FlexGrid for WinForms

67 Copyright copy GrapeCity Inc All rights reserved

To implement validations such as specifying the range of acceptable values or defining the minimum string length ofinput FlexGrid provides EditorValidation property of the Column class The property is oftype ValidationRuleCollection class which consists of pre-defined rules for implementing enhanced data validation inFlexGrid columns For instance the sample code below demonstrates StringLength and Required validation rulesapplied to the Customer column using the EditorValidation property

Refer the code below to know how to add validation rules in WinForms FlexGrid columns

private void SetupGridColumns() var customerNameColumn = _flexCols[CustomerName] customerNameColumnCaption = Customer customerNameColumnEditorValidationAdd(new RequiredRule()) customerNameColumnEditorValidationAdd(new StringLengthRule() MinimumLength = 2 ) var customerIDColumn = _flexCols[CustomerID] customerIDColumnVisible = false var frequencyColumn = _flexCols[Frequency] frequencyColumnFormat = 0 frequencyColumnAllowEditing = false var ageColumn = _flexCols[Age] ageColumnEditorValidationAdd(new RequiredRule()) ageColumnEditorValidationAdd(new RangeRule() Minimum = 10 Maximum = 90 )

C

FlexGrid for WinForms

68 Copyright copy GrapeCity Inc All rights reserved

Another way of applying validation is by capturing the ValidateEdit event and checking the value of EditorTextproperty If value obtained is invalid set the Cancel parameter to true to keep the grid in editing mode until userenters a valid value Such validation can be used in scenarios such as setting the range of valid values validating thecurrent cell value based on another cell value For example the below sample code validates input into a currencycolumn to ensure that values entered are between 1000 and 10000

Use ValidateEdit event to check for valid values during edit mode of the WinForms FlexGrid cell as shown in the codebelow

Private Sub SetupGridColumns() Dim customerNameColumn = _flexCols(CustomerName) customerNameColumnCaption = Customer customerNameColumnEditorValidationAdd(New RequiredRule()) customerNameColumnEditorValidationAdd(New StringLengthRule() With MinimumLength = 2 ) Dim customerIDColumn = _flexCols(CustomerID) customerIDColumnVisible = False Dim frequencyColumn = _flexCols(Frequency) frequencyColumnFormat = 0 frequencyColumnAllowEditing = False Dim ageColumn = _flexCols(Age) ageColumnEditorValidationAdd(New RequiredRule()) ageColumnEditorValidationAdd(New RangeRule() With Minimum = 10 Maximum = 90 )End Sub

VBNET

private void _flex_ValidateEdit( object sender ValidateEditEventArgs e) 金額を検証します if (_flexCols[eCol]DataType == typeof(Decimal)) try Decimal dec = DecimalParse(_flexEditorText) if ( dec lt 1000 || dec gt 10000 ) MessageBoxShow(Value must be between 1000 and 10000) eCancel = true catch MessageBoxShow(Value not recognized as a Currency) eCancel = true

C

Private Sub _flex_ValidateEdit(ByVal sender As Object ByVal e As ValidateEditEventArgs)

VBNET

FlexGrid for WinForms

69 Copyright copy GrapeCity Inc All rights reserved

金額を検証します If _flexCols(eCol)DataType Is GetType(Decimal) Then

Try Dim dec As Decimal = DecimalParse(_flexEditorText)

If dec lt 1000 OrElse dec gt 10000 Then MessageBoxShow(Value must be between 1000 and 10000) eCancel = True End If

Catch MessageBoxShow(Value not recognized as a Currency) eCancel = True End Try End IfEnd Sub

データ注釈

Data annotation means adding meaningful metadata tags to the classes and other objects making it easier to bridgethe gap between models and views by performing data validation and displaying appropriate messages to the endusers For example you may use data annotations to specify how items should be formatted what their captionsshould be whether they should be editable or not

FlexGrid supports multiple data annotation attributes used for customizing data classes displaying data from sourceand setting validation rules To use the attributes in your project you need to add a reference to theSystemComponentModelDataAnnotations assembly and then add the attributes to your data objects in the code

Note The C1FlexGrid supports the annotations defined in NET 4SystemComponentModelDataAnnotations should be version 4000 or higher

Listed below are some of the major annotation attributes that are supported in FlexGrid control Cilck herefor complete list of DataAnnotation attributes

FlexGrid for WinForms

70 Copyright copy GrapeCity Inc All rights reserved

Attribute Name Functionality in FlexGrid

Association Specifies that an entity member represents a data relationship such as a foreignkey relationship

Display Provides a general-purpose attribute that lets you specify localizable strings fortypes and members of entity partial classes

DisplayFormat Specifies how data fields are displayed and formatted by ASPNET Dynamic Data

DisplayColumn Specifies the column that is displayed in the referred table as a foreign-keycolumn

Editable Indicates whether a data field is editable

Key Denotes one or more properties that uniquely identify an entity

Validation

RequiredAttributeStringLengthAttributeRangeAttributeRegularExpressionAttributeMinLengthAttributeMetaDataAttributeMaxLengthAttributeEmailAddressAttributeCompareAttributeDataTypeAttribute

The data annotation validation attributes are used as validation rules in FlexGridoperations

The following code example shows how data annotation feature works in WinForms FlexGrid control

自動生成されたCustomerName列ヘッダに「Customer」と表示されます この列には少なくとも2つの記号の長さが最小の空でない文字列も必要です[Display(Name = Customer)][Required][StringLength(intMaxValue MinimumLength = 2)]

public string CustomerName get set 自動生成されたCustomerID列は非表示になります[Display(AutoGenerateField = false)]public int CustomerID get set

自動生成された「Frequency」列にはパーセンテージで書式設定された値が表示されます また編集を許可しません[DisplayFormat(DataFormatString = 0)][Editable(false)]public double Frequency get set

自動生成された「Age」列は事前定義された範囲の値を許可します[Required][Range(10 90)]public int Age get set サンプルデータを作成しますpublic static BindingListltDatagt GetSampleData(int cnt) var list = new BindingListltDatagt() var rnd = new Random()

C

FlexGrid for WinForms

71 Copyright copy GrapeCity Inc All rights reserved

for (int i = 0 i lt cnt i++) var item = new Data() itemCustomerName = _firstNames[rndNext(0 _firstNamesLength)] + + _lastNames[rndNext(0 _lastNamesLength)] itemCustomerID = i itemFrequency = rndNextDouble() itemAge = rndNext(10 91) listAdd(item) return list

自動生成されたCustomerName列ヘッダに「Customer」と表示されます この列には少なくとも2つの記号の長さが最小の空でない文字列も必要です ltDisplay(Name=Customer)gt ltRequiredgt ltStringLength(IntegerMaxValue MinimumLength=2)gt Public Property CustomerName As String 自動生成されたCustomerID列は非表示になります ltDisplay(AutoGenerateField=False)gt Public Property CustomerID As Integer 自動生成された「Frequency」列にはパーセンテージで書式設定された値が表示されます また編集を許可しません ltDisplayFormat(DataFormatString=0)gt ltEditable(False)gt Public Property Frequency As Double 自動生成された「Age」列は事前定義された範囲の値を許可します ltRequiredgt ltRange(10 90)gt Public Property Age As Integer

サンプルデータを作成します Public Shared Function GetSampleData(ByVal cnt As Integer) As BindingList(Of Data) Dim list = New BindingList(Of Data)() Dim rnd = New Random()

For i As Integer = 0 To cnt - 1 Dim item = New Data() itemCustomerName = _firstNames(rnd[Next](0 _firstNamesLength)) amp + _lastNames(rnd[Next](0 _lastNamesLength)) itemCustomerID = i itemFrequency = rndNextDouble() itemAge = rnd[Next](10 91) listAdd(item) Next

Return list End Function

VBNET

スパークライン

Sparklines are the miniature charts visually representing a series of values to show trends such as periodic fluctuationsor to highlight maximum or minimum values of the data series In grids sparklines are specially useful as they easily fitin a single cell and can help identify the data patterns at a glance

FlexGrid for WinForms

72 Copyright copy GrapeCity Inc All rights reserved

FlexGrid for WinForms lets you display sparklines in columns by setting ShowSparkline property of the Column classto true You can also set the type of sparkline using SparklineType property of the Sparkline class FlexGrid supportsthree types of sparklines which are

Line Similar to line chart line sparkline indicates change in values over a period of time with the help of a lineColumn Similar to column charts column sparkline uses vertical columns to demonstrate pattern acrossdifferent categoriesWinLoss Similar to column sparkline winloss sparkline uses vertical columns to represent values However itdoes not indicate the magnitude and is generally used to indicate the binary data

To display the data markers on sparkline you can set the ShowMarkers property to true The Sparkline class alsoprovides properties to highlight the first last highest lowest or negative data points by displaying them in differentformat You can even style the sparklines using the Styles property

Below code shows how to add sparkline to the WinForms FlexGrid columns

WinLossSparklineを表示するようにプロパティを設定します c1FlexGrid1Cols[2]ShowSparkline = true c1FlexGrid1Cols[2]SparklineSparklineType = SparklineTypeWinLoss c1FlexGrid1Cols[2]SparklineStylesSeriesColor = ColorGreen c1FlexGrid1Cols[2]SparklineShowNegative = true

C

WinLossSparklineを表示するようにプロパティを設定します c1FlexGrid1Cols(2)ShowSparkline = True c1FlexGrid1Cols(2)SparklineSparklineType = SparklineTypeWinLoss c1FlexGrid1Cols(2)SparklineStylesSeriesColor = ColorGreen c1FlexGrid1Cols(2)SparklineShowNegative = True

VBNET

ヘッダとフッタ

Column header refers to the fixed rows on the top of the grid which contains a caption string sort glyph etc

In FlexGrid by default the top row with zero index is allocated for the column header However you can span the header to other rows aswell by specifying them as fixed To set more than one rows as fixed you need to set the Fixed property of RowCollection class to an integergreater than 1

FlexGrid for WinForms

73 Copyright copy GrapeCity Inc All rights reserved

Set Header TextFlexGrid when in bound mode reads the field names from the data source and renders them as column header text However youcan explicitly set Caption property of the Row class to overwrite field name string from the data source In case of unbound grid as well theCaption property specifies the header text Note that this property sets the value of cells in the default header row at zero index To setvalue in the other fixed row cells you need to use the usual value allocation ways of FlexGrid For more information on how to set cellvalues see Set Value in Cell

Specify the header rows and set the header text in WinForms FlexGrid using the code below

Merge Column HeaderFlexGrid provides the AllowMerging property for Row object which specifies whether it is allowed to merge cells in a particular row (in thiscase the header row) or not Once you have allowed merging in the header row set either AllowMerging or AllowMergingFixed propertyof C1FlexGrid class to FixedOnly Availability of these two properties in the FlexGrid control offers you more flexibility to implement multiplelogics related to merging For more information on merging cells see Merge

Use the code below to merge column headers in the WinForms FlexGrid

Wrap Column Header Text

2つの行を列ヘッダ行として設定しますc1FlexGrid1RowsFixed = 2 最初の列のヘッダとサブヘッダを設定しますc1FlexGrid1Cols [1] Caption = Column Header 1c1FlexGrid1 [11] = Column Sub-header 1

C

2つの行を列ヘッダー行として設定します c1FlexGrid1RowsFixed = 2

最初の列のヘッダとサブヘッダを設定します c1FlexGrid1Cols(1)Caption = Column Header 1 c1FlexGrid1(1 1) = Column Sub-header 1

VBNET

ヘッダ行でのマージを許可しますc1FlexGrid1Rows[0]AllowMerging = true

グリッドのAllowMergingまたはAllowMergingFixedプロパティを設定して固定行のみを結合します c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

ヘッダ行でのマージを許可しますc1FlexGrid1Rows(0)AllowMerging = True

グリッドのAllowMergingまたはAllowMergingFixedプロパティを設定して固定行のみを結合します c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

FlexGrid for WinForms

74 Copyright copy GrapeCity Inc All rights reserved

To wrap the text in column header access the CellStyle item Fixed of the CellStyleCollection class and set its WordWrap property totrue Note that to view the wrapped text properly you need to adjust the row height or just call the AutoSizeRow() method to automaticallyresize the row according to the text length

Use the code below to wrap header text of the WinForms FlexGrid columns

Style Column HeaderTo style the column header you can access the CellStyle item Fixed of the CellStyleCollection class and set various styling relatedproperties for same such as Font ForeColor and TextEffect

Customize column header of the WinForms FlexGrid using the code below

Set Column FooterColumn Footer refers to the last row of the grid which displays additional information about the whole column Most common use ofcolumn footer is to show the summary of column data

In FlexGrid you can create the column footer by using Footers property of the C1FlexGrid class FlexGrid lets you choose whether toscroll the footer along with rows or keep it fixed at the bottom of the grid by using Fixed property of the Footers class This class alsoprovides the Descriptions property which accesses the FooterDescription collection to set the additional information such as Caption Todisplay aggregate result in the column footer through various aggregate functions you must access the AggregateDefinition collection

列のキャプションを設定しますc1FlexGrid1Cols[3]Caption = Large Text for Column Header Text Wrapping

行の高さを設定しますc1FlexGrid1Rows[0]Height = 50

固定の行と列のワードラップを設定しますc1FlexGrid1Styles[Fixed]WordWrap = true

C

列のキャプションを設定しますc1FlexGrid1Cols(3)Caption = Large Text for Column Header Text Wrapping

行の高さを設定しますc1FlexGrid1Rows(0)Height = 50

固定の行と列のワードラップを設定しますc1FlexGrid1Styles(Fixed)WordWrap = True

VBNET

ヘッダテキストのフォントを設定しますc1FlexGrid1Styles[Fixed]Font = new Font(Tahoma 10 FontStyleBold) ヘッダテキストの前色を設定しますc1FlexGrid1Styles[Fixed]ForeColor = ColorAqua ヘッダーテキストの背景色を設定しますc1FlexGrid1Styles[Fixed]BackColor = ColorBlue

ヘッダテキストにテキスト効果を適用しますc1FlexGrid1Styles[Fixed]TextEffect = C1WinC1FlexGridTextEffectEnumRaised

C

ヘッダテキストのフォントを設定します c1FlexGrid1Styles(Fixed)Font = New Font(Tahoma 10 FontStyleBold)

ヘッダテキストの前色を設定します c1FlexGrid1Styles(Fixed)ForeColor = ColorAqua

ヘッダーテキストの背景色を設定します c1FlexGrid1Styles(Fixed)BackColor = ColorBlue

ヘッダテキストにテキスト効果を適用します c1FlexGrid1Styles(Fixed)TextEffect = C1WinC1FlexGridTextEffectEnumRaised

VBNET

FlexGrid for WinForms

75 Copyright copy GrapeCity Inc All rights reserved

using Aggregates property of the FooterDescription class Aggregate functions can be specified using the Aggregate property whichaccepts values from AggregateEnum enumeration

Following code shows how to add a column footer in the WinForms FlexGrid

列にフッタを追加しますc1FlexGrid1FootersDescriptionsAdd(new C1WinC1FlexGridFooterDescription() Caption = Total ) フッタに集計を適用しますc1FlexGrid1FootersDescriptions[0]AggregatesAdd(new C1WinC1FlexGridAggregateDefinition() Column = 4 Aggregate = C1WinC1FlexGridAggregateEnumSum )

C

列にフッタを追加しますc1FlexGrid1FootersDescriptionsAdd(New C1WinC1FlexGridFooterDescription() With Caption = Total )

フッタに集計を適用しますc1FlexGrid1FootersDescriptions(0)AggregatesAdd(New C1WinC1FlexGridAggregateDefinition() With Column = 4 Aggregate = C1WinC1FlexGridAggregateEnumSum )

VBNET

サイズ変更

Set Column WidthFlexGrid provides the DefaultSize property of ColumnCollection class to set the column width across the grid You canalso specify the width of a particular column by setting the Width property of the Column class Default value ofWidth property is -1 which indicates that the column is taking width specified by the DefaultSize property The Widthproperty is also available at design time through the C1FlexGrid Column Editor For more information on columneditor see Editors

Use the code below to set the default width of a column of the WinForms FlexGrid

Auto-adjust Column WidthTo adjust the column width according to the text length FlexGrid provides the AutoSizeCol() and AutoSizeCols()methods While AutoSizeCol() method automatically adjusts width of the specified column the AutoSizeCols()method is used for cell ranges

Following code shows how you can auto adjust the column widths according to the text length in the WinFormsFlexGrid

すべての列のデフォルト幅を設定しますc1FlexGrid1ColsDefaultSize = 110最初の列の幅を設定しますc1FlexGrid1Cols [1] Width = 30

C

すべての列のデフォルト幅を設定します c1FlexGrid1ColsDefaultSize = 110最初の列の幅を設定します c1FlexGrid1Cols(1)Width = 30

VBNET

FlexGrid for WinForms

76 Copyright copy GrapeCity Inc All rights reserved

Set MinMax Column WidthFlexGrid allows you to set bounds to the column width by using the MinSize and MaxSize propertiesof ColumnCollection This feature is especially useful in scenarios such as when AllowResizing property is set to trueor while using the AutoSizeCol or AutoSizeCols method

Specify the bounds of column width in the WinForms FlexGrid using the code below

Star SizingStar sizing refers to proportional sizing of grid columns to occupy the available space so that layout of grid remainssame even on resizing For instance consider a grid with 5 columns whose star sizes are specified as 3 2 and In this case first fourth and fifth column always take the same width and grid allocates thrice the width of firstcolumn to the second and twice the width to third column

テキストの長さに応じて最初の列の幅を自動調整しますc1FlexGrid1AutoSizeCol(1) 列の幅を1番目から4番目まで自動調整しますc1FlexGrid1AutoSizeCols(1 4 2)

すべての列の幅を自動調整します c1FlexGrid1AutoSizeCols()

C

テキストの長さに応じて最初の列の幅を自動調整しますc1FlexGrid1AutoSizeCol(1)

列の幅を1番目から4番目まで自動調整しますc1FlexGrid1AutoSizeCols(1 4 2)

すべての列の幅を自動調整します c1FlexGrid1AutoSizeCols()

VBNET

列コレクションの最小幅を設定します c1FlexGrid1ColsMinSize = 20 列コレクションの最大幅を設定します c1FlexGrid1ColsMaxSize = 60

C

列コレクションの最小幅を設定します c1FlexGrid1ColsMinSize = 20

列コレクションの最大幅を設定します c1FlexGrid1ColsMaxSize = 60

VBNET

FlexGrid for WinForms

77 Copyright copy GrapeCity Inc All rights reserved

FlexGrid provides the StarWidth property of Column class to specify the star sizes of columns To restrict the widthsfrom getting too narrow or too wide you can set the MinWidth and MaxWidth properties These properties are alsoavailable through the C1FlexGrid Column Editor For more information on column editor see Editors

Set star sizing or proportional sizing in the WinForms FlexGrid columns using the code below

列のスターサイズを設定しますc1FlexGrid1Cols[1]StarWidth = c1FlexGrid1Cols[2]StarWidth = 3c1FlexGrid1Cols[3]StarWidth = 2c1FlexGrid1Cols[4]StarWidth = c1FlexGrid1Cols[5]StarWidth =

列が狭くなりすぎないようにMinWidthプロパティを設定しますc1FlexGrid1Cols[1]MinWidth = 50

C

列のスターサイズを設定しますc1FlexGrid1Cols(1)StarWidth = c1FlexGrid1Cols(2)StarWidth = 3c1FlexGrid1Cols(3)StarWidth = 2c1FlexGrid1Cols(4)StarWidth = c1FlexGrid1Cols(5)StarWidth =

列が狭くなりすぎないようにMinWidthプロパティを設定しますc1FlexGrid1Cols(1)MinWidth = 50

VBNET

FlexGrid for WinForms

78 Copyright copy GrapeCity Inc All rights reserved

A grid control is a collection of rows and columns Columns generally contain a particular type of information through out while rows are used to recorddifferent types of information about a particular item

In FlexGrid the collection of rows is represented by the RowCollection class which can be accessed through Rows property of the C1FlexGrid class Thissection discusses the various operations that can be performed on rows

Topic Snapshot Content

Basic Operations Discusses about how to perform basic row operations

Set Row CountAdd RowDelete RowInsert RowSet Data TypeSet Fixed RowSet Frozen Row

User Interaction Discusses about operations that can be performed by the end-user at run time

Allow AddingAllow DeletingAllow DraggingAllow FreezingAllow Resizing

Header Discusses about how to set row header and perform other related operations

Set Header TextMerge Row HeaderWrap Row Header TextStyle Row Header

Row Detail Discusses how to display additional information using row detail feature

In-form EditingHierarchical ViewCustom Row Details

Sizing Discusses about various aspects of row sizing

Set Row HeightAuto-adjust Row HeightSet MinMax Row Height

基本操作

This topic discusses various basic operations which can be performed on a row

Set Row CountWhen grid is bound to a data source the number of rows is determined by the number of records available in thedata source However in the case of unbound mode you can set any integer value in Count property ofthe RowCollection class to set the number of rows to be displayed in the grid

Use the code below to set row count in the WinForms FlexGrid

Set row count c1FlexGrid1RowsCount = 15

C

VBNET

FlexGrid for WinForms

79 Copyright copy GrapeCity Inc All rights reserved

Add RowFlexGrid provides various ways to add a new row at runtime You can either use Add method of the RowCollectionclass or AddItem method of the C1FlexGrid class to add a new record In the unbound mode you can also incrementthe value of Count property to add new rows Note that all these ways add rows towards the end of the grid To inserta row at a specific location see Insert Row Also note that an exception is thrown if a new row is added to a boundgrid using Count property

Add a row to WinForms FlexGrid using any of these approaches shown in the code below

Delete RowTo delete a particular row from the grid you can use Remove method of the RowCollection class and specify the rowyou want to delete as its parameter The RowCollection class also provides RemoveRange method which allows you

Set row countc1FlexGrid1RowsCount = 15

Approach1 Use the RowCollectionAdd method to add row C1WinC1FlexGridRow r r = c1FlexGrid1RowsAdd() Set data r[1] = New Row 2

Approach2 Use AddItem method to add row and set data c1FlexGrid1AddItem( + t + New Row 1) Approach3 Use the RowCollectionCount property to add row c1FlexGrid1RowsCount += 1 Set data c1FlexGrid1[c1FlexGrid1RowsCount - 1 1] = New Row 3

C

Approach1 Use the RowCollectionAdd method to add row Dim r As C1WinC1FlexGridRow r = c1FlexGrid1RowsAdd()

Set data r(1) = New Row 2

Approach2 Use AddItem method to add row and set data c1FlexGrid1AddItem( amp vbTab amp New Row 1)

Approach3 Use the RowCollectionCount property to add row c1FlexGrid1RowsCount += 1

Set data c1FlexGrid1(c1FlexGrid1RowsCount - 1 1) = New Row 3

VBNET

FlexGrid for WinForms

80 Copyright copy GrapeCity Inc All rights reserved

to remove a range of rows using a single call Similarly you can also use RemoveItem method of the C1FlexGridclass to remove a specific row In the unbound grid you can reduce the number of rows by changing the value ofCount property

Following code gives different approaches to delete row from the WinForms FlexGrid

Insert RowTo insert a row in FlexGrid at a specific location you can use Insert method of the RowCollection class which lets youspecify the position where rows are to be inserted You can also insert multiple rows in the grid by usingthe InsertRange method

Below code demonstrates how to insert a row at a particular position in the WinForms FlexGrid

Approach1 Remove second row using RowCollectionRemove methodc1FlexGrid1RowsRemove(2)

Approach1 Remove second row using the RemoveItem methodc1FlexGrid1RemoveItem(2)

Approach3 Remove 3 rows starting from second using the RemoveRange methodc1FlexGrid1RowsRemoveRange(2 3) Approach4 Remove last row using the RowCollectionCount property c1FlexGrid1RowsCount -= 1

C

Approach1 Remove second row using RowCollectionRemove method c1FlexGrid1RowsRemove(2)

Approach1 Remove second row using the RemoveItem method c1FlexGrid1RemoveItem(2)

Approach3 Remove 3 rows starting from second using the RemoveRange method c1FlexGrid1RowsRemoveRange(2 3)

Approach4 Remove last row using the RowCollectionCount property c1FlexGrid1RowsCount -= 1

VBNET

C1WinC1FlexGridRow r Approach1 Use the Insert method to insert row at second position r = c1FlexGrid1RowsInsert(2) r[1] = Inserted row Approach2

C

FlexGrid for WinForms

81 Copyright copy GrapeCity Inc All rights reserved

Set Data TypeIn case of a bound FlexGrid data type of each bound column is automatically picked from the data source dependingon the data However in the case of unbound mode you can set the data type of rows or columns by specifyingthe DataType property of Row or Column class respectively Note that when data type is set for both rows andcolumns column settings take preference over row settings

Use the code below to set data type of a WinForms FlexGrid row

Set Fixed RowFixed rows refer to the rows with non-editable cells which are always visible on top of the grid even when user scrollsdown the grid In FlexGrid fixed rows can be set using Fixed property of the RowCollection class This propertyaccepts an integer value that specifies the number of rows to be fixed

Set fixed rows in the WinForms FlexGrid using the code below

Set Frozen RowFrozen rows similar to fixed rows are non-scrollable but can be edited by the user In FlexGrid frozen rows can be set

Use the InsertRange method to add three rows at second position c1FlexGrid1RowsInsertRange(2 3)

Dim r As C1WinC1FlexGridRow Approach1 Use the Insert method to insert row at second position r = c1FlexGrid1RowsInsert(2) r(1) = Inserted row

Approach2 Use the InsertRange method to add three rows at second position c1FlexGrid1RowsInsertRange(2 3)

VBNET

C1WinC1FlexGridRow r r = c1FlexGrid1RowsAdd() rDataType = typeof(int)

C

Dim r As C1WinC1FlexGridRow r = c1FlexGrid1RowsAdd() rDataType = GetType(int)

VBNET

Set three rows as fixed c1FlexGrid1RowsFixed = 3

C

Set three rows as fixedc1FlexGrid1RowsFixed = 3

VBNET

FlexGrid for WinForms

82 Copyright copy GrapeCity Inc All rights reserved

by using Frozen property provided by the RowCollection class

Use the code below to set frozen rows in the WinForms FlexGrid

Set first two rows as frozen c1FlexGrid1RowsFrozen = 2

C

Set first two rows as frozen c1FlexGrid1RowsFrozen = 2

VBNET

ユーザー操作

This topic discusses how you can let end-users interact with the FlexGrid rows

Allow AddingBy default FlexGrid does not allow end-user to add new row to the grid To provide an option to add rows at runtimeyou can set AllowAddNew property of the C1FlexGrid class to true FlexGrid also provides a design-time optionEnable Adding Rows in C1FlexGrid Tasks menu to allow adding new row by the end-user For more information ontask menus see Tasks Menus Moreover you can also set watermark text to be displayed in the new row templatethrough NewRowWatermark property

Use the code below to allow users to add rows in WinForms FlexGrid at run-time

Allow user to add rows c1FlexGrid1AllowAddNew = true Set watermark in the template new row c1FlexGrid1NewRowWatermark = Add new row

C

Allow user to add rows c1FlexGrid1AllowAddNew = True

Set watermark in the template new row

VBNET

FlexGrid for WinForms

83 Copyright copy GrapeCity Inc All rights reserved

Allow DeletingFlexGrid by default does not allow end-user to delete rows from the grid However if your application requires youcan let the end-user delete the selected rows through Delete key by setting AllowDelete property to true You canalso enable row deletion by checking ON the Enable Deleting Rows checkbox on the C1FlexGrid Tasks menu

Following code shows how to allow users to delete rows from WinForms FlexGrid at run-time

Allow DraggingFlexGrid by default does not allow user to rearrange rows by dragging However you can change this behavior inunbound grid by using the FlexGridAllowDragging property and RowAllowDragging property To enable dragging ofgrid rows you can set the FlexGridAllowDragging property to either Rows or Both This property accepts the valuesfrom AllowDraggingEnum You can also disable dragging of a particular row by setting the RowAllowDraggingproperty to false

Note As moving a row is not allowed in bound mode the bound grid throws an exception on dragging arow To implement dragging in bound mode see the blog Drag and Drop Rows in C1Flexgrid

Let users drag the rows in an unbound WinForms FlexGrid at run-time by using the code below

Allow FreezingTo allow end user to freeze the rows at runtime you can use AllowFreezing property of the C1FlexGrid class whichaccepts values from AllowFreezingEnum When this property is set to Rows or Both a lock sign appears when mouseis hovered over the edge of header row End-user can click and drag the lock sign to freeze the rows

Use the code below to allow your users to freeze the WinForms FlexGrid rows at run-time

c1FlexGrid1NewRowWatermark = Add new row

Allow user to delete rowsc1FlexGrid1AllowDelete = true

C

Allow user to delete rowsc1FlexGrid1AllowDelete = True

VBNET

Allow dragging of all rows across the grid c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumRows Disable dragging of a particular row c1FlexGrid1Rows[3]AllowDragging = false

C

Allow dragging of all rows across the grid c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumRows

Disable dragging of a particular row c1FlexGrid1Rows(3)AllowDragging = False

VBNET

FlexGrid for WinForms

84 Copyright copy GrapeCity Inc All rights reserved

Allow ResizingBy default FlexGrid does not give option to resize the rows To change this behavior you can use AllowResizingproperty of the C1FlexGrid class This property accepts values from the AllowResizingEnum enumerationwhich enables end-user to change size of columns rows or both The enumeration also gives you options touniformly resize the rows columns or both that is if you resize one of the columns or rows the grid automaticallyresizes rest of the columns or rows as well FlexGrid also provides RowAllowResizing property which is Boolean typeand lets you enable or disable resizing of a particular row

Following code shows how to allow users to resize the WinForms FlexGrid rows at run-time

Allow freezing of rows at runtimec1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumRows

C

Allow freezing of rows at runtimec1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumRows

VBNET

Allow user to resize rows c1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumRows Stop user from resizing second row c1FlexGrid1Rows[2]AllowResizing = false

C

Allow user to resize rows c1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumRows

Stop user from resizing second row c1FlexGrid1Rows(2)AllowResizing = False

VBNET

ヘッダ

Row header refers to the fixed rows on the left hand side of the grid which may or may not contain the caption string

In FlexGrid by default the left most column with zero index is allocated for the row header However you can span theheader to other columns as well by specifying them as fixed To set more than one column as fixed you need toset the Fixed property of ColumnCollection class to an integer greater than 1

FlexGrid for WinForms

85 Copyright copy GrapeCity Inc All rights reserved

Set Header TextTo set the row header text you can set Caption property of the Row class Note that this property sets the value of cellsin the default header column at zero index To set value in the other fixed column cells you need to use the usual valueallocation ways of FlexGrid For more information on how to set cell values see Set Value in Cell

Specify the header column and set the header text in WinForms FlexGrid using the code below

Merge Row HeaderFlexGrid provides AllowMerging property of the Column class which specifies whether it is allowed to merge cells in aparticular column (in this case the header column) or not Once you have allowed merging in the header columnset either AllowMerging or AllowMergingFixed property of the C1FlexGrid class to FixedOnly Availability of these twoproperties in the FlexGrid control offers you more flexibility to implement multiple logics related to merging For moreinformation on merging cells see Merge

Set header for first rowc1FlexGrid1Rows[1]Caption = Row 1

Set header for all rowsfor (int i = c1FlexGrid1RowsFixed i lt c1FlexGrid1RowsCount i++) c1FlexGrid1[i 0] = Row + iToString()

Set column widthc1FlexGrid1Cols[0]Width = 85

C

Set header for first row c1FlexGrid1Rows(1)Caption = Row 1

Set header for all rows For i As Integer = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 c1FlexGrid1(i 0) = Row amp iToString() Next

Set column width c1FlexGrid1Cols(0)Width = 85

VBNET

FlexGrid for WinForms

86 Copyright copy GrapeCity Inc All rights reserved

Use the code below to merge row headers in the WinForms FlexGrid

Wrap Row Header TextTo wrap the text in row header access the CellStyle item Fixed of the CellStyleCollection class and set its WordWrapproperty to true Note that to view the wrapped text properly you need to adjust height of FlexGrid rows or just callthe AutoSizeRow() method to automatically resize the rows according to the length of text

Use the code below to wrap header text of the WinForms FlexGrid rows

Style Row HeaderTo style the row header you can access the CellStyle item Fixed of the CellStyleCollection class and set variousstyling related properties for same such as Font ForeColor and TextEffect

Allow merging on the header columnc1FlexGrid1Cols[0]AllowMerging = true

Set AllowMerging or AllowMergingFixed property of the grid to merge fixed rowcolumns only c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

Allow merging on the header columnc1FlexGrid1Cols(0)AllowMerging = True

Set AllowMerging or AllowMergingFixed property of the grid to merge fixed rowcolumns only c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

Set row captionc1FlexGrid1Rows[3]Caption = Large text to display text wrapping and mergingc1FlexGrid1Rows[4]Caption = Large text to display text wrapping and merging Set row heightc1FlexGrid1Rows[3]Height = 35c1FlexGrid1Rows[4]Height = 35

Set word wrapping for fixed rows and columnsc1FlexGrid1Styles[Fixed]WordWrap = true

C

Set row captionc1FlexGrid1Rows(3)Caption = Large text to display text wrapping and mergingc1FlexGrid1Rows(4)Caption = Large text to display text wrapping and merging

Set row heightc1FlexGrid1Rows(3)Height = 35c1FlexGrid1Rows(4)Height = 35

Set word wrapping for fixed rows and columnsc1FlexGrid1Styles(Fixed)WordWrap = True

VBNET

FlexGrid for WinForms

87 Copyright copy GrapeCity Inc All rights reserved

Customize row header of the WinForms FlexGrid using the code below

Set font of the header textc1FlexGrid1Styles[Fixed]Font = new Font(Tahoma 10 FontStyleBold) Set forecolor of the header textc1FlexGrid1Styles[Fixed]ForeColor = ColorPaleVioletRed Set backcolor of the header textc1FlexGrid1Styles[Fixed]BackColor = ColorLemonChiffon Apply text effect on the header textc1FlexGrid1Styles[Fixed]TextEffect = C1WinC1FlexGridTextEffectEnumInset

C

Set font of the header text c1FlexGrid1Styles(Fixed)Font = New Font(Tahoma 10 FontStyleBold)

Set forecolor of the header text c1FlexGrid1Styles(Fixed)ForeColor = ColorPaleVioletRed

Set backcolor of the header text c1FlexGrid1Styles(Fixed)BackColor = ColorLemonChiffon

Apply text effect on the header text c1FlexGrid1Styles(Fixed)TextEffect = C1WinC1FlexGridTextEffectEnumInset

VBNET

行の詳細

Row detail is a feature to provide additional information related to a row or record in the form of another expandablelayer In such case row which is the first layer contains the basic information while the second layer contains the detailedinformation This feature is specially useful when the additional information is too large to be displayed in the availablescreen space or it is not consistent for every record

FlexGrid for WinForms

88 Copyright copy GrapeCity Inc All rights reserved

FlexGrid provides the row detail feature using IC1FlexGridRowDetail interface which is implemented by the detail controls tobe hosted on detail row In addition FlexGrid also provides a separate assembly C1WinC1FlexGridRowDetails452dllto provide template user controls InputPanel and FlexGrid ready to be used in detail row You can add details section toany row in FlexGrid which enables you to group data in a template which is visible optionally This allows users to viewadditional data related to a row by simply selecting the row The grid also provides built-in expand or collapse buttons tocontrol the visibility of data within the expandable row

Some common use case scenarios of row detail feature are

1 In-form editing where an InputPanel control is hosted to get input from the user to fill information in a record2 Hierarchical grid which contains a master grid and a detail grid to show additional information about the record3 Custom row details where any control can be used to create row detail template

Detailed implementation of these scenarios is given in their respective sections below

In-form EditingFlexGrid supports in-form editing by hosting InputPanel control in detail row The InputPanel control contains data fieldswhere user can enter or edit the values like a form Once user finishes editing fields those values get reflected in theselected row

FlexGrid for WinForms

89 Copyright copy GrapeCity Inc All rights reserved

In FlexGrid you can implement in-form editing by adding reference to C1WinC1FlexGridRowDetails452dll and usingthe C1InputPanelRowDetail class which already implements the IC1FlexGridRowDetail interface The instance of this classis then assigned to RowDetailProvider property of the C1FlexGrid class which adds the InputPanel control to detail rowand enables the in-form editing

Hierarchical ViewHierarchical view refers to master-detail model where top level grid is the master grid and nested grid is the detail gridwhich displays additional information about expanded row of the master grid For instance example below demonstratesthe master-detail structure using Customer and Order tables respectively with CustomerID as common data element todefine a relation

flexGridRowDetailProvider = (g r) =gt new C1InputPanelRowDetail()flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected

C

flexGridRowDetailProvider = Function(g r) New C1InputPanelRowDetail()flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected

VBNET

FlexGrid for WinForms

90 Copyright copy GrapeCity Inc All rights reserved

In FlexGrid you can implement hierarchical grid by adding reference to C1WinC1FlexGridRowDetails452dll and usingthe C1FlexGridRowDetail class which already implements the IC1FlexGridRowDetail interface The instance of this class isthen assigned to RowDetailProvider property of the C1FlexGrid class to nest another grid in the detail row which enablesthe hierarchical grid interface

private void FlexGrid_Load(object sender EventArgs e) string conn = UtilGetConnectionString() var ds = new DataSet() string[] tables = Customers OrdersSplit() foreach (string tableName in tables) UtilFillTable(ds tableName conn) Defining relation between master and detail grid dsRelationsAdd(Customers_Orders dsTables[Customers]Columns[CustomerID] dsTables[Orders]Columns[CustomerID]) flexGridDataSource = ds flexGridDataMember = Customers flexGridRowDetailProvider = (g r) =gt new C1FlexGridRowDetail() flexGridAreRowDetailsFrozen = false

C

Private Sub FlexGrid_Load(ByVal sender As Object ByVal e As EventArgs) Dim conn As String = UtilGetConnectionString() Dim ds = New DataSet() Dim tables As String() = Customers OrdersSplit(c)

For Each tableName As String In tables UtilFillTable(ds tableName conn) Next Defining relation between master and detail grid dsRelationsAdd(Customers_Orders dsTables(Customers)Columns(CustomerID) dsTables(Orders)Columns(CustomerID))

VBNET

FlexGrid for WinForms

91 Copyright copy GrapeCity Inc All rights reserved

Custom Row DetailsIn addition to the InputPanel and FlexGrid control you can also host a custom control in the detail row of a grid Forinstance in the example below a text label control is attached to the row to enlist the additional information withoutaffecting the dimensions of the grid

To implement the custom row details in FlexGrid you need to create a user control which implementsthe IC1FlexGridRowDetail interface For instance here we have created a class named CustomRowDetail which representsthe text label control to be hosted in the detail row You then need to assign an object of this class to RowDetailProviderproperty of the C1FlexGrid class to enable the custom control to display additional information in the detail row

flexGridDataSource = ds flexGridDataMember = Customers flexGridRowDetailProvider = Function(g r) New C1FlexGridRowDetail() flexGridAreRowDetailsFrozen = False End Sub

private void CustomSample_Load(object sender EventArgs e) flexGridDataSource = DemoDataSource(Employees) flexGridRowDetailProvider = (g r) =gt new CustomRowDetail() flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected flexGridCols[Notes]Visible = false

Custom row detail class which shows label with notes about employee public class CustomRowDetail C1Label IC1FlexGridRowDetail Used to setup control before showing the FlexGrid detail control void IC1FlexGridRowDetailSetup(C1FlexGrid parentGrid int rowIndex) var bs = new BindingSource(parentGridDataSource parentGridDataMember) bsPosition = parentGridRows[rowIndex]DataIndex DataField = Notes DataSource = bs

C

FlexGrid for WinForms

92 Copyright copy GrapeCity Inc All rights reserved

Used to update size of the FlexGrid detail control void IC1FlexGridRowDetailUpdateSize(C1FlexGrid parentGrid int rowIndex Size proposedSize) var srSz = parentGridScrollableRectangleSize var sz = TextRendererMeasureText(Text Font srSz TextFormatFlagsWordBreak) szWidth = MathMax(szWidth srSzWidth) Size = sz

Private Sub CustomSample_Load(ByVal sender As Object ByVal e As EventArgs) flexGridDataSource = DemoDataSource(Employees) flexGridRowDetailProvider = Function(g r) New CustomRowDetail() flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected flexGridCols(Notes)Visible = False End Sub

Custom row detail class which shows label with notes about employee Public Class CustomRowDetail Inherits C1Label Implements IC1FlexGridRowDetail

Used to setup control before showing the FlexGrid detail control Private Sub Setup(ByVal parentGrid As C1FlexGrid ByVal rowIndex As Integer) Dim bs = New BindingSource(parentGridDataSource parentGridDataMember) bsPosition = parentGridRows(rowIndex)DataIndex DataField = Notes DataSource = bs End Sub

Used to update size of the FlexGrid detail control Private Sub UpdateSize(ByVal parentGrid As C1FlexGrid ByVal rowIndex As Integer ByVal proposedSize As Size) Dim srSz = parentGridScrollableRectangleSize Dim sz = TextRendererMeasureText(Text Font srSz TextFormatFlagsWordBreak) szWidth = MathMax(szWidth srSzWidth) Size = sz End Sub End Class

VBNET

サイズ変更

Set Row HeightFlexGrid provides DefaultSize property of the RowCollection class to set row height across the grid You can alsospecify the height of a particular row by setting Height property of the Row class Default value of the Heightproperty is -1 which indicates that the row is taking height specified by the DefaultSize property

Use the code below to set the default height of a row of the WinForms FlexGrid

Set the default size of all rowsc1FlexGrid1RowsDefaultSize = 50

C

FlexGrid for WinForms

93 Copyright copy GrapeCity Inc All rights reserved

Auto-adjust Row HeightTo adjust the row height according to text length and word wrapping options FlexGrid provides the AutoSizeRow()and AutoSizeRows() methods While AutoSizeRow() method automatically adjusts height of the specified row theAutoSizeRows() method is used for cell ranges

Following code shows how you can auto adjust the row height according to the text length in the WinForms FlexGrid

Set MinMax Row HeightFlexGrid allows you to set bounds to the row height by using the MinSize and MaxSize propertiesof the RowCollection class This feature is especially useful in scenarios such as when AllowResizing property is set totrue or while using the AutoSizeRow() or AutoSizeRows() method

Specify the bounds of row height in the WinForms FlexGrid using the code below

Set the height of a particular rowc1FlexGrid1Rows[1]Height = 55

Set the default size of all rowsc1FlexGrid1RowsDefaultSize = 50

Set the height of a particular rowc1FlexGrid1Rows(1)Height = 55

VBNET

Adjust the height of fourth row automaticallyc1FlexGrid1AutoSizeRow(4) Adjust the height of all rows automatically c1FlexGrid1AutoSizeRows() Adjust the height of cell range automaticallyc1FlexGrid1AutoSizeRows(2 4 5 6 10 C1WinC1FlexGridAutoSizeFlagsNone)

C

Adjust the height of fourth row automatically c1FlexGrid1AutoSizeRow(4)

Adjust the height of all rows automatically c1FlexGrid1AutoSizeRows()

Adjust the height of cell range automatically c1FlexGrid1AutoSizeRows(2 4 5 6 10 C1WinC1FlexGridAutoSizeFlagsNone)

VBNET

Set the maximum height of rowc1FlexGrid1RowsMaxSize = 50 Set the minimum height of rowc1FlexGrid1RowsMinSize = 20

C

FlexGrid for WinForms

94 Copyright copy GrapeCity Inc All rights reserved

Set the maximum height of rowc1FlexGrid1RowsMaxSize = 50

Set the minimum height of row c1FlexGrid1RowsMinSize = 20

VBNET

FlexGrid for WinForms

95 Copyright copy GrapeCity Inc All rights reserved

セル

Cell is the smallest unit of a grid Although in most common scenarios we prefer working on row or column levelthere are some operations which are required to be carried out on the cell level Getting setting or removing data arefew to name

Topic Snapshot Content

Basic Operations Discusses how to perform basic operations related to a cell

Set Value in CellSet Values in Cell RangeClear Value from Cell (Range)Set Image in CellDisplay Tooltip in CellRetrieve Cell Values

Cell Format Discusses how to format cell or cell data in various scenarios

Cell ContentCell AppearanceConditional FormattingOwner Drawn Cell

基本操作

Set Value in CellFlexGrid provides two ways to set values in cell You can either use Item property (indexer) or SetData method of the C1FlexGrid class

Use the code below to set a value in the WinForms FlexGrid cell

Set Values in Cell RangeTo set values in a cell range you can either use Data property of the CellRange class or SetData method of the C1FlexGrid class

Following code shows how to set values in a cell range in WinForms FlexGrid

インデックスを使用してデータを設定しますc1FlexGrid1[2 3] = 2nd col 3rd row SetDataメソッドを使用してデータを設定しますc1FlexGrid1SetData(2 4 2nd col 4th row)

C

インデックスを使用してデータを設定します c1FlexGrid1(2 3) = 2nd col 3rd row

SetDataメソッドを使用してデータを設定します c1FlexGrid1SetData(2 4 2nd col 4th row)

VBNET

セル範囲を取得しますC1WinC1FlexGridCellRange cr = c1FlexGrid1GetCellRange(2 3 5 6) 方法1dataプロパティを使用してセル範囲にデータを設定しますcrData = Cell Range

C

FlexGrid for WinForms

96 Copyright copy GrapeCity Inc All rights reserved

Clear Value from Cell (Range)There are two ways by which contents of cell or cell range can be cleared You can either chose to do it programmatically by setting thecontent of cell to an empty string using indexer or SetData method Or you can set the AutoClipboard property to true so that user candelete the values by pressing the Delete key

Below code demonstrates how to allow keyboard operations so that user can clear values from WinForms FlexGrid cells

Set Image in CellTo set image in a cell you can use SetCellImage method of the C1FlexGrid class You can also set an image in a cell range by using Imageproperty of the CellRange class By default text and image both are displayed in the cell However you can choose to display only image bysetting the ImageAndText property to false

Use the code below to set image in a WinForms FlexGrid cell

方法2SetDataメソッドを使用してセル範囲にデータを設定します c1FlexGrid1SetData(cr Cell Range)

セル範囲を取得します Dim cr As C1WinC1FlexGridCellRange = c1FlexGrid1GetCellRange(2 3 5 6)

方法1dataプロパティを使用してセル範囲にデータを設定します crData = Cell Range

方法2SetDataメソッドを使用してセル範囲にデータを設定します c1FlexGrid1SetData(cr Cell Range)

VBNET

ユーザーがDeleteキーを押してセルの内容をクリアするなどのキーボード操作を実行できるようにしますc1FlexGrid1AutoClipboard = true

コードを介して特定のセルのデータをクリアしますc1FlexGrid1SetData(3 4 )

C

ユーザーがDeleteキーを押してセルの内容をクリアするなどのキーボード操作を実行できるようにします c1FlexGrid1AutoClipboard = True

コードを介して特定のセルのデータをクリアします c1FlexGrid1SetData(3 4 )

VBNET

セル(36)に画像を設定しますc1FlexGrid1SetCellImage(3 6 ImageFromFile(masterpng))

C

FlexGrid for WinForms

97 Copyright copy GrapeCity Inc All rights reserved

Display Tooltip in CellTo display partially hidden content of cells as tooltip FlexGrid provides ShowCellLabels property of the C1FlexGrid class You can also showadditional information in the form of a tooltip by using the MouseEnterCell and MouseLeaveCell event

Below code shows how to display a tooltip on a WinForms FlexGrid cell

セル範囲(126)から(146)に画像を設定しますC1WinC1FlexGridCellRange crcr = c1FlexGrid1GetCellRange(12 6 14 6)crImage = ImageFromFile(amexjpg)

テキストなしで画像を表示しますc1FlexGrid1Rows[3]ImageAndText = false

セル(36)に画像を設定します c1FlexGrid1SetCellImage(3 6 ImageFromFile(masterpng))

セル範囲(126)から(146)に画像を設定します Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1GetCellRange(12 6 14 6) crImage = ImageFromFile(amexjpg)

テキストなしで画像を表示します c1FlexGrid1Rows(3)ImageAndText = False

VBNET

private void Form1_Load(object sender EventArgs e) このコードはデータを「c1NWindDataSetEmployees」テーブルにロードします 必要に応じて移動または削除できます thisemployeesTableAdapterFill(thisc1NWindDataSetEmployees) for (int i = c1FlexGrid1RowsFixed i lt c1FlexGrid1RowsCount i++) c1FlexGrid1Rows[i]UserData = Employee + c1FlexGrid1[i 2] + + c1FlexGrid1[i 3] private void C1FlexGrid1_MouseEnterCell(object sender C1WinC1FlexGridRowColEventArgs e) if (eRow gt= c1FlexGrid1RowsFixed) string tip tip = c1FlexGrid1Rows[eRow]UserDataToString() ツールチップを表示します toolTip1SetToolTip(c1FlexGrid1 tip)

private void C1FlexGrid1_MouseLeaveCell(object sender C1WinC1FlexGridRowColEventArgs e) ツールチップを非表示にします toolTip1SetToolTip(c1FlexGrid1 )

C

FlexGrid for WinForms

98 Copyright copy GrapeCity Inc All rights reserved

Retrieve Cell ValuesThere are numerous ways using which you can fetch the value of FlexGrid cells depending on your requirement Below tablediscusses several scenarios such as fetching the raw data or formatted data from a single cell or a cell range

Requirement MethodProperty Usage

Get the raw data Item property (indexer) ExampleCode

var data = c1FlexGrid1[1 1] SystemDiagnosticsDebugWriteLine($Cell data data)

GetData() method ExampleCode

var data1 = c1FlexGrid1GetData(1 1) SystemDiagnosticsDebugWriteLine($Cell data data1)

Get the formatted data GetDataDisplay() method ExampleCode

var data2 = c1FlexGrid1GetDataDisplay(1 1) SystemDiagnosticsDebugWriteLine($Display data data2)

Get values of a cell range Clip property ExampleCode

var data3 = c1FlexGrid1Clip SystemDiagnosticsDebugWriteLine($Clip data data3)

GetCellRange method ExampleCode

var data4 = c1FlexGrid1GetCellRange(1 1) SystemDiagnosticsDebugWriteLine($Cell Range data data4Clip)

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) このコードはデータを「c1NWindDataSetEmployees」テーブルにロードします 必要に応じて移動または削除できます MeemployeesTableAdapterFill(Mec1NWindDataSetEmployees)

For i As Integer = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 c1FlexGrid1Rows(i)UserData = Employee amp c1FlexGrid1(i 2) amp + c1FlexGrid1(i 3) Next End Sub

Private Sub C1FlexGrid1_MouseEnterCell(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) If eRow gt= c1FlexGrid1RowsFixed Then Dim tip As String tip = c1FlexGrid1Rows(eRow)UserDataToString() ツールチップを表示します toolTip1SetToolTip(c1FlexGrid1 tip) End If End Sub

Private Sub C1FlexGrid1_MouseLeaveCell(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) ツールチップを非表示にします toolTip1SetToolTip(c1FlexGrid1 ) End Sub

VBNET

FlexGrid for WinForms

99 Copyright copy GrapeCity Inc All rights reserved

セルの書式設定

Cell ContentTo control how content of the cells is formatted and displayed set the Format property of Row or Column object toformat string similar to the ones that are used with StringFormat property in the NET framework For instance thesample code below formats the third column as Date and fourth column as Currency

FlexGrid also provides design time option to set the Format property through the Format String dialog You canaccess the Format String dialog by clicking Ellipsis button against the Format String field in Column Tasks menu Oryou can also use the Format property in C1FlexGrid Column Editor

短い日付形式を設定しますc1FlexGrid1Cols[3]Format = D 通貨形式を設定しますc1FlexGrid1Cols[4]Format = c

C

短い日付形式を設定しますc1FlexGrid1Cols(3)Format = D

通貨形式を設定しますc1FlexGrid1Cols(4)Format = c

VBNET

FlexGrid for WinForms

100 Copyright copy GrapeCity Inc All rights reserved

Note that Format String dialog is specific to column and changes the Format property of the selected column only

Cell AppearanceFlexGrid provides CellStyle objects to handle the appearance aspects of cells such as alignment font colors bordersand so on The grid has Styles property that holds the collection of styles used to format the grid This collection hassome built-in members that define the appearance of grid elements such as fixed and scrollable cells selection focuscell and so on You can change these styles to modify the appearance of grid

Although changing the built-in styles is the simplest way to change appearance of the grid you can also create yourown custom styles and assign them to cells rows or columns

Use the code below to change appearance of the WinForms FlexGrid cells

組み込みのスタイルをカスタマイズしますCellStyle cs = c1FlexGrid1StylesFocus

C

FlexGrid for WinForms

101 Copyright copy GrapeCity Inc All rights reserved

Conditional FormattingTo format a cell according to its content you need to create a new style and apply it to the cells satisfying a particularcondition using SetCellStyle() method For instance to highlight the values greater than a specified value you canformat the cells containing them using different style

Following code shows how to apply conditional formatting on WinForms FlexGrid cells

csFont = new Font(c1FlexGrid1Font FontStyleBold)csForeColor = ColorGreencsBackColor = ColorRed

カスタムスタイルを作成します CellStyle cs1 = c1FlexGrid1StylesAdd(NewStyle)cs1BackColor = ColorAquacs1ForeColor = ColorBlue

カスタムスタイルを割り当てますc1FlexGrid1Cols[3]Style = cs1

Dim cs As CellStyle = c1FlexGrid1StylesFocus csFont = New Font(c1FlexGrid1Font FontStyleBold) csForeColor = ColorGreen csBackColor = ColorRed

Dim cs1 As CellStyle = c1FlexGrid1StylesAdd(NewStyle) cs1BackColor = ColorAqua cs1ForeColor = ColorBlue

c1FlexGrid1Cols(3)Style = cs1

VBNET

CellStyle cs 大きな値のカスタムスタイルを作成しますcs = c1FlexGrid1StylesAdd(LargeValue)csFont = new Font(Font FontStyleItalic)

C

FlexGrid for WinForms

102 Copyright copy GrapeCity Inc All rights reserved

Owner Drawn CellThe above sections explain how you can customize FlexGrid cells to change the appearance of grid using CellStyleobjects However for further customization of grid cells such as rendering gradient background custom graphics etcyou can use DrawMode property and OwnerDrawCell event of the C1FlexGrid class

The DrawMode property determines whether or not the OwnerDrawCell event is fired The event allows you tooverride every visual aspect of the cell You can change the text and image to be displayed in the cell by setting theeText and eImage parameters in the event handler You can also change the style that is used to display the cell bysetting the eStyle property

Note that you should not modify properties of the Style parameter as it might affect other cells Instead assign a newCellStyle object to the Style parameter For example instead of setting eStyleForeColor = ColorRed assign a wholenew style to the parameter using eStyle = c1FlexGrid1Styles[RedStyle]

You can also use your own drawing code to draw into the cell and even combine your custom code with calls to theeDrawCell method For example you can paint the cell background using GDI calls and then call eDrawCell todisplay the cell borders and content

In the example below WinForms FlexGrid uses a gradient brush to paint the background of the selected cell rangeFirst the sample code sets the DrawMode property to OwnerDraw and then declares a LinearGradientBrushobject

csBackColor = ColorGold

for (int row = 1 row lt c1FlexGrid1RowsCount row++)if (ConvertToDouble(c1FlexGrid1[row 4]) gt 80000)c1FlexGrid1SetCellStyle(row 4 cs)

Dim cs As CellStyle

cs = c1FlexGrid1StylesAdd(LargeValue) csFont = New Font(Font FontStyleItalic) csBackColor = ColorGold

For row As Integer = 1 To c1FlexGrid1RowsCount - 1

If ConvertToDouble(c1FlexGrid1(row 4)) gt 80000 Then c1FlexGrid1SetCellStyle(row 4 cs) End If Next

VBNET

SystemDrawingDrawing2DLinearGradientBrush m_GradientBrushprivate void Form1_Load(object sender EventArgs e)

C

FlexGrid for WinForms

103 Copyright copy GrapeCity Inc All rights reserved

所有者描画セルで使用するブラシ m_GradientBrush = new SystemDrawingDrawing2DLinearGradientBrush(ClientRectangle ColorSteelBlue ColorWhite 45)

グラデーションを追加するにはowner-drawを使用します c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw

private void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) グラデーションブラシを使用して選択したセルの背景を描画します if (c1FlexGrid1SelectionContains(eRow eCol)) 背景を描きますeGraphicsFillRectangle(m_GradientBrush eBounds)

グリッドにコンテンツを描画させますeDrawCell(C1WinC1FlexGridDrawCellFlagsContent)

このセルの描画は完了ですeHandled = true

Private m_GradientBrush As DrawingDrawing2DLinearGradientBrush

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) 所有者描画セルで使用するブラシ m_GradientBrush = New DrawingDrawing2DLinearGradientBrush(ClientRectangle ColorSteelBlue ColorWhite 45)

グラデーションを追加するにはowner-drawを使用します c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDrawEnd Sub

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) グラデーションブラシを使用して選択したセルの背景を描画します If c1FlexGrid1SelectionContains(eRow eCol) Then 背景を描きます eGraphicsFillRectangle(m_GradientBrush eBounds)

グリッドにコンテンツを描画させます eDrawCell(C1WinC1FlexGridDrawCellFlagsContent)

このセルの描画は完了です eHandled = True End IfEnd SubEnd IfEnd Sub

VBNET

FlexGrid for WinForms

104 Copyright copy GrapeCity Inc All rights reserved

グリッド

This section discusses about various operations that can be performed on the grid

Topic Snapshot Content

Basic Operations Discusses about basic operations that can be performed on the grid

Transpose Data in GridDisplay Context Menu

Keyboard Navigation Discusses about supperted keys and their operations in

Non-edit ModeEdit Mode

Improve Performance Provides tips and tricks to get best out of your grid by improving its performance

Use Data VirtualizationUse BeginUpdate and EndUpdate MethodsKeep AutoResize Property to False (default)Assign Styles DynamicallyAvoid Modifying Styles in the OwnerDrawCell EventShow Ellipses in a Single ColumnShow Multi-line Text in a CellRetrieve Data Sorting When Bound to a Data TableSpecify Character Limit for Column

基本操作

This topic discusses about various operations that require handling at the grid level

Transpose Data in GridTransposing data refers to swapping column data and row data In WinForms FlexGrid this can be achieved usingTranspose() method of the C1FlexGrid class as shown in the code below

Note that data can be transposed only in the case of unbound grid Also if grid has sorting applied on a column theTranspose() method removes sorting before transposing the data

Display Context MenuContext menus can be helpful to user as they provide shortcuts for actions that are frequently used In FlexGrid therecan be two scenarios to display a context menu

Display context menu in non-edit modeDisplay context menu in edit mode

Display Context Menu in Non-edit Mode

To display context menu when grid is in non-edit mode you need to create an instance of ContextMenuStrip controladd the menu items and assign the instance to ContextMenuStrip property of the Control class

c1FlexGrid1Transpose()

C

C1FlexGrid1Transpose()

VBNET

FlexGrid for WinForms

105 Copyright copy GrapeCity Inc All rights reserved

Refer to the code below to see how to display a context menu in WinForms FlexGrid in non-edit mode

Display Context Menu in Edit Mode

To display context menu in edit mode you need to display the context menu on editor by using StartEdit event ofthe C1FlexGrid class In the StartEdit event instantiate the editor and the ContextMenuStrip add menu items andthen assign it to ContextMenuStrip property of the editor

Create an instance of ContextMenuStrip controlContextMenuStrip cm = new ContextMenuStrip()

Add menu items to the context menucmItemsAdd(Add Above)cmItemsAdd(Add Below)cmItemsAdd(Add Left)cmItemsAdd(Add Right)

Assign the instance to ContextMenuStrip property c1FlexGrid1ContextMenuStrip = cm

C

Create an instance of ContextMenuStrip controlDim cm As ContextMenuStrip = New ContextMenuStrip()

Add menu items to the context menucmItemsAdd(Add Above)cmItemsAdd(Add Below)cmItemsAdd(Add Left)cmItemsAdd(Add Right)

Assign the instance to ContextMenuStrip property c1FlexGrid1ContextMenuStrip = cm

VBNET

FlexGrid for WinForms

106 Copyright copy GrapeCity Inc All rights reserved

Use the code below to display context menu in WinForms FlexGrid in edit mode

private void C1FlexGrid1_StartEdit(object sender C1WinC1FlexGridRowColEventArgs e) TextBox tb = (TextBox)c1FlexGrid1Editor

Create context menu ContextMenuStrip cm2 = new ContextMenuStrip() cm2ItemsAdd(Cut) cm2ItemsAdd(Copy) cm2ItemsAdd(Paste) Set context menu tbContextMenuStrip = cm2

C

Private Sub C1FlexGrid1_StartEdit(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) Dim tb As TextBox = CType(c1FlexGrid1Editor TextBox)

Create context menu Dim cm2 As ContextMenuStrip = New ContextMenuStrip() cm2ItemsAdd(Cut) cm2ItemsAdd(Copy) cm2ItemsAdd(Paste)

Set context menu tbContextMenuStrip = cm2End Sub

VBNET

キーボードによる移動

With built-in keyboard support FlexGrid lets you perform the basic navigation operations such as moving the focusentering or exiting the edit mode etc with a perfect ease just by using keys Below tables list the supported keys andtheir corresponding operations in non-edit as well as in edit mode of the cell

Non-edit Mode

Key Sequence Key Action

FlexGrid for WinForms

107 Copyright copy GrapeCity Inc All rights reserved

uarr

larr rarr

darr

Moves focus to the adjacent cell in direction indicated by the arrow key

Shift + ArrowSelects adjacent cells in direction indicated by the arrow key

F2Grid is editable Toggles the cell to edit mode If a value exists in the cell it getsselected Else the grid simply displays a cursor in the cell

Grid is not editable No action

EnterGrid is editable Toggles the cell to edit mode If a value exists in the cell it getsselected Else the grid simply displays a cursor in the cell

Grid is not editable Moves the selection down to the next visible row

You can also change default behavior of Enter key press by using the KeyActionEnterproperty

HomeMoves focus to the first cell of row

EndMoves focus to the last cell of row

Ctrl + HomeMoves focus to the first cell of column

Ctrl + EndMoves focus to the last cell of column

TabBy default grid ignores the Tab key press and lets it cycle through the controls on theform However you can define the action to be performed on Tab key press by usingthe KeyActionTab property

Ctrl + C

Ctrl + X

Ctrl + V

Performs usual clipboard operations that is copy(Ctrl+C) cut(Ctrl+X) and paste(Ctrl+V)when AutoClipboard property is set to true (Default value is false)

Edit Mode

Key Sequence Key Action

uarr

darr

Moves focus to the adjacent cell in the direction indicated by arrow key

FlexGrid for WinForms

108 Copyright copy GrapeCity Inc All rights reserved

larr rarrMoves cursor by one character in the direction indicated by arrow key When cursor is onthe first or last character moves focus to the adjacent cell in the direction of arrow key

EnterToggles the cell to non-edit mode and moves focus to the cell below You can also changedefault behavior of Enter key press by using the KeyActionEnter property

EscCancels editing and exits the edit mode

TabBy default grid ignores the Tab key press and lets it cycle through the controls on theform However you can define the action to be performed on Tab key press by usingthe KeyActionTab property

パフォーマンスの向上

Use Data VirtualizationTo efficiently render large data sets FlexGrid supports data vitualization in which data is fetched in pages as the user scrolls down The gridknows the total number of rows but only loads and displays those that are visible to the user For instance you can use C1DataCollectionpackage to implement virtualizable data source Create a class inherited from the C1VirtualDataCollection and implement GetPageAsyncmethod which returns one page of data from data source you have assigned The following GIF shows how FlexGrid appears in the virtualscrolling mode

public class VirtualModeCollectionView C1VirtualDataCollectionltCustomergt public int TotalCount get set = 1_000 protected override async TaskltTupleltint IReadOnlyListltCustomergtgtgt GetPageAsync(int pageIndex int startingIndex int count IReadOnlyListltSortDescriptiongt sortDescriptions = null FilterExpression filterExpression = null CancellationToken cancellationToken = default(CancellationToken)) await TaskDelay(500 cancellationToken)Simulates network traffic return new Tupleltint IReadOnlyListltCustomergtgt(TotalCount EnumerableRange(startingIndex count)Select(i =gt new Customer(i))ToList())

C

Public Class VirtualModeCollectionView

VBNET

FlexGrid for WinForms

109 Copyright copy GrapeCity Inc All rights reserved

Use BeginUpdate and EndUpdate MethodsThe BeginUpdate and EndUpdate methods are used to optimize the performance of the grid Call BeginUpdate before making extensivechanges and call EndUpdate when done to suspend repainting This reduces flicker and increases performance This optimization is especiallyeffective when adding large number of rows to the grid because it needs to recalculate ranges and update scrollbars each time a row is added

The code below shows how to add a large number of rows to the WinForms FlexGrid efficiently Note how the EndUpdate method is calledinside a finally block to ensure repainting is properly restored

Keep AutoResize Property to False (default)In case of bound grid if AutoResize property is set to true the control automatically resizes its columns to fit the widest entry every time newdata is read from the data source If the data source contains a large number of rows and columns the automatic resizing may take a relativelylong time In such cases you should consider setting AutoResize to false and setting the column widths directly in code

Assign Styles DynamicallyFlexGrid allows you to create cell styles and assign them to rows columns and arbitrary cell ranges You can use this feature to format the gridcells conditionally Usually you do this by using the SetCellStyle() method However in that case you have to update the style whenever the cellvalue changes Also if the grid is bound to a data source styles are lost whenever data source is reset after operations such as sorting andfiltering A better alternative in these cases is to use the OwnerDraw feature and select styles dynamically based on the cell values For example

Inherits C1VirtualDataCollection(Of Customer)

Public Property TotalCount As Integer = 1_000

Protected Overrides Async Function GetPageAsync(ByVal pageIndex As Integer ByVal startingIndex As Integer ByVal count As Integer ByVal Optional sortDescriptions As IReadOnlyList(Of SortDescription) = Nothing ByVal Optional filterExpression As FilterExpression = Nothing ByVal Optional cancellationToken As CancellationToken = DirectCast(Nothing CancellationToken)) As Task(Of Tuple(Of Integer IReadOnlyList(Of Customer))) Await TaskDelay(500 cancellationToken) Simulates network traffic Return New Tuple(Of Integer IReadOnlyList(Of Customer))(TotalCount EnumerableRange(CInt(startingIndex) CInt(count))[Select](Function(i) New Customer(i))ToList()) End FunctionEnd Class

void UpdateGrid(C1FlexGrid c1FlexGrid1) try c1FlexGrid1BeginUpdate() suspend painting to avoid flicker c1FlexGrid1RowsCount = 1 for (int i = 1 i lt 10000 i++) c1FlexGrid1AddItem(Row + iToString()) finally c1FlexGrid1EndUpdate() always restore painting

C

Private Sub UpdateGrid(ByVal c1FlexGrid1 As C1FlexGrid) Try c1FlexGrid1BeginUpdate() suspend painting to avoid flicker c1FlexGrid1RowsCount = 1

For i As Integer = 1 To 10000 - 1 c1FlexGrid1AddItem(Row amp iToString()) Next

Finally c1FlexGrid1EndUpdate() always restore painting End TryEnd Sub

VBNET

FlexGrid for WinForms

110 Copyright copy GrapeCity Inc All rights reserved

the sample code shows how to display negative values in red color and values above 1000 in green color in the WinForms FlexGrid

Avoid Modifying Styles in the OwnerDrawCell EventAnother way to improve performance is not to modify the CellStyle object passed as a parameter in the OwnerDrawCell event Instead assign anew value to the eStyle parameter This is important because the CellStyle passed to the event handler is often used by other cells Forexample you could unintentionally change a normal style of the WinForms FlexGrid which would affect other similar cells as well in the grid

private void Form1_Load(object sender EventArgs e) Fill a column with random values c1FlexGrid1Cols[1]DataType = typeof(int) Random rnd = new Random() for (int r = 1 r lt c1FlexGrid1RowsCount r++) c1FlexGrid1[r 1] = rndNext(-10000 10000) Create style used to show negative values c1FlexGrid1StylesAdd(Red)ForeColor = ColorRed Enable OwnerDraw by setting the DrawMode property c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw c1FlexGrid1OwnerDrawCell += new C1WinC1FlexGridOwnerDrawCellEventHandler(C1FlexGrid1_OwnerDrawCell)

private void C1FlexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if(eMeasuring) Check that the row and column contain integer data if (eRow gt 0 ampamp c1FlexGrid1Cols[eCol]DataType == typeof(int)) Apply the style Red eStyle = c1FlexGrid1Styles[Red]

C

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) Fill a column with random values c1FlexGrid1Cols(1)DataType = GetType(Integer) Dim rnd As Random = New Random()

For r As Integer = 1 To c1FlexGrid1RowsCount - 1 c1FlexGrid1(r 1) = rnd[Next](-10000 10000) Next

Create style used to show negative values c1FlexGrid1StylesAdd(Red)ForeColor = ColorRed

Enable OwnerDraw by setting the DrawMode property c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw c1FlexGrid1OwnerDrawCell += New C1WinC1FlexGridOwnerDrawCellEventHandler(AddressOf C1FlexGrid1_OwnerDrawCell) End Sub

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If Not eMeasuring Then

Check that the row and column contain integer data If eRow gt 0 AndAlso c1FlexGrid1Cols(eCol)DataType Is GetType(Integer) Then Apply the style Red eStyle = c1FlexGrid1Styles(Red) End If End If End Sub

VBNET

FlexGrid for WinForms

111 Copyright copy GrapeCity Inc All rights reserved

Show Ellipses in a Single ColumnThe Trimming property should be used to show ellipses in a single column of the grid To determine how long strings are trimmed to fit the cellthe Trimming property can be set to either None Character Word EllipsisCharacter EllipsisWord or EllipsisPath For more information ontrimming see Display Trimmed Text

The following code sets the Trimming property to show ellipses at the end of the second WinForms Flexgrid column with the text trimmed tothe nearest character

Show Multi-line Text in a CellWhen showing multiple lines of text in a cell use the WordWrap and Height properties The WordWrap property determines whether the gridshould automatically break long strings that contain spaces and display them in multiple lines Strings that contain hard line breaks (vbCrLf ornr) are always displayed in multiple lines Multiple line text can be displayed in both fixed and scrollable cells For more information on wordwrapping see Wrap Text

Refer to code below to see how a multi-line text should be effectively displayed in the WinForms FlexGrid

CORRECT APPROACHprivate void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) Select style to use when painting this cell eStyle = MyStyleSelector(eRow eCol) WRONG APPROACHprivate void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) Select style to use when painting this cell This is wrong because changing any CellStyle objects invalidates the grid which would cause this event handler to be called over and over again eStyleColor = MyColorSelector(eRow eCol)

C

CORRECT APPROACHPrivate Sub C1FlexGrid1_OwnerDrawCellMethod(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) Select style to use when painting this celleStyle = MyStyleSelector(eRow eCol)End Sub

WRONG APPROACHPrivate Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) Select style to use when painting this cell This is wrong because changing any CellStyle objects invalidates the grid which would cause this event handler to be called over and over againeStyleColor = MyColorSelector(eRow eCol)End Sub

VBNET

c1FlexGrid1Cols[1]StyleNewTrimming =StringTrimmingEllipsisCharacter

C

c1FlexGrid1Cols(1)StyleNewTrimming = StringTrimmingEllipsisCharacter

VBNET

Set the WordWrap property

C

FlexGrid for WinForms

112 Copyright copy GrapeCity Inc All rights reserved

Retrieve Data Sorting When Bound to a Data TableTo maintain the way the grid is sorted when data is refreshed you can use the default views Sort property and a sort expression The Sortproperty uses a string containing the column name followed by ASC(default) or DESC to sort the column in ascending or descending orderrespectively Multiple columns can be sorted by specifying each column name separated by a comma A sort expression can include names ofgrid columns or a calculation Setting the sort expression at run time immediately reflects the changes in the data view

Below code shows how to use the sort expression with Sort property in the WinForms FlexGrid

Specify Character Limit for ColumnTo set the maximum number of characters a user can enter for any given column use the SetupEditor event You must declare an externaleditor such as C1TextBox in the StartEdit event of the C1FlexGrid class Then in the SetupEditor event you can set the maximum number ofcharacters that are allowed in a column cell

Use the code below to set the character limit for a WinForms FlexGrid column

c1FlexGrid1Styles[Normal]WordWrap = true Set the row heightc1FlexGrid1Rows[1]Height = 2 fgRowsDefaultSize Add text to the cellc1FlexGrid1[1 2] = This is the first line rn This is the second line

Set the WordWrap property c1FlexGrid1Styles(Normal)WordWrap = True

Set the row height c1FlexGrid1Rows(1)Height = 2 fgRowsDefaultSize

Add text to the cell c1FlexGrid1(1 2) = This is the first line amp vbCrLf amp This is the second line

VBNET

Sort the data by the UnitsInStock column then by the ProductID column thisproductsBindingSourceSort = UnitsInStock ASC ProductID ASC

C

Sort the data by the UnitsInStock column then by the ProductID columnMeproductsBindingSourceSort = UnitsInStock ASC ProductID ASC

VBNET

private void C1FlexGrid1_StartEdit(object sender C1WinC1FlexGridRowColEventArgs e) c1FlexGrid1Editor = c1TextBox private void C1FlexGrid1_SetupEditor(object sender RowColEventArgs e) Set the 3rd column to allow 20 characters and the rest only 10 if (eCol == 2) c1TextBoxMaxLength = 20 else c1TextBoxMaxLength = 10

C

Private Sub C1FlexGrid1_StartEdit(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs)

VBNET

FlexGrid for WinForms

113 Copyright copy GrapeCity Inc All rights reserved

c1FlexGrid1Editor = c1TextBox End Sub

Private Sub C1FlexGrid1_SetupEditor(ByVal sender As Object ByVal e As RowColEventArgs)

Set the 3rd column to allow 20 characters and the rest only 10 If eCol = 2 Then c1TextBoxMaxLength = 20 Else c1TextBoxMaxLength = 10 End If End Sub

FlexGrid for WinForms

114 Copyright copy GrapeCity Inc All rights reserved

スクロールバー

Display or Hide the Scroll BarIn FlexGrid you can manage the display of scroll bars using the ScrollBars property which lets you choose whether todisplay horizontal vertical both or no scroll bar through the ScrollBars enumeration

Below code shows how to always display both the scrollbars in the WinForms FlexGrid

Set Scroll PositionTo scroll FlexGrid to a specified location you can set TopRow and LeftCol property of the C1FlexGrid class TopRowproperty scrolls the grid vertically while LeftCol sets the horizontal scroll position of the grid The maximum value ofthese properties depends on the total number of rows or columns and the count that can be displayed in the gridThis feature is really useful in scenarios like synchronized scrolling of multiple grids

Use the code below to set scroll position of the WinForms FlexGrid

水平および垂直スクロールバーを表示しますc1FlexGrid1ScrollBars = ScrollBarsBoth 常にスクロールバーを表示しますc1FlexGrid1ScrollOptions = ScrollFlagsAlwaysVisible

C

水平および垂直スクロールバーを表示しますc1FlexGrid1ScrollBars = ScrollBarsBoth

常にスクロールバーを表示しますc1FlexGrid1ScrollOptions = ScrollFlagsAlwaysVisible

VBNET

スクロール位置を設定しますc1FlexGrid1TopRow = 3c1FlexGrid1LeftCol = 2

C

スクロール位置を設定しますc1FlexGrid1TopRow = 3

VBNET

FlexGrid for WinForms

115 Copyright copy GrapeCity Inc All rights reserved

Other Scroll OptionsFlexGrid also provides more options to handle various aspects of displaying a scroll bar through ScrollOptionsproperty This property accepts the values from ScrollFlags enumeration which lets you customize the scroll baroptions as described in the table below

Value Scroll Operation

AlwaysVisible Displays the scroll bar even when they are disable or there is no scrollable area

DelayedScroll Scrolls the content only after user has released the scrollbar thumb

KeepMergedRangePosition Can not set scroll position to the first cell of a merged range

None Uses the default scrolling behavior

ScrollByRowColumn Scrolls the content in units of rows or columns instead of scrolling by pixels

ShowScrollTips Fires the ShowScrollTip event and displays a tooltip next to the vertical scrollbarwhile scrolling vertically

Following code shows how to scroll the WinForms FlexGrid by rows or columns only

c1FlexGrid1LeftCol = 2

行や列単位でスクロールします c1FlexGrid1ScrollOptions = ScrollFlagsScrollByRowColumn

C

行や列単位でスクロールしますc1FlexGrid1ScrollOptions = ScrollFlagsScrollByRowColumn

VBNET

FlexGrid for WinForms

116 Copyright copy GrapeCity Inc All rights reserved

選択

Selection ModesFlexGrid by default allows to select a continuous batch of cells using mouse or keyboard and entire row or column by clicking thecorresponding header However the default behavior can be changed to allow selection in units of cell row column etc byusing SelectionMode property of the C1FlexGrid class The property accepts values from the SelectionModeEnumenumeration Below table gives a quick snapshot of how selection looks like in each of these modes

Value Description Snapshot

Default Allows selection of continuous batch of cells using mouse orkeyboard Also lets the user select entire row or column onclicking the respective header

Cell Allows selection of single cell at a time

CellRange Allows selection of continuous batch of cells using mouse orkeyboard

Column Allows selection of single column at a time

ColumnRange Allows selection of multiple contiguous columns at a time

ListBox Allows selection of multiple non-contiguous rows using the Ctrlkey

FlexGrid for WinForms

117 Copyright copy GrapeCity Inc All rights reserved

Row Allows selection of single row at a time

RowRange Allows selection of multiple contiguous rows at a time

Set SelectionFlexGrid provides various ways to set the selection through code You can use any of these methods depending on the requirementsuch as selecting the single cell cell range or rows

Selection MethodProperty Sample code

Single cell Set the Row and Col property Default value of both of theseproperties is 1 Hence by default selection is set to the firstscrollable cell on top left of the grid

Example Title

c1FlexGrid1Row = 2c1FlexGrid1Col = 1

Call the Select(rowIndex colIndex) method to select a singlecell

Example Title

c1FlexGrid1Select(2 1)

Cell range Set the RowSel and ColSel property These properties set theselection starting from value set in Row and Col property tothe specified row and column Note that to specify a blockselection you must set Row and before setting RowSel andColSel

Example Title

c1FlexGrid1Row = 2c1FlexGrid1Col = 1c1FlexGrid1RowSel = 4c1FlexGrid1ColSel = 3

Call the Select(CellRange Boolean) method to select a cellrange in a single call

Example Title

CellRange cellRange = new CellRange()cellRanger1 = 2cellRanger2 = 4cellRangec1 = 1cellRangec2 = 3c1FlexGrid1Select(cellRange)

Rows

(If SelectionModes =

SelectionModesEnum

ListBox)

Set the RowSelected property to true for individual rowobjects to select the non-continuous rows

Example Title

c1FlexGrid1SelectionMode = SelectionModeEnumListBoxc1FlexGrid1Rows[1]Selected = truec1FlexGrid1Rows[4]Selected =

Value Description Snapshot

FlexGrid for WinForms

118 Copyright copy GrapeCity Inc All rights reserved

true

Get Selection To get selected range of the WinForms FlexGrid you can use Selection property of the C1FlexGrid class

Select Text on Double ClickBy default double click on a grid cell changes the cell state to edit mode and shows the cursor at position of the mouse pointerHowever you can change this behavior and select the cell value on double click of a cell This can be done by detecting anddisabling the double click in BeforeDoubleClick event Then call the StartEditing method to enter the edit mode change theeditor to a TextBox and call the SelectAll method to select the cell value

Following code shows how you can select text of the WinForms FlexGrid cell on a double click

private void Button1_Click(object sender EventArgs e) C1WinC1FlexGridCellRange cr cr = c1FlexGrid1Selection MessageBoxShow(Selected rangen + crr1 + + crc1 + to + crr2 + + crc2)

C

Private Sub Button1_Click(ByVal sender As Object ByVal e As EventArgs) Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1Selection MessageBoxShow(Selected range amp vbLf amp crr1 amp + crc1 amp to + crr2 amp + crc2)End Sub

VBNET

private void C1FlexGrid1_BeforeDoubleClick(object sender BeforeMouseDownEventArgs e) デフォルトのダブルクリックを無効にします eCancel = true 編集モードに入ります c1FlexGrid1StartEditing() TextBoxクラスに変換しSelectAllメソッドを使用して選択します TextBox tb = (TextBox)c1FlexGrid1Editor tbSelectAll()

C

Private Sub C1FlexGrid1_BeforeDoubleClick(ByVal sender As Object ByVal e As BeforeMouseDownEventArgs) デフォルトのダブルクリックを無効にします eCancel = True 編集モードに入ります c1FlexGrid1StartEditing() TextBoxクラスに変換しSelectAllメソッドを使用して選択します Dim tb As TextBox = CType(c1FlexGrid1Editor TextBox) tbSelectAll()End Sub

VBNET

Selection MethodProperty Sample code

FlexGrid for WinForms

119 Copyright copy GrapeCity Inc All rights reserved

編集

This topic discusses about various events and methods which are related to editing and also about how to disableediting

Topic Content

Edit Mode Discusses various events and methods related to editing

Disable Editing Discusses how to disable editing in grid at various levels

Disable Grid EditingDisable Row or Column EditingDisable Cell Editing

編集モード

In FlexGrid edit mode can be invoked at runtime using mouse click or even keyboard To determineprogrammatically whether the grid is in edit mode you can read the value of Editor property If the grid is in editmode the property returns a reference to the control that is being used as editor such as TextBox or ComboBoxHowever if the grid is not in edit mode the property returns null

To put the grid in edit mode programmatically you can use the StartEditing method and to finish editing you can callthe FinishEditing method You can also retain the state of edit mode in grid while navigating through the cells byusing the PreserveEditMode property

In addition FlexGrid fires various events to facilitate better control on the editing process Below table lists thesequence of events which are fired by the grid during the editing process

Event Name Description

BeforeEdit The event fires whenever an editable cell is selected It allows you to prevent the cell from beingedited by setting the events Cancel parameter to true You can also modify the ComboList propertyso the appropriate drop-down button gets painted in the cell Note that the user might not actuallystart editing after this he could simply move the selection to a different cell or control

StartEdit The event is similar to BeforeEdit except the user has actually typed a key or clicked the dropdownbutton in the cell and really is about to start editing You can still cancel the editing at this point Notethat the Editor property is still null at this point because the control hasnt yet determined the typeof editor that should be used You can assign custom editors to the Editor property at this point

ChangeEdit The event is a wrapper of editorTextChanged event The event fires when the contents of the editorchange You can use this event to keep track of the current content in editor

SetupEditor The event fires after the editor control has been created and configured to edit the cell but before itis displayed You can change the editor properties at this point (for example set the maximum lengthor password character to be used in a TextBox editor) You can also attach your own event handlers tothe editor

ValidateEdit The event fires when the user is done editing before the editor value gets copied back into the gridYou can examine the original value by retrieving it from the grid (the event provides the coordinatesof the cell) You can examine the new value about to be assigned to the grid through the Editorproperties (for example EditorText) If the new value is not valid for the cell set the Cancel parameterto true and the grid remains in edit mode If instead of keeping the cell in edit mode you wouldrather restore the original value and leave edit mode set Cancel parameter to true and then call theFinishEditing method

LeaveEdit This event fires after the grid control leaves edit mode You can use this event to approve or deny the

FlexGrid for WinForms

120 Copyright copy GrapeCity Inc All rights reserved

new cell content or to change the editor content about to be committed

AfterEdit This event fires after the new value has been applied to the cell and the editor has been deactivatedYou can use this event to update anything that depends on the cell value (for example subtotals orsorting)

Also there are few events which are related to keyboard operations and are fired when a key is pressed They aresimilar to their counterparts from SystemWindowsFormsControl class apart from the fact that they occur when thegrid is in edit mode

Event Description

KeyDownEdit This event fires when grid is in edit mode and a key is pressed You can use this event toperform an action once or even multiple times while the key is held down such as movinga cursor

KeyPressEdit This event fires when grid is in edit mode and a character key is pressed You can use thisevent to perform any operation related to typing such as handling input in the cell editor

KeyUpEdit This event fires when grid is in edit mode and key is released You can use this event toplace a logic that executes after KeypressEdit logic has taken effect

Event Name Description

編集の無効化

FlexGrid by default allows end-user to edit the cell values at runtime However with FlexGrid you can easily managehow much control you want to give to the end-users using various properties provided by the FlexGrid

Disable Grid EditingTo disable editing of the whole WinForms FlexGrid you need to set AllowEditing property of the C1FlexGrid class tofalse as shown in the code below

Disable Row or Column EditingTo disable the editing of a particular row or column of the WinForms FlexGrid you can set the AllowEditing propertyof Row or Column object to false as shown in the code below

グリッドで編集を無効にします c1FlexGrid1AllowEditing = false

C

グリッドで編集を無効にしますc1FlexGrid1AllowEditing = False

VBNET

3行目の編集を無効にしますc1FlexGrid1Rows[3]AllowEditing = false 3列目の編集を無効にしますc1FlexGrid1Cols[3]AllowEditing = false

C

FlexGrid for WinForms

121 Copyright copy GrapeCity Inc All rights reserved

Disable Cell EditingTo disable editing of a particular cell you can use the BeforeEdit event and set the Cancel parameter for thatparticular cell to true

3行目の編集を無効にしますc1FlexGrid1Rows(3)AllowEditing = False

3列目の編集を無効にしますc1FlexGrid1Cols(3)AllowEditing = False

VBNET

セル編集を無効にしますprivate void C1FlexGrid1_BeforeEdit(object sender RowColEventArgs e) if ((eCol == 4) ampamp (eRow == 2)) eCancel = true

C

セル編集を無効にしますPrivate Sub C1FlexGrid1_BeforeEdit(ByVal sender As Object ByVal e As RowColEventArgs) If eCol = 4 AndAlso eRow = 2 Then eCancel = True End IfEnd Sub

VBNET

FlexGrid for WinForms

122 Copyright copy GrapeCity Inc All rights reserved

並べ替え

Sorting is one of the basic features a grid must have and FlexGrid provides you complete control on how data can besorted in ascending or descending order for easier data analysis This topic discusses about sorting in FlexGrid andother related operations

Topic Snapshot Content

Sort Operations Discusses various operations related to sorting

Sorting through CodeSort Multiple ColumnsRevertUndo SortingDisable Sort on a Particular ColumnSort OrderCustom Sorting

Sort Indicator Discusses how to hide position and customize sort indicator

HideDisplay Sort IndicatorPosition Sort IndicatorCustomize Sort Indicator

並べ替えの操作

FlexGrid by default allows end-users to apply sorting on a single column by clicking the column header in ascending ordescending order However the grid also provides you flexibility so that you can sort your data according to yourrequirement Below sections take you through the ways to perform various operations related to sorting

Sorting through CodeYou can apply sorting through code by calling Sort method of the C1FlexGrid class The method takes SortFlagsenumeration as its parameter which lets you provide the various sort options such as setting the sort order and ignorecasing The method has various overloads which gives you flexibility to apply sorting either on a column or a range ofcells rows or columns

Use the code below to sort columns and apply sorting options through code in the WinForms FlexGrid

FlexGrid for WinForms

123 Copyright copy GrapeCity Inc All rights reserved

Sort Multiple ColumnsTo apply sorting on multiple columns through code you can use the Sort property of Column class and then call theSort() method with SortFlags set to UseColSort The Sort property accepts values from SortFlags enumeration

Following code shows how to sort multiple columns of the WinForms FlexGrid through code

To allow user to sort multiple columns at runtime set AllowSorting property of the C1FlexGrid class to MultiColumn Theproperty accepts values from the AllowSortingEnum enumeration

Following code shows how to let user sort multiple columns of the WinForms FlexGrid at run-time

方法1 2番目の列を降順で並べ替えますc1FlexGrid1Sort(C1WinC1FlexGridSortFlagsDescending 2) 方法 2SortFlagを使用して複数の並べ替えオプションを指定しますC1WinC1FlexGridSortFlags order = C1WinC1FlexGridSortFlagsAscending | C1WinC1FlexGridSortFlagsIgnoreCase Sortメソッドを呼び出しますc1FlexGrid1Sort(order 2)

C

方法1 2番目の列を降順で並べ替えますc1FlexGrid1Sort(C1WinC1FlexGridSortFlagsDescending 2)

方法2 SortFlagを使用して複数の並べ替えオプションを指定しますDim order As C1WinC1FlexGridSortFlags = C1WinC1FlexGridSortFlagsAscending Or C1WinC1FlexGridSortFlagsIgnoreCase

Sortメソッドを呼び出しますc1FlexGrid1Sort(order 2)

VBNET

複数列を並べ替えますc1FlexGrid1Cols[2]Sort = SortFlagsAscendingc1FlexGrid1Cols[3]Sort = SortFlagsDescending Sortメソッドを呼び出しますc1FlexGrid1Sort(SortFlagsUseColSort 2 3)

C

複数列を並べ替えますc1FlexGrid1Cols(2)Sort = SortFlagsAscendingc1FlexGrid1Cols(3)Sort = SortFlagsDescending

Sortメソッドを呼び出しますc1FlexGrid1Sort(SortFlagsUseColSort 2 3)

VBNET

グリッドの複数の列での並べ替えを許可します c1FlexGrid1AllowSorting = AllowSortingEnumMultiColumn

C

FlexGrid for WinForms

124 Copyright copy GrapeCity Inc All rights reserved

RevertUndo SortingTo remove sorting from the grid you can set SortDefinition property of the C1FlexGrid class to an empty string

Below code how to remove sorting from the WinForms FlexGrid

Disable Sort on a Particular ColumnTo disable sorting on a particular column you need to set the AllowSorting property of that Column object to false

Use the code below to disable sorting on a particular column of the WinForms FlexGrid

Sort OrderOrder of sorting usually varies in case of bound and unbound mode When a column header is clicked in case of boundmode sorting is done same as DefaultViewSort property of the data table However in case of unbound mode columnis sorted either according to StringCompare method or by differentiating the lower and upper case according to theculture

Refer to the code below to specify sorting order of a WinForms FlexGrid column

グリッドの複数の列での並べ替えを許可しますc1FlexGrid1AllowSorting = AllowSortingEnumMultiColumn

VBNET

並べ替えを削除します c1FlexGrid1SortDefinition = stringEmpty

C

並べ替えを削除しますc1FlexGrid1SortDefinition = StringEmpty

VBNET

グリッドの特定の列での並べ替えを無効にしますc1FlexGrid1Cols[2]AllowSorting = false

C

グリッドの特定の列での並べ替えを無効にしますc1FlexGrid1Cols(2)AllowSorting = False

VBNET

C1WinC1FlexGridSortFlags order = C1WinC1FlexGridSortFlagsAscending | C1WinC1FlexGridSortFlagsIgnoreCase c1FlexGrid1Sort(order 2)

C

Dim order As C1WinC1FlexGridSortFlags = C1WinC1FlexGridSortFlagsAscending Or C1WinC1FlexGridSortFlagsIgnoreCasec1FlexGrid1Sort(order 2)

VBNET

FlexGrid for WinForms

125 Copyright copy GrapeCity Inc All rights reserved

Custom SortingFlexGrid provides several sorting options which are required for most commonly used scenarios such as ignore case usethe display value etc However if you need to have more flexibility and control over sort operation you can even writeyour own custom logic using the IComparer class For instance the example below sorts the Name column by fileextensions In the sample code custom logic to sort by file extension is implemented in the FileNameComparer class whichis then passed as parameter to Sort() method of the C1FlexGrid class

The code below demonstrates how to apply custom sorting on the WinForms FlexGrid columns

c1FlexGrid1Sort(new FileNameComparer(c1FlexGrid1 eOrder)) class FileNameComparer IComparer C1FlexGrid c1FlexGrid1 bool _desc

ctor public FileNameComparer(C1FlexGrid flex SortFlags order) c1FlexGrid1 = flex _desc = ((order amp SortFlagsDescending) = 0) IComparer public int Compare(object r1 object r2) ファイル名を取得します string s1 = (string)c1FlexGrid1[((Row)r1)Index Name] string s2 = (string)c1FlexGrid1[((Row)r2)Index Name]

拡張機能を比較します int icmp = stringCompare(PathGetExtension(s1) PathGetExtension(s2) true)

並べ替え順(昇順または降順)を返します return (_desc) -icmp icmp

C

C1FlexGrid1Sort(New FileNameComparer(C1FlexGrid1 SortFlagsAscending))

Public Class FileNameComparer Implements IComparer

Private c1FlexGrid1 As C1FlexGrid Private _desc As Boolean

Public Sub New(ByVal flex As C1FlexGrid ByVal order As SortFlags) c1FlexGrid1 = flex _desc = ((order And SortFlagsDescending) ltgt 0) End Sub

Public Function Compare(r1 As Object r2 As Object) As Integer Implements IComparerCompare Dim s1 As String = CStr(c1FlexGrid1((CType(r1 Row))Index Name)) Dim s2 As String = CStr(c1FlexGrid1((CType(r2 Row))Index Name)) Dim icmp As Integer = StringCompare(PathGetExtension(s1) PathGetExtension(s2) True) Return If((_desc) -icmp icmp) End Function

VBNET

FlexGrid for WinForms

126 Copyright copy GrapeCity Inc All rights reserved

For detailed implementation of custom sorting see the product sample named Custom Sort

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing WinFormsEdition using ComponentOneControlPanelexe

並べ替えのインジケータ

FlexGrid displays sort indicator a small triangular arrow sign to indicate the direction of sorting The grid alsoprovides flexibility to hide display position or customize the indicator

Hide or Display Sort IndicatorFlexGrid by default displays the sort indicator when a column header is clicked to sort the columns However you canhide the indicator by setting the ShowSortPosition property to None The property accepts valuesfrom ShowSortPositionEnum enumeration

Use the code below to hide the sort indicator displayed on the sorted WinForms FlexGrid column

Position Sort IndicatorSort indicator by default gets displayed towards the right side of the header cell However when the filtering isapplied on a column the sort indicator displays on top of the header cell to give place to the filtering icon You can fixthe position of sort indicator by setting value of ShowSortPosition property to Top or Right

Customize the position of column sort indicator in WinForms FlexGrid using the code below

Customize Sort IndicatorFlexGrid provides the GlyphEnum enumeration which lets you specify the image to be used for sort indicator Formore information on the GlyphEnum and glyph customization see Custom Glyphs

並べ替えインジケータを非表示にしますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumNone

C

並べ替えインジケータを非表示にしますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumNone

VBNET

並べ替えインジケータの位置を上に変更しますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumTop

C

並べ替えインジケータの位置を上に変更しますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumTop

VBNET

FlexGrid for WinForms

127 Copyright copy GrapeCity Inc All rights reserved

フィルタ

Grid filtering lets you narrow down display records according to a specified condition applied on a column It is especially useful in case of large data sets asit lets you easily analyze data by displaying a specific type of records only

This section discusses about the process types and customization of filters

Topic Snapshot Content

Filter Operations Discusses about how to enable or apply filtering and other related operations

Allow FilteringFiltering through CodeCustom FilteringRemove FilteringTypes of Filters

Filter UI Discusses about filtering icon its customization and how to set the filter language

Show Filter IconUse Custom IconsChange Filter Language

フィルタの操作

Data filtering in a grid can be performed in two ways

Header-based Filter

In header-based filtering an icon is displayed in the header cell of column which gives you options to specify the filter in a drop-down and alsoindicates if the filter is applied on a particular column In FlexGrid this behavior can be achieved by simply using AllowFiltering property of the gridIn this case filter does not require any extra real estate on the screen This approach also gives you flexibility to customize and create better filtereditors More details about same is given in the sections below

Filter Row

Filter row is a row dedicated for displaying the filtering criteria and appears just below the column header So in this case user can always see thefiltered columns and their current filtering criteria But this added advantage comes at the cost of extra screen real estate that a filter row needs InFlexGrid you can easily achieve filter row using the custom implementation For implementation see the product sample named Filter Row

Note The Filter Row sample is located at DocumentsComponentOne SamplesWinFormsv452C1FlexGridCS on your system if you haveinstalled the samples while installing WinForms Edition using ComponentOneControlPanelexe

Allow FilteringIn FlexGrid filtering can be enabled by setting the C1FlexGridAllowFiltering property to true This enables the default ColumnFilter on allcolumns of the grid The ColumnFilter lets the users choose from ValueFilter and ConditionFilter at runtime

FlexGrid for WinForms

128 Copyright copy GrapeCity Inc All rights reserved

You can also specify the filter types for each column by setting the AllowFiltering property of each Column object AllowFiltering property ofcolumn lets you choose from any of the following values

Value Description

Default Enables the ColumnFilter which is a combination of ValueFilter and ConditionFilter and gives user a runtime option to choose eitherof them

ByValue Enables ValueFilter which contains a checkbox list of values present in that column User can check off the values that should not bedisplayed in the filtered output

ByCondition Enables ConditionFilter which lets you specify combination of two conditions such as equals greater than contains etc Youcan combine the specified conditions using And and Or operator

Custom Lets you instantiate a custom filter and explicitly assign it to Filter property of the column

None Disables filtering for that column

Use the following code snippet to enable a condition filter on first column of the WinForms FlexGrid

For more details regarding abovementioned filter types see Types of Filters

Filtering through CodeAlthough AllowFiltering property of grid enables grid filtering and can be used in most common scenarios there may be cases where you need tofurther fine tune the filter options This can be achieved by modifying AllowFiltering and Filter properties of individual columns For example thecode below enables filtering in the WinForms FlexGrid but restricts the filtering to columns of type string

You can also customize the filtering process further by creating filters and assigning them to columns or by retrieving existing filters and modifyingtheir properties For example the code below creates a ConditionFilter in the WinForms FlexGrid configures it to select all items that are equal toGermany and then assigns the new filter to the ShipCountry column

グリッドでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = true 列1に対してフィルタを指定しますc1FlexGrid1Cols[1]AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

C

グリッドでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = True

列1に対してフィルタを指定しますc1FlexGrid1Cols(1)AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

VBNET

文字列型の列にフィルタリングを制限します foreach (Column c in c1FlexGrid1Cols) cAllowFiltering = cDataType == typeof(string) AllowFilteringDefault AllowFilteringNone

C

文字列型の列にフィルタリングを制限しますFor Each c As Column In c1FlexGrid1Cols cAllowFiltering = If(cDataType Is GetType(String) AllowFilteringDefault AllowFilteringNone)Next

VBNET

グリッドでフィルタリングを有効にします c1FlexGrid1AllowFiltering = true 新しいConditionFilterを作成します C1WinC1FlexGridConditionFilter Filter Filter = new C1WinC1FlexGridConditionFilter()

C

FlexGrid for WinForms

129 Copyright copy GrapeCity Inc All rights reserved

Custom FilteringWhen filtering is applied to FlexGrid it hides the rows that do not qualify the filtering criteria by setting their Visible property to false However insome cases you may want to customize this behavior For such scenarios you can use the BeforeFilter and AfterFilter events fired by FlexGridThe below example customizes the filtering behavior of WinForms FlexGrid by applying a different style to non-qualifying rows instead of hidingthem

Germanyのアイテムを絞り込むためのフィルタを作成します FilterCondition1Operator = C1WinC1FlexGridConditionOperatorEquals FilterCondition1Parameter = Germany 「ShipCountry」列に新しいフィルタを割り当てます c1FlexGrid1Cols[ShipCountry]Filter = Filter フィルタを適用します c1FlexGrid1ApplyFilters()

グリッドでフィルタリングを有効にしますc1FlexGrid1AllowFiltering = True

新しいConditionFilterを作成しますDim Filter As C1WinC1FlexGridConditionFilterFilter = New C1WinC1FlexGridConditionFilter()

Germanyのアイテムを絞り込むためのフィルタを作成しますFilterCondition1[Operator] = C1WinC1FlexGridConditionOperatorEqualsFilterCondition1Parameter = Germany

「ShipCountry」列に新しいフィルタを割り当てますc1FlexGrid1Cols(ShipCountry)Filter = Filter

フィルタを適用しますc1FlexGrid1ApplyFilters()

VBNET

private void c1FlexGrid1_BeforeFilter(object sender CancelEventArgs e) c1FlexGrid1BeginUpdate()

private void c1FlexGrid1_AfterFilter(object sender EventArgs e) フィルタリングされた行を表示するために使用されるスタイルを取得します var cs = c1FlexGrid1Styles[filteredOut]

すべての行にスタイルを適用します

C

FlexGrid for WinForms

130 Copyright copy GrapeCity Inc All rights reserved

The above code uses a custom style named filteredout which can be defined as shown in the code below

Remove FilteringUser can remove column filtering at runtime by using Clear option given in the filter UI of each column You can also remove filtering of the wholegrid programmatically by passing the empty string in FilterDefinition property of FlexGrid

Below code demonstrates how to clear all the filters from the WinForms FlexGrid

for (int r = c1FlexGrid1RowsFixed r lt c1FlexGrid1RowsCount r++) var row = c1FlexGrid1Rows[r] if (rowVisible) 通常の行スタイルをリセットします rowStyle = null else フィルタリングされた行 見えるようにしスタイルを適用します rowVisible = true rowStyle = cs

更新を再開します c1FlexGrid1EndUpdate()

Private Sub c1FlexGrid1_BeforeFilter(ByVal sender As Object ByVal e As CancelEventArgs) c1FlexGrid1BeginUpdate()End Sub

Private Sub c1FlexGrid1_AfterFilter(ByVal sender As Object ByVal e As EventArgs) フィルタリングされた行を表示するために使用されるスタイルを取得します Dim cs = c1FlexGrid1Styles(filteredOut)

すべての行にスタイルを適用します For r = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 Dim row = c1FlexGrid1Rows(r)

If rowVisible Then 通常の行スタイルをリセットします rowStyle = Nothing Else フィルタリングされた行 見えるようにしスタイルを適用します rowVisible = True rowStyle = cs End If Next

更新を再開します c1FlexGrid1EndUpdate()End Sub

VBNET

フィルタによって除外された行のスタイルを作成しますvar cs = c1FlexGrid1StylesAdd(filteredOut)csBackColor = ColorLightGraycsForeColor = ColorDarkGray

C

フィルタによって除外された行のスタイルを作成しますDim cs = c1FlexGrid1StylesAdd(filteredOut)csBackColor = ColorLightGraycsForeColor = ColorDarkGray

VBNET

フィルタ定義を空の文字列に設定してフィルタリングを削除しますc1FlexGrid1FilterDefinition = stringEmpty

C

FlexGrid for WinForms

131 Copyright copy GrapeCity Inc All rights reserved

フィルタ定義を空の文字列に設定してフィルタリングを削除しますc1FlexGrid1FilterDefinition = StringEmpty

VBNET

フィルタの種類

FlexGrid not only provides built-in filters such as Column filter Value filter and Condition Filter but also lets youcreate your own custom filter The built-in filters are provided through AllowFiltering property of Column class whichlets you set the type of filter to be applied on a particular column On the other hand the custom filters make use ofthe IC1ColumnFilter interface and the IC1ColumnFilterEditor interface This topic discusses the implementation ofbuilt-in and custom filters in detail

Column FilterColumn filter is the default filter that is applied to all the columns automatically when AllowFiltering property of thegrid is set to true The ColumnFilter is a combination of ValueFilter and ConditionFilter (discussed below) and givesuser an option to choose either of them at runtime While working with code you can use its ValueFilterand ConditionFilter properties to access the two types of filters The filter also provides Apply method to apply filterto a value and Reset method to reset the filter and hence making it inactive

Use the below code to apply column filter on ProductName column of the WinForms FlexGrid

列フィルタ(ProductNameが「C」で始まる製品をフィルター処理します)ColumnFilter colFilter = new ColumnFilter()colFilterConditionFilterCondition1Parameter = CcolFilterConditionFilterCondition1Operator = ConditionOperatorBeginsWithc1FlexGrid1Cols[ProductName]Filter = colFilter

C

列フィルタ(ProductNameが「C」で始まる製品をフィルター処理します) Dim colFilter As ColumnFilter = New ColumnFilter()

VBNET

FlexGrid for WinForms

132 Copyright copy GrapeCity Inc All rights reserved

Value FilterValue filter refers to the value based filter which gets enabled on setting the AllowFiltering property of column toByValue The ValueFilter provides the dropdown list of all values with checkbox which lets the user select the valueswhich are to be displayed in the output These values can be get or set through the ShowValues property You canalso set a limit on number of values to be displayed in the dropdown list by setting the ValuesLimit property Just likecolumn filter value filter also provides Apply method to apply filter to a value and Reset method to reset the filter

Below code shows how to apply ValueFilter on a column of the WinForms FlexGrid

Condition FilterCondition filter refers to a filter based on one or two logical conditions which can be enabled by setting theAllowFiltering property to ByCondition The ConditionFilter gives user an option to set the conditionsthrough Condition1 and Condition2 properties which can be combined using ANDOR operator by settingthe AndConditions property to filter the records Similar to other filters this class also provides Apply and Resetmethod

colFilterConditionFilterCondition1Parameter = C colFilterConditionFilterCondition1[Operator] = ConditionOperatorBeginsWith c1FlexGrid1Cols(ProductName)Filter = colFilter

値フィルタ(CategoryIdが12358である製品をフィルタ処理します)ValueFilter valueFilter = new ValueFilter()valueFilterShowValues = new object[] 1 2 3 5 8 c1FlexGrid1Cols[CategoryId]Filter = valueFilter

C

値フィルタ(CategoryIdが12358である製品をフィルタ処理します) Dim valueFilter As ValueFilter = New ValueFilter() valueFilterShowValues = New Object() 1 2 3 5 8 c1FlexGrid1Cols(CategoryId)Filter = valueFilter

VBNET

FlexGrid for WinForms

133 Copyright copy GrapeCity Inc All rights reserved

Below code demonstrates how to apply a ConditionFilter on a WinForms FlexGrid column

Custom FilterThe abovementioned filters provide you enough flexibility to implement most common filtering scenarios efficientlyIn addition custom filter option also lets you create your own filter to meet any other specialized requirements ofyour application To create a custom filter you need to create a filter class that implements the IC1ColumnFilterinterface and an editor class that implements the IC1ColumnFilterEditor interface Below example shows theimplementation of a custom string filter which lets you filter based on ranges

条件フィルタ(UnitPricegt = 50およびlt= 100の製品をフィルタ処理します)ConditionFilter conditionFilter = new ConditionFilter()conditionFilterCondition1Parameter = 50conditionFilterCondition1Operator = ConditionOperatorGreaterThanOrEqualToconditionFilterCondition2Parameter = 100conditionFilterCondition2Operator = ConditionOperatorLessThanOrEqualToconditionFilterAndConditions = truec1FlexGrid1Cols[UnitPrice]Filter = conditionFilter

C

条件フィルタ(UnitPricegt = 50およびlt= 100の製品をフィルタ処理します) Dim conditionFilter As ConditionFilter = New ConditionFilter() conditionFilterCondition1Parameter = 50 conditionFilterCondition1[Operator] = ConditionOperatorGreaterThanOrEqualTo conditionFilterCondition2Parameter = 100 conditionFilterCondition2[Operator] = ConditionOperatorLessThanOrEqualTo conditionFilterAndConditions = True c1FlexGrid1Cols(UnitPrice)Filter = conditionFilter

VBNET

FlexGrid for WinForms

134 Copyright copy GrapeCity Inc All rights reserved

Following is the code of a custom filter created for the WinForms FlexGrid Note that the class implementsIC1CustomFilter interface

StringFiltercs

class StringFilter C1WinC1FlexGridIC1ColumnFilter

ListltPointgt _ranges = new ListltPointgt()

ltsummarygt このフィッタが受け入れる文字列を定義するポイントのリストを取得します ltsummarygt public ListltPointgt Ranges get return _ranges

範囲リストが空でない場合フィルタはアクティブです public bool IsActive get return _rangesCount gt 0

フィルタをリセットします public void Reset() _rangesClear()

指定された日付にフィルタを適用します public bool Apply(object value) if (value = null)

C

FlexGrid for WinForms

135 Copyright copy GrapeCity Inc All rights reserved

var s = valueToString() if (sLength gt 0) int c = charToUpperInvariant(s[0]) foreach (var cr in _ranges) if (c gt= charToUpperInvariant((char)crX) ampamp c lt= charToUpperInvariant((char)crY)) return true return false

このフィルタのエディタコントロールを返します public C1WinC1FlexGridIC1ColumnFilterEditor GetEditor() return new StringFilterEditor()

Friend Class StringFilter Implements C1WinC1FlexGridIC1ColumnFilter Private _ranges As List(Of Point) = New List(Of Point)()

ltsummarygt このフィッタが受け入れる文字列を定義するポイントのリストを取得します ltsummarygt Public ReadOnly Property Ranges As List(Of Point) Get Return _ranges End Get End Property

範囲リストが空でない場合フィルタはアクティブです Public ReadOnly Property IsActive As Boolean Implements C1WinC1FlexGridIC1ColumnFilterIsActive Get Return _rangesCount gt 0 End Get End Property

フィルタをリセットします Public Sub Reset() Implements C1WinC1FlexGridIC1ColumnFilterReset _rangesClear() End Sub

指定された日付にフィルタを適用します Public Function Apply(ByVal value As Object) As Boolean Implements C1WinC1FlexGridIC1ColumnFilterApply If value IsNot Nothing Then Dim s = valueToString()

If sLength gt 0 Then Dim c As Integer = AscW(CharToUpperInvariant(s(0)))

VBNET

FlexGrid for WinForms

136 Copyright copy GrapeCity Inc All rights reserved

Following is the code of a custom class that implements IC1CustomFilterEditor interface

StringFilterEditorcs

For Each cr In _ranges

If c gt= AscW(CharToUpperInvariant(MicrosoftVisualBasicChrW(crX))) AndAlso c lt= AscW(CharToUpperInvariant(MicrosoftVisualBasicChrW(crY))) Then Return True End If Next End If End If

Return False End Function

このフィルタのエディタコントロールを返します Public Function GetEditor() As C1WinC1FlexGridIC1ColumnFilterEditor Implements C1WinC1FlexGridIC1ColumnFilterGetEditor Return New StringFilterEditor() End Function

End Class

public partial class StringFilterEditor UserControl C1WinC1FlexGridIC1ColumnFilterEditor StringFilter _filter

public StringFilterEditor() InitializeComponent()

public void Initialize(C1WinC1FlexGridC1FlexGridBase grid int columnIndex C1WinC1FlexGridIC1ColumnFilter filter) _filter = (StringFilter)filter

チェックボックスの値を初期化します foreach (var pt in _filterRanges) switch ((char)ptX) case A _chkAEChecked = true break case F _chkFJChecked = true break case K _chkKOChecked = true break case P _chkPTChecked = true

C

FlexGrid for WinForms

137 Copyright copy GrapeCity Inc All rights reserved

break case U _chkUZChecked = true break public void ApplyChanges() フィルタをリセットします _filterRangesClear()

選択した範囲を追加します foreach (Control ctl in thisControls) var cb = ctl as CheckBox if (cb = null ampamp cbChecked) var pt = new Point((int)cbText[0] (int)cbText[cbTextLength - 1]) _filterRangesAdd(pt) public bool KeepFormOpen get return false void _chkAE_CheckedChanged(object sender EventArgs e) var cb = sender as CheckBox cbFont = new Font(Font cbChecked FontStyleBold FontStyleRegular)

Public Partial Class StringFilterEditor Inherits UserControl Implements C1WinC1FlexGridIC1ColumnFilterEditor

Private _filter As StringFilter Public Sub New() InitializeComponent() End Sub

Public Sub Initialize(ByVal grid As C1WinC1FlexGridC1FlexGridBase ByVal columnIndex As Integer ByVal filter As C1WinC1FlexGridIC1ColumnFilter) Implements C1WinC1FlexGridIC1ColumnFilterEditorInitialize _filter = CType(filter StringFilter)

チェックボックスの値を初期化します For Each pt In _filterRanges

Select Case MicrosoftVisualBasicChrW(ptX) Case Ac _chkAEChecked = True Case Fc _chkFJChecked = True Case Kc _chkKOChecked = True Case Pc

VBNET

FlexGrid for WinForms

138 Copyright copy GrapeCity Inc All rights reserved

_chkPTChecked = True Case Uc _chkUZChecked = True End Select Next End Sub

Public Sub ApplyChanges() Implements C1WinC1FlexGridIC1ColumnFilterEditorApplyChanges フィルタをリセットします _filterRangesClear()

選択した範囲を追加します For Each ctl As Control In Controls Dim cb = TryCast(ctl CheckBox)

If cb IsNot Nothing AndAlso cbChecked Then Dim pt = New Point(MicrosoftVisualBasicAscW(cbText(0)) MicrosoftVisualBasicAscW(cbText(cbTextLength - 1))) _filterRangesAdd(pt) End If Next End Sub

Public ReadOnly Property KeepFormOpen As Boolean Implements C1WinC1FlexGridIC1ColumnFilterEditorKeepFormOpen Get Return False End Get End Property

Private Sub _chkAE_CheckedChanged(ByVal sender As Object ByVal e As EventArgs) Dim cb = TryCast(sender CheckBox) cbFont = New Font(MyBaseFont If(cbChecked FontStyleBold FontStyleRegular)) End Sub

End Class

フィルタUI

FlexGrid provides several options to flexibly customize the filtering UI and lets you create your own unique filter for yourapplication The control allows you to show hide and customize the filtering icon You can even change the language displaying infilter to meet your localization requirements

Show Filter Icon

FlexGrid by default shows the filtering icon( ) when mouse hovers over the filterable column header However you can chooseto display the filtering icon always by setting ShowFilterIcon property of the C1FlexGrid class to Always The property accepts thevalues from FilterIconVisibility enumeration

FlexGrid for WinForms

139 Copyright copy GrapeCity Inc All rights reserved

Use the code below to always display the filter icon on filtered columns of the WinForms FlexGrid

Use Custom IconsFlexGrid also lets you customize the filtering icon by using Glyphs property of the C1FlexGrid class which accepts an imagethrough GlyphEnum enumeration You can also change icon displayed on the current filtered column using the same enumerationFor more information about custom glyphs see Custom Glyphs

常にフィルタのアイコンを表示しますc1FlexGrid1ShowFilterIcon = C1WinC1FlexGridFilterIconVisibilityAlways

C

常にフィルタのアイコンを表示しますc1FlexGrid1ShowFilterIcon = C1WinC1FlexGridFilterIconVisibilityAlways

VBNET

FlexGrid for WinForms

140 Copyright copy GrapeCity Inc All rights reserved

Following code displays how to apply custom icons on filtered columns of the WinForms FlexGrid

Change Filter LanguageBy default FlexGrid localizes the column filter editor to use language specified by the CurrentUICulture setting However you canuse the Language property to override the default and specify the language to be used when grid displays the column filter editor

Use the below code to change the display language of filter in the WinForms FlexGrid

フィルタのアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilterEditor] = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilteredColumn] = ImageFromFile(filterico)

C

フィルタのアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilterEditor) = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilteredColumn) = ImageFromFile(filterico)

VBNET

フィルタ言語を日本語に設定しますc1FlexGrid1Language = C1UtilLocalizationLanguageJapanese

C

フィルタ言語を日本語に設定しますc1FlexGrid1Language = C1UtilLocalizationLanguageJapanese

VBNET

FlexGrid for WinForms

141 Copyright copy GrapeCity Inc All rights reserved

検索

With FlexGrid you can easily perform search either on the entire grid or just a specific column This topic discusseshow you can enable search in FlexGrid

Search in Entire GridTo search the entire FlexGrid you need to add the C1FlexGridSearchPanel control to the form and associate it with thegrid to be searched using SetC1FlexGridSearchPanel method The C1FlexGridSearchPanel control highlights thesearch results and filters the records having search results automatically However you can choose not to highlight theresults by setting the HighlightSearchResults to false It also provides a SearchMode property to set whether tostart the search automatically or on hitting the Search button or Enter key You can also set the watermark in searchbox as well as a time delay in search

Use the code below to search the entire WinForms FlexGrid using SearchPanel

検索パネルを検索対象のFlexGridに関連付けますc1FlexGridSearchPanel1SetC1FlexGridSearchPanel(c1FlexGrid1 c1FlexGridSearchPanel1)

検索を構成しますc1FlexGridSearchPanel1HighlightSearchResults = truec1FlexGridSearchPanel1SearchMode = C1WinC1FlexGridSearchModeAlways c1FlexGridSearchPanel1Watermark = Search productsc1FlexGridSearchPanel1SearchDelay = 2

C

検索パネルを検索対象のFlexGridに関連付けます

VBNET

FlexGrid for WinForms

142 Copyright copy GrapeCity Inc All rights reserved

Search in ColumnTo enable column-wise search FlexGrid provides AutoSearch property of the C1FlexGrid class which accepts valuesfrom AutoSearchEnum enumeration The enumeration lets you start downward column search from the first scrollablerow or from the current cursor position To search a value in a particular column you need to keep the cursor in thatcolumn and type the value to be searched and grid automatically jumps to the search result in that column You canalso set delay in search by setting the AutoSearchDelay property

Following code enables column-wise search in the WinForms FlexGrid

c1FlexGridSearchPanel1SetC1FlexGridSearchPanel(c1FlexGrid1 c1FlexGridSearchPanel1)

検索を構成しますc1FlexGridSearchPanel1HighlightSearchResults = Truec1FlexGridSearchPanel1SearchMode = C1WinC1FlexGridSearchModeAlwaysc1FlexGridSearchPanel1Watermark = Search productsc1FlexGridSearchPanel1SearchDelay = 2

一番上の行からの列単位の検索を有効にしますc1FlexGrid1AutoSearch = C1WinC1FlexGridAutoSearchEnumFromTopc1FlexGrid1AutoSearchDelay = 2

C

一番上の行からの列単位の検索を有効にしますc1FlexGrid1AutoSearch = C1WinC1FlexGridAutoSearchEnumFromTopc1FlexGrid1AutoSearchDelay = 2

VBNET

FlexGrid for WinForms

143 Copyright copy GrapeCity Inc All rights reserved

マージ

FlexGrid allows you to merge cells with same values making them span multiple rows or columns This capability is useful for enhancing appearance andclarity of data displayed in the grid The effect of these settings is similar to the HTML ltROWSPANgt and ltCOLSPANgt tags

Cell merging has several possible uses For example you can use it to create merged table headers merged data views or grids where the text spills intoadjacent columns This section discusses these scenarios in the topics below

Topic Snapshot Content

Auto-merge Discusses about how to enable automatic merging in grid

Free auto-mergeRestricted auto-mergeMerge table headers

Handle Spilling Text Discusses how to display long texts in normal and node rows

Handle Spill in Normal CellsHandle Text in Node Rows

Custom Merge Discusses about ways to customize the default merging behavior

Method 1 Use IComparer interfaceMethod 2 Override the GetMergedRange method

自動マージ

FlexGrid lets you enable automatic cell merging in the grid by setting the AllowMerging property to a value other than None Inaddition you need to set the AllowMerging property of each target row or column to true Merging occurs only if adjacent cellscontain the same non-empty string There is no method to force a pair of cells to merge The merging is done automaticallybased on the cell contents This feature makes it easy to provide merged views of sorted data where values in adjacent rowspresent repeated data

Free Auto-mergeFree auto-merge refers to merging of cells with just one pre-condition of having same values in adjacent cells To automaticallymerge the cells in a row or a column you simply need to set AllowMerging property of the C1FlexGrid class to Free and setAllowMerging property of the target row or column object to true

FlexGrid for WinForms

144 Copyright copy GrapeCity Inc All rights reserved

Below code shows how to apply free merging on a WinForms FlexGrid column

Restricted Auto-mergeIn most of the scenarios you would want the grid to merge the grid cells with same values only if cells above or in left directionare also merged This behavior is called restricted auto-merge and can be achieved by setting the C1FlexGridAllowMergingproperty to RestrictAll RestrictRows or RestrictCols This is required in addition to setting the AllowMerging property oftarget row or column to true

Use the code below to allow restricted auto-merging on a WinForms FlexGrid column

Merge Table HeadersMerging the header cells specially in case of multi-row header is another very common scenario used in grids and tables Tomerge the header cells you must set the C1FlexGridAllowMerging property to FixedOnly You must also set theAllowMerging property of designated row and columns to true In this case headers cells with same value merge together togive a simplified appearance

許可される結合の種類を指定しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFree 結合を許可する列を指定しますc1FlexGrid1Cols[2]AllowMerging = true

C

許可される結合の種類を指定しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFree

結合を許可する列を指定しますc1FlexGrid1Cols(2)AllowMerging = True

VBNET

結合を許可する列を指定しますc1FlexGrid1Cols[3]AllowMerging = true 左側のセルが結合されている場合にのみ列を結合しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumRestrictCols

C

結合を許可する列を指定しますc1FlexGrid1Cols(3)AllowMerging = True

左側のセルが結合されている場合にのみ列を結合しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumRestrictCols

VBNET

FlexGrid for WinForms

145 Copyright copy GrapeCity Inc All rights reserved

Following code demonstrates how to apply merging only on table headers of the WinForms FlexGrid

Custom Auto-mergeFlexGrid also provides a Custom option through AllowMerging enumeration In this case auto-merge is performed on cellrange collection provided using MergedRanges property of the C1FlexGrid class The custom auto-merge is performedindependent of cell content For instance below image shows the merging of two specified cell ranges despite of the differentcell values

固定の行と列の結合を許可しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

固定の行と列の結合を許可しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

FlexGrid for WinForms

146 Copyright copy GrapeCity Inc All rights reserved

Use the following code snippet to apply custom merge on the WinForms FlexGrid

結合のモードをアクティブにしますthisc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumCustom

いくつかのマージされた範囲を定義します 2つのセルは幅が広く1つのセルは高いですthisc1FlexGrid1MergedRangesAdd(2 2 2 3)

3つのセルは幅が広く3つのセルは高さですthisc1FlexGrid1MergedRangesAdd(5 2 7 4)

C

結合のモードをアクティブにしますMec1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumCustom

いくつかのマージされた範囲を定義します 2つのセルは幅が広く1つのセルは高いですMec1FlexGrid1MergedRangesAdd(2 2 2 3)

3つのセルは幅が広く3つのセルは高さですMec1FlexGrid1MergedRangesAdd(5 2 7 4)

VBNET

はみ出して表示されるセルの処理

In FlexGrid you can create the same behavior as excel for handling long text entries by spilling them into emptyadjacent cells This behavior not only helps you in handling long text entries of usual cells but also in displayingoutline nodes which are different from data rows This topic discusses these two scenarios in the following sectionsThese settings work on the grid level and does not need you to set AllowMerging property of specific row or column

Handle Spill in Normal CellsThis FlexGrid setting causes text that is too long to fit in a cell to spill into empty adjacent cells If you have a longentry in a cell and the adjacent cell is empty the entry spills onto the adjacent cells to occupy as much room as

FlexGrid for WinForms

147 Copyright copy GrapeCity Inc All rights reserved

needed This behavior can be achieved by setting the AllowMerging property to Spill For instance in the imagebelow long data strings from TestGroup column cells spill to the empty Flag column cells giving a better visibility ofdata while using the available space on the grid

Following code enables spilling of long text to adjacent empty cell in the WinForms FlexGrid

Handle Text in Node RowsThe Nodes setting is similar to Spill but only applies to outline nodes This setting is useful when data is organizedinto groups and the node rows contain information in a format different from the data rows For this you must setthe C1FlexGridAllowMerging property to Nodes

長いテキストを隣接する空のセルにこぼしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumSpill

C

長いテキストを隣接する空のセルにこぼしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumSpill

VBNET

FlexGrid for WinForms

148 Copyright copy GrapeCity Inc All rights reserved

Following code shows how to handle long text in node rows of the WinForms FlexGrid

ノード行の長いテキストを隣接する空のセルにスピルします c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumNodes

C

ノード行の長いテキストを隣接する空のセルにスピルしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumNodes

VBNET

カスタムのマージ

FlexGrid by default gives you enough options to merge in most common scenarios using AllowMerging propertyHowever there may be instances where you want to customize the merging options to get more out of your grid Youcan customize the default merging behavior in two ways

Method 1 Use IComparer InterfaceBy default the grid merges adjacent cells containing same non-null value In default scenario string comparisons arecase-sensitive and blanks are included However you can also merge cells using a case-insensitive comparison andtrimming blanks by writing a custom class that implements IComparer interface and assign it to CustomComparerproperty of the C1FlexGrid class

Method 2 Override the GetMergedRange MethodAnother way is to create a new class that derives from the C1FlexGrid class and overrides the GetMergedRangeand GetData methods to provide your own custom merging logic It merges the cells based on contextual

FlexGrid for WinForms

149 Copyright copy GrapeCity Inc All rights reserved

understanding of data in FlexGrid which is implemented through the overridden methods in the sample The belowexample demonstrates custom merging in timetable of each lecturer using the WinForms FlexGrid

public override CellRange GetMergedRange(int row int col bool clip) 結合のロジックで使用するID列のインデックスを保存します _colIndex = ColsIndexOf(LecturerID)

結合する時にカスタムデータを使用するようにフラグを設定します _doingMerge = true

基本クラスの結合のロジックを呼び出します(GetDataメソッドを使用してデータを取得します) CellRange cellRange = baseGetMergedRange(row col clip)

GetDataが通常どおりに動作するようにフラグをリセットします _doingMerge = false

結合された範囲を返します return cellRange

public override Object GetData(int row int col) 結合範囲を決定するためのデータを取得します ID列のコンテンツを追加して異なるIDの行のセルがマージされないようにします if (_doingMerge ampamp _colIndex gt -1 ampamp col = _colIndex) SystemDiagnosticsDebugWriteLine($rowcol) return baseGetDataDisplay(row col) + baseGetDataDisplay(row _colIndex)

C

FlexGrid for WinForms

150 Copyright copy GrapeCity Inc All rights reserved

For detailed implementation of more scenarios of custom merging see the product Projects named CustomMergeCustomMerge2 CustomMerge3 CustomMerge4

Note The abovementioned product samples are located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installingWinForms Edition using ComponentOneControlPanelexe

表示測定編集などするデータを取得します 基本クラスに通常どおり処理させます return baseGetData(row col)

Public Overrides Function GetMergedRange(ByVal row As Integer ByVal col As Integer ByVal clip As Boolean) As CellRange 結合のロジックで使用するID列のインデックスを保存します _colIndex = ColsIndexOf(LecturerID)

結合する時にカスタムデータを使用するようにフラグを設定します _doingMerge = True

基本クラスの結合のロジックを呼び出します(GetDataメソッドを使用してデータを取得します) Dim cellRange As CellRange = MyBaseGetMergedRange(row col clip)

GetDataが通常どおりに動作するようにフラグをリセットします _doingMerge = False

結合された範囲を返します Return cellRangeEnd Function

Public Overrides Function GetData(ByVal row As Integer ByVal col As Integer) As Object 結合範囲を決定するためのデータを取得します ID列のコンテンツを追加して異なるIDの行のセルがマージされないようにします If _doingMerge AndAlso _colIndex gt -1 AndAlso col ltgt _colIndex Then DebugWriteLine($rowcol) Return MyBaseGetDataDisplay(row col) + MyBaseGetDataDisplay(row _colIndex) End If

表示測定編集などするデータを取得します 基本クラスに通常どおり処理させます Return MyBaseGetData(row col)End Function

VBNET

FlexGrid for WinForms

151 Copyright copy GrapeCity Inc All rights reserved

グループ

Grouping refers to organizing the grid data into a hierarchical structure where rows with common column value aredisplayed as a group The feature also lets you expand or collapse the groups to facilitate easier analysis of grid data

In FlexGrid grouping can be achieved through code as well as through user interaction via column context menuand FlexGridGroupPanel control This topic discusses these ways and additional operations related to grouping

Grouping through CodeFlexGrid provides GroupDescriptions property to describe how data source items are grouped in the grid Thisproperty accepts the instance of any collection which implements IList interface (eg List) as its value The items of thecollection describe grouping using a property name as the criterion

Following code shows how to apply grouping in the WinForms FlexGrid through code

Grouping through Group Panel

CustomerIDでデータをグループ化しますc1FlexGrid1GroupDescriptions = new ListltGroupDescriptiongt() new GroupDescription(CustomerID)

C

CustomerIDでデータをグループ化しますc1FlexGrid1GroupDescriptions = New List(Of GroupDescription)() From New GroupDescription(CustomerID)

VBNET

FlexGrid for WinForms

152 Copyright copy GrapeCity Inc All rights reserved

FlexGrid also lets you create groups at runtime using an extension control named C1FlexGridGroupPanel which isprovided by the C1WinC1FlexGridGroupPanel assembly

To achieve grouping in FlexGrid at runtime add the C1FlexGridGroupPanel control to the form and bind it with thegrid to be bound using FlexGrid property of the C1FlexGridGroupPanel class Once a grid is bound to the grouppanel control you can drag and drop the columns to panel in order to group the grid by that column To create anested hierarchy of dragged columns you can drag multiple columns in the desired order You can also set themaximum number of groups allowed within FlexGrid using MaxGroups property of the C1FlexGridGroupPanel classBy default all the created groups appear in the expanded state To change this setting and display the groups incollapsed state by default you can set the AutoExpandAllGroups property to false The group panel control alsoprovides the Text property to display a string when no columns are dropped on the panel

Use the code below to apply grouping in WinForms FlexGrid through the FlexGridGroupPanel control

C1FlexGridGroupPanel c1FlexGridGroupPanel = new C1FlexGridGroupPanel()c1FlexGridGroupPanelBounds = new SystemDrawingRectangle(00 650 150)thisControlsAdd(c1FlexGridGroupPanel) C1FlexGridGroupPanelの一般プロパティを設定しますc1FlexGridGroupPanelFlexGrid = c1FlexGrid1c1FlexGridGroupPanelText = Drag the columns herec1FlexGridGroupPanelMaxGroups = 5c1FlexGridGroupPanelAutoExpandAllGroups = true

C

Dim c1FlexGridGroupPanel As C1FlexGridGroupPanel = New C1FlexGridGroupPanel() c1FlexGridGroupPanelBounds = New DrawingRectangle(0 0 650 150) MeControlsAdd(c1FlexGridGroupPanel)

VBNET

FlexGrid for WinForms

153 Copyright copy GrapeCity Inc All rights reserved

Grouping through Context MenuFlexGrid provides support for column context menu at run-time to facilitate quick actions related to columnoperations One of these context menu options is Group By This Column You can use this context menu option togroup the grid data by any of the columns at run-time Once grouping is applied you also get the Ungroup option toremove grouping To enable the column context menu you need to set ColumnContextMenuEnabled propertyprovided by the C1FlexGrid class to true By default this property is set to false

Grouping and MoreApart from the default features grouping in FlexGrid comes with many other options to give you ample flexibility tomeet your requirements

Use the SubtotalPosition property to change the position of group row which gets displayed above the groupby defaultSet the HideGroupedColumns property to true to hide the columns by which grid is groupedChange the format of group header by using the GroupHeaderFormat property By default the group row

C1FlexGridGroupPanelの一般プロパティを設定します c1FlexGridGroupPanelFlexGrid = c1FlexGrid1 c1FlexGridGroupPanelText = Drag the columns here c1FlexGridGroupPanelMaxGroups = 5 c1FlexGridGroupPanelAutoExpandAllGroups = True

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = true

C

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = True

VBNET

FlexGrid for WinForms

154 Copyright copy GrapeCity Inc All rights reserved

displays a string of namevalue formatSet the C1FlexGridAllowMerging property to AllowMergingEnumNodes to spill the long group headercontent into the adjacent empty cells For more information see Handle Text in Node RowsDisplay aggregate value of columns in group header by using Aggregate property of the Column classUse AllowSorting property to sort the groups based on their valuesUse the GridTreeStyle property to customize the appearance of outline tree that shows the grouping inFlexGrid For more information see Style the Tree Grid

FlexGrid for WinForms

155 Copyright copy GrapeCity Inc All rights reserved

集計

Summarizing data is one of the most important features of the grid where you can easily group the similar data andcalculate various types of aggregates such as Sum Average Count Max Min and more

In FlexGrid you can easily summarize data by using SubTotal method of the C1FlexGrid class It adds subtotal rows thatcontain aggregate data for the regular (non-subtotal) rows and also supports the hierarchical aggregates The method hasvarious overloads which gives you enough flexibility to deal with multiple summarizing related scenarios All theseoverloads have one parameter in common that is AggregateEnum which lets you set the type of aggregate you want toimplement Other parameters in various overloads let you set the outline level start and end column and column thatcontains values to be aggregated

Create SubtotalsBelow example demonstrates the use of SubTotal method in the WinForms FlexGrid for calculation of average aggregatebased on Score column

Style SubtotalsWhen the Subtotal method adds the rows with the aggregate information it automatically assigns in-built subtotal styles

グリッドに存在する既存の小計をすべてクリアしますc1FlexGrid1Subtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加しますc1FlexGrid1Subtotal(AggregateEnumAverage 1 3 3 4 Average for 0)

C

グリッドに存在する既存の小計をすべてクリアしますc1FlexGrid1Subtotal(AggregateEnumClear)

レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加しますc1FlexGrid1Subtotal(AggregateEnumAverage 1 3 3 4 Average for 0)

VBNET

FlexGrid for WinForms

156 Copyright copy GrapeCity Inc All rights reserved

to the new rows You can customize the appearance of the subtotal rows by changing the properties of the outline stylesin the designer with the Style Editor or using the code Below example demonstrates styling of subtotals at three levels inthe WinForms FlexGrid

Customize SubtotalsFlexGrid in addition to built-in aggregate options lets you create custom expressions in bound mode and use them assubtotals in groups along with aggregates You can specify the custom expressions for a column using GroupExpressionproperty of the Column class Below example demonstrates how to create a custom expression as a subtotal for Qualifiedcolumn of the WinForms FlexGrid

小計をレベル0でスタイル設定しますCellStyle s = c1FlexGrid1Styles[CellStyleEnumSubtotal0]sBackColor = ColorBlacksForeColor = ColorWhitesFont = new Font(c1FlexGrid1Font FontStyleBold) 小計をレベル1でスタイル設定しますs = c1FlexGrid1Styles[CellStyleEnumSubtotal1]sBackColor = ColorDarkBluesForeColor = ColorWhite

小計をレベル2でスタイル設定しますs = c1FlexGrid1Styles[CellStyleEnumSubtotal2]sBackColor = ColorDarkRedsForeColor = ColorWhitec1FlexGrid1AutoSizeCols()

C

Dim s As CellStyle = c1FlexGrid1Styles(CellStyleEnumSubtotal0) sBackColor = ColorBlack sForeColor = ColorWhite sFont = New Font(c1FlexGrid1Font FontStyleBold)

s = c1FlexGrid1Styles(CellStyleEnumSubtotal1) sBackColor = ColorDarkBlue sForeColor = ColorWhite

s = c1FlexGrid1Styles(CellStyleEnumSubtotal2) sBackColor = ColorDarkRed sForeColor = ColorWhite c1FlexGrid1AutoSizeCols()

VBNET

FlexGrid for WinForms

157 Copyright copy GrapeCity Inc All rights reserved

public void CustomizeSubTotal(C1FlexGrid c1FlexGrid1) ListltGroupDescriptiongt grps = new ListltGroupDescriptiongt() 列「Course」のグループを作成します GroupDescription grp = new GroupDescription(Course ListSortDirectionDescending true) grpsAdd(grp) 上記のグループに従ってFlexGridをグループ化します c1FlexGrid1GroupDescriptions = grps カスタムの計算式を使用してFlexGridに新しい列を追加します var column = c1FlexGrid1ColsAdd() columnName = Qualified columnDataType = typeof(object) columnCaption = Qualified(gt5000) columnAllowEditing = false columnExpression = [Attendance] [Score] GroupExpression の実装 c1FlexGrid1Cols[Score]GroupExpression = =Average([Score]) c1FlexGrid1Cols[Attendance]GroupExpression = =Average([Attendance]) c1FlexGrid1Cols[Qualified]GroupExpression = =iif(Average([Score][Attendance])lt5000falsetrue) c1FlexGrid1AutoSizeCols()

C

Public Sub CustomizeSubTotal(ByVal c1FlexGrid1 As C1FlexGrid) Dim grps As List(Of GroupDescription) = New List(Of GroupDescription)() 列「Course」のグループを作成します Dim grp As GroupDescription = New GroupDescription(Course ListSortDirectionDescending True) grpsAdd(grp)

上記のグループに従ってFlexGridをグループ化します c1FlexGrid1GroupDescriptions = grps

カスタムの計算式を使用してFlexGridに新しい列を追加します Dim column = c1FlexGrid1ColsAdd()

VBNET

FlexGrid for WinForms

158 Copyright copy GrapeCity Inc All rights reserved

columnName = Qualified columnDataType = GetType(Object) columnCaption = Qualified(gt5000) columnAllowEditing = False columnExpression = [Attendance] [Score]

GroupExpression の実装 c1FlexGrid1Cols(Score)GroupExpression = =Average([Score]) c1FlexGrid1Cols(Attendance)GroupExpression = =Average([Attendance]) c1FlexGrid1Cols(Qualified)GroupExpression = =iif(Average([Score][Attendance])lt5000falsetrue) c1FlexGrid1AutoSizeCols()End Sub

FlexGrid for WinForms

159 Copyright copy GrapeCity Inc All rights reserved

ツリーグリッド

OverviewOne of the unique and popular features of the FlexGrid control is the ability to add hierarchical grouping to regulardata grid and display it in a tree like structure called Tree Grid The Tree Grid control is very similar to the one you seein a TreeView control It shows an indented structure with collapse or expand icon next to each node row so the usercan expand and collapse the outline to see the desired level of detail by clicking on the nodes

Although you can create simple outline trees using FlexGrid grouping Tree Grid helps you implement more advanceduse cases such as displaying customer and order details In a usual grid showing such data it is difficult to see thedetails of each customer and order In such case you can create a Tree Grid to group the data in a hierarchicalstructure for better view and accessibility of information

Quick BindingLoading data in a Tree Grid is exactly the same as loading in a regular grid If the data source is available at designtime you can use the Visual Studio Property Window to set the grids DataSource property of the C1FlexGrid class andbind the grid to the data without writing even a single line of code For detailed steps see Bound Mode

You can also set the DataSource property through code Following code shows how to use the DataSource propertyto populate data in the WinForms Tree Grid

private void Bound_Node_Load(object sender EventArgs e) FlexGridを連結します BindGrid(_gridBound)

public void BindGrid(C1FlexGrid grid) DataTable _dt = new DataTable() データを取得します var fields = Country City SalesPerson Quantity ExtendedPrice var sql = stringFormat(SELECT 0 FROM Invoices ORDER BY 0 fields)

C

FlexGrid for WinForms

160 Copyright copy GrapeCity Inc All rights reserved

The code uses an OleDbDataAdapter to fill a DataTable with data then assigns datatable to DataSource property ofthe grid To turn this regular grid in a Tree grid you need to insert the node rows which is discussed in the sectionbelow

Create Nodes (Bound and Unbound Mode)To create a Tree Grid FlexGrid introduces a concept of Node rows These rows do not contain regular data and aresimply header rows under which similar data is grouped just like nodes in a usual TreeView control You can alsodefine the hierarchy of these nodes by setting the Level property These nodes can be collapsed and expanded to hideor show the data they contain The Tree Grid can be displayed in any column defined by the GridTreeColumnproperty By default this property is set to -1 which causes the tree not to be displayed at all

Bound Mode (Using InsertNode Method)

You can create node rows using InsertNode method of the RowCollection class which inserts a new node row at a

var da = new OleDbDataAdapter(sql GetConnectionString()) daFill(_dt) グリッドにデータを連結します gridDataSource = _dt ExtendedPrice 列を書式設定します gridCols[ExtendedPrice]Format = n2

static string GetConnectionString() string path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) + ComponentOne SamplesCommon string conn = provider=microsoftjetoledb40data source=0c1nwindmdb return stringFormat(conn path)

Private Sub Bound_Node_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを連結します BindGrid(_gridBound) End Sub

Public Sub BindGrid(ByVal grid As C1FlexGrid) Dim _dt As DataTable = New DataTable() データを取得します Dim fields = Country City SalesPerson Quantity ExtendedPrice Dim sql = StringFormat(SELECT 0 FROM Invoices ORDER BY 0 fields) Dim da = New OleDbDataAdapter(sql GetConnectionString()) daFill(_dt) グリッドにデータを連結します gridDataSource = _dt ExtendedPrice 列を書式設定します gridCols(ExtendedPrice)Format = n2 End Sub

Private Shared Function GetConnectionString() As String Dim path As String = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) amp ComponentOne SamplesCommon Dim conn As String = provider=microsoftjetoledb40data source=0c1nwindmdb Return StringFormat(conn path) End Function

VBNET

FlexGrid for WinForms

161 Copyright copy GrapeCity Inc All rights reserved

specified index This is the low-level way of inserting totals and building outlines

The GroupBy method used here inserts node rows by grouping identical values To obtain a Node object you caneither use return value of the InsertNode method or retrieve the node for an existing row using the IsNode property

Use the following code to create nodes using InsertNode method in the bound WinForms Tree Grid

private void Bound_Node_Load(object sender EventArgs e) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) GroupBy(_gridBound Country 0) GroupBy(_gridBound City 1) public void CreateTree(C1FlexGrid grid) gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)

void GroupBy(C1FlexGrid grid string columnName int level) レベル0でグループのスタイル設定します CellStyle s0 = gridStylesAdd(Group0) s0BackColor = ColorGray s0ForeColor = ColorWhite s0Font = new Font(gridFont FontStyleBold) レベル1でグループのスタイル設定します CellStyle s1 = gridStylesAdd(Group1) s1BackColor = ColorLightGray s1ForeColor = ColorBlack object current = null for (int r = gridRowsFixed r lt gridRowsCount r++)

C

FlexGrid for WinForms

162 Copyright copy GrapeCity Inc All rights reserved

if (gridRows[r]IsNode) var value = grid[r columnName] if (objectEquals(value current)) 値が変更されました ノードを挿入します gridRowsInsertNode(r level) if (level == 0) gridRows[r]Style = s0 else if (level == 1) gridRows[r]Style = s1 最初のスクロール可能な列にグループ名を表示します grid[r gridColsFixed] = value 現在の値を更新します current = value gridAutoSizeCols()

Private Sub Bound_Node_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) GroupBy(_gridBound Country 0) GroupBy(_gridBound City 1)End Sub

Public Sub CreateTree(ByVal grid As C1FlexGrid) gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)End Sub

Private Sub GroupBy(ByVal grid As C1FlexGrid ByVal columnName As String ByVal level As Integer) レベル0でグループのスタイル設定します Dim s0 As CellStyle = gridStylesAdd(Group0) s0BackColor = ColorGray s0ForeColor = ColorWhite s0Font = New Font(gridFont FontStyleBold) レベル1でグループのスタイル設定します Dim s1 As CellStyle = gridStylesAdd(Group1) s1BackColor = ColorLightGray s1ForeColor = ColorBlack Dim current As Object = Nothing Dim r As Integer = gridRowsFixed

While r And lt gridRowsCount End While

r += 1

If True Then

If Not gridRows(r)IsNode Then Dim value = grid(r columnName)

VBNET

FlexGrid for WinForms

163 Copyright copy GrapeCity Inc All rights reserved

The code also calls the AutoSizeCols method to ensure that the column is wide enough to accommodate the TreeGrid Finally it calls the GridTreeShow method to display the nodes

Also the Node class provides following methods and properties based on TreeView object model which can be usedto manage the Tree Grid

Checked Gets or sets the check state of cell defined by NodeRow and GridTreeColumnCollapsedExpanded Gets or sets collapsed or expanded state of the nodeData Gets or sets value in the cell defined by NodeRow and GridTreeColumnImage Gets or sets image in the cell defined by NodeRow and GridTreeColumnLevel Gets or sets node level in the Tree Grid

You can also explore the outline structure using the following properties and methods

Children Gets number of child nodes under this nodeGetCellRange Gets the CellRange object that described range of rows that belong to this nodeGetNode Gets the node that has a given relationship to this node (parent first child next sibling and so on)Nodes Gets a node array containing child nodes of this node

Bound Mode (Using Subtotal Method)

In bound mode another way to create nodes is using the Subtotal method To make the Tree Grid really useful thenode rows must include summary information for the data they contain

If you create Tree Grid using the Subtotal method the subtotals are added automatically The method scans theentire grid and automatically inserts node rows with optional subtotals at locations where the grid data changes

This is the high-level way of inserting totals and building outlines

If Not ObjectEquals(value current) Then 値が変更されました ノードを挿入します gridRowsInsertNode(r level)

If level = 0 Then gridRows(r)Style = s0 ElseIf level = 1 Then gridRows(r)Style = s1 End If

最初のスクロール可能な列にグループ名を表示します grid(r gridColsFixed) = value 現在の値を更新します current = value End If End IfEnd If gridAutoSizeCols()End Sub

FlexGrid for WinForms

164 Copyright copy GrapeCity Inc All rights reserved

The first parameter of the Subtotal method is AggregateEnum enumeration which calculates various types ofaggregates like Sum Average Count Max Min and others In the code below Subtotal method of the C1FlexGridclass is used for creating nodes in a bound WinForms Tree Grid

private void SubtotalNode_Bound_Load(object sender EventArgs e) FlexGridを取得します BindGrid(_gridBound) shows Tree in Bound FlexGrid CreateTree(_gridBound) 連結されたFlexGridに小計を作成します CreateSubTotal(_gridBound)public void BindGrid(C1FlexGrid grid) DataTable dt = new DataTable() dtColumnsAdd(ID typeof(int)) dtColumnsAdd(Name typeof(string)) dtColumnsAdd(Course typeof(string)) dtColumnsAdd(Score typeof(int)) dtColumnsAdd(Attendance typeof(int)) dtColumnsAdd(Country typeof(string)) サンプルデータ dtRowsAdd(1 Helen Bennett ComputerScience 79 84 Spain) dtRowsAdd(2 Ana Trujillo Biology 78 87 Mexico) dtRowsAdd(3 Antonio Moreno Aeronautics 71 70 Spain) dtRowsAdd(4 Paolo Accorti Biology 74 63 Spain) dtRowsAdd(5 Elizabeth Brown ComputerScience 80 93 Mexico) dtRowsAdd(6 Jaime Yorres Biology 61 48 Spain) dtRowsAdd(7 Yvonne Moncada Aeronautics 85 78 Mexico) dtRowsAdd(8 Martine Ranceacute Aeronautics 67 81 Spain) dtRowsAdd(9 Sergio Gutieacuterrezy ComputerScience 62 58 Mexico) dtRowsAdd(10 Thomas Hardy Aeronautics 94 92 Mexico) dtRowsAdd(11 Patricio Simpson Aeronautics 46 52 Spain) dtRowsAdd(12 Maria Anders ComputerScience 85 73 Spain) gridDataSource = dt gridAutoSizeCols() (gridDataSource as DataTable)DefaultViewSort = Course

C

FlexGrid for WinForms

165 Copyright copy GrapeCity Inc All rights reserved

FlexGridでツリーを作成しますpublic void CreateTree(C1FlexGrid grid) gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1) gridAutoSizeCols()public void CreateSubTotal(C1FlexGrid grid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加します gridSubtotal(AggregateEnumAverage 1 3 3 4 Average for 0) gridAutoSizeCols()

Private Sub SubtotalNode_Bound_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) Creates Subtotal(s) in Bound FlexGrid CreateSubTotal(_gridBound)End Sub

Public Sub BindGrid(ByVal grid As C1FlexGrid) Dim dt As DataTable = New DataTable() dtColumnsAdd(ID GetType(Integer)) dtColumnsAdd(Name GetType(String)) dtColumnsAdd(Course GetType(String)) dtColumnsAdd(Score GetType(Integer)) dtColumnsAdd(Attendance GetType(Integer)) dtColumnsAdd(Country GetType(String))

サンプルデータ dtRowsAdd(1 Helen Bennett ComputerScience 79 84 Spain) dtRowsAdd(2 Ana Trujillo Biology 78 87 Mexico) dtRowsAdd(3 Antonio Moreno Aeronautics 71 70 Spain) dtRowsAdd(4 Paolo Accorti Biology 74 63 Spain) dtRowsAdd(5 Elizabeth Brown ComputerScience 80 93 Mexico) dtRowsAdd(6 Jaime Yorres Biology 61 48 Spain) dtRowsAdd(7 Yvonne Moncada Aeronautics 85 78 Mexico) dtRowsAdd(8 Martine Ranceacute Aeronautics 67 81 Spain) dtRowsAdd(9 Sergio Gutieacuterrezy ComputerScience 62 58 Mexico) dtRowsAdd(10 Thomas Hardy Aeronautics 94 92 Mexico) dtRowsAdd(11 Patricio Simpson Aeronautics 46 52 Spain) dtRowsAdd(12 Maria Anders ComputerScience 85 73 Spain) gridDataSource = dt gridAutoSizeCols() TryCast(gridDataSource DataTable)DefaultViewSort = CourseEnd Sub

FlexGridでツリーを作成しますPublic Sub CreateTree(ByVal grid As C1FlexGrid) gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)

VBNET

FlexGrid for WinForms

166 Copyright copy GrapeCity Inc All rights reserved

Unbound Mode (Using Subtotal Method)

The Subtotal method is a very convenient and flexible way to create a tree grid It has a number of overloads thatallow you to specify which columns are to be grouped on and totaled on by index or by name whether to include acaption in the node rows that it inserts how to perform the grouping and so on

In the code below Subtotal method of the C1FlexGrid class is used for creating nodes in an unbound WinForms TreeGrid

gridAutoSizeCols()End Sub

Public Sub CreateSubTotal(ByVal grid As C1FlexGrid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加します gridSubtotal(AggregateEnumAverage 1 3 3 4 Average for 0) gridAutoSizeCols()End Sub

private void Unbound_Subtotal_Load(object sender EventArgs e) 連結されていないFlexGridにデータを追加します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) 連結されていないFlexGridに小計を作成します CreateSubTotal(_gridUnbound) public void PopulateGrid(C1FlexGrid grid) グリッドにデータを入力します Random rnd = new Random() gridRowsCount = 14 grid[0 1] = Direction grid[0 2] = Region CellRange rg = gridGetCellRange(0 3 0 gridColsCount - 1) rgData = Rnd

C

FlexGrid for WinForms

167 Copyright copy GrapeCity Inc All rights reserved

for (int r = 1 r lt gridRowsCount r++) grid[r 0] = r grid[r 1] = (r lt 7) Inbound Outbound grid[r 2] = (r lt 3) North (r lt 7) South (r lt 10) East West for (int c = 3 c lt gridColsCount c++) grid[r c] = rndNext(1000) gridCols[c]Format = gridAutoSizeCols()

FlexGridでツリーを作成しますprivate void ShowTreeNode(C1FlexGrid grid) ツリーを作成します gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols()

Creates Subtotal in FlexGridpublic void CreateSubTotal(C1FlexGrid grid) Clears any existing subtotal(s) present in grid gridSubtotal(AggregateEnumClear) for (int c = 3 c lt gridColsCount c++) Adds subtotals in grid gridSubtotal(AggregateEnumSum 0 -1 c Grand Total) gridSubtotal(AggregateEnumSum 2 2 c Total for 0) gridAutoSizeCols()

Private Sub Unbound_Subtotal_Load(ByVal sender As Object ByVal e As EventArgs) 連結されていないFlexGridにデータを追加します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) 連結されていないFlexGridに小計を作成します CreateSubTotal(_gridUnbound) End Sub

Public Sub PopulateGrid(ByVal grid As C1FlexGrid) グリッドにデータを入力します Dim rnd As Random = New Random() gridRowsCount = 14 grid(0 1) = Direction grid(0 2) = Region Dim rg As CellRange = gridGetCellRange(0 3 0 gridColsCount - 1) rgData = Rnd Dim r As Integer = 1

While r And lt gridRowsCount End While

VBNET

FlexGrid for WinForms

168 Copyright copy GrapeCity Inc All rights reserved

r += 1

If True Then grid(r 0) = r grid(r 1) = r And lt 7 Inbound Outbound grid(r 2) = r And lt 3 North r And lt 7 South r And lt 10 East West Dim c As Integer = 3

While c And lt gridColsCount End While

c += 1

If True Then grid(r c) = rnd[Next](1000) gridCols(c)Format = End If End If

gridAutoSizeCols() End Sub

FlexGridでツリーを作成します Private Sub ShowTreeNode(ByVal grid As C1FlexGrid) ツリーを作成しますFlexGridでツリーを作成します gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols() End Sub

FlexGridで小計を作成します Public Sub CreateSubTotal(ByVal grid As C1FlexGrid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) Dim c As Integer = 3

While c And lt gridColsCount End While

c += 1

If True Then グリッドに小計を追加します gridSubtotal(AggregateEnumSum 0 -1 c Grand Total) gridSubtotal(AggregateEnumSum 2 2 c Total for 0) End If

gridAutoSizeCols() End Sub

FlexGrid for WinForms

169 Copyright copy GrapeCity Inc All rights reserved

Unbound Mode(Using IsNode Property)

In an unbound grid you can turn regular rows into node rows by simply setting the IsNode property to true If youtry to turn a regular data bound row into a node it causes the grid to throw an exception

Use the following code to create nodes using IsNode property in an unbound WinForms Tree Grid

private void Unbound_Row_Load(object sender EventArgs e) 連結されていないFlexGridにデータを入力します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound)

private void PopulateGrid(C1FlexGrid grid) FlexGridをリセットします gridRowsCount = 0 gridColsCount = 2 string fileName = testxml xmlドキュメントをロードします XmlDocument xdoc = new XmlDocument() xdocLoad(fileName) XMLドキュメントを読み取りFlexGridのノードとして表示します ShowNode(_gridUnbound xdocChildNodes[1] 0) gridAutoSizeCols() FlexGridでツリーを作成しますprivate void ShowTreeNode(C1FlexGrid grid) ツリーを作成します gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols()

FlexGridにxmlノードを追加しますprivate void ShowNode(C1FlexGrid grid XmlNode node int level)

C

FlexGrid for WinForms

170 Copyright copy GrapeCity Inc All rights reserved

コメントノードをスキップします if (nodeNodeType == XmlNodeTypeComment) return 読み取りxmlノードの新しい行を追加します int row = gridRowsCount gridRowsAdd() グリッドのセルにxmlノードデータを割り当てます grid[row 0] = nodeName xmlノードに子が1つしかないかどうかを確認します if (nodeChildNodesCount == 1) グリッドのセルにノード値を設定します grid[row 1] = nodeInnerText 新しい行をノードにします gridRows[row]IsNode = true gridRows[row]NodeLevel = level ノードに子がある場合はそれらも取得します if (nodeChildNodesCount gt 1) 子を取得するために再帰します foreach (XmlNode child in nodeChildNodes) ShowNode(_gridUnbound child level + 1)

Private Sub Unbound_Row_Load(ByVal sender As Object ByVal e As EventArgs) 連結されていないFlexGridにデータを入力します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) End Sub

Private Sub PopulateGrid(ByVal grid As C1FlexGrid) FlexGridをリセットします gridRowsCount = 0 gridColsCount = 2 Dim fileName As String = testxml xmlドキュメントをロードします Dim xdoc As XmlDocument = New XmlDocument() xdocLoad(fileName) XMLドキュメントを読み取りFlexGridのノードとして表示します ShowNode(_gridUnbound xdocChildNodes(1) 0) gridAutoSizeCols() End Sub

FlexGridでツリーを作成します Private Sub ShowTreeNode(ByVal grid As C1FlexGrid) ツリーを作成します gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols() End Sub

FlexGridにxmlノードを追加します Private Sub ShowNode(ByVal grid As C1FlexGrid ByVal node As XmlNode ByVal level As Integer) コメントノードをスキップします If nodeNodeType Is XmlNodeTypeComment Then Return

VBNET

FlexGrid for WinForms

171 Copyright copy GrapeCity Inc All rights reserved

読み取りxmlノードの新しい行を追加します Dim row As Integer = gridRowsCount gridRowsAdd() グリッドのセルにxmlノードデータを割り当てます grid(row 0) = nodeName

xmlノードに子が1つしかないかどうかを確認します If nodeChildNodesCount = 1 Then グリッドのセルにノード値を設定します grid(row 1) = nodeInnerText End If

新しい行をノードにします gridRows(row)IsNode = True gridRows(row)NodeLevel = level

ノードに子がある場合はそれらも取得します If nodeChildNodesCount And gt Then End If

1

If True Then

子を取得するために再帰します For Each child As XmlNode In nodeChildNodes ShowNode(_gridUnbound child level + 1) Next End If End Sub

ノードの操作

Tree Grid not only allows you to present the data in a structured form but it also supports performing variousoperations with the nodes You can add delete move and fetch nodes by using various methods provided bythe Node class

FlexGrid for WinForms

172 Copyright copy GrapeCity Inc All rights reserved

Add NodeYou can add a node at a specific position in the Tree Grid using AddNode method of the Node class This appends anew node row to the collection The method takes NodeTypeEnum enumeration as its argument which lets youspecify a node with respect to another given node

The code below shows how to add a node in the WinForms Tree Grid at a specific location

private void cmbAdd_SelectionChangeCommitted(object sender SystemEventArgs e) 現在の行ノードを取得します Node nd = flexRows[flexRow]Node ユーザーの要求に応じて相対を追加します (could be a child or a sibling) ndAddNode((NodeTypeEnum)(cmbAddSelectedIndex + 2) cmbAddText) flexFocus()

C

Private Sub cmbAdd_SelectionChangeCommitted(ByVal sender As Object ByVal e As EventArgs) 現在の行ノードを取得します Dim nd As Node = flexRows(flexRow)Node ユーザーの要求に応じて相対を追加します (could be a child or a sibling) ndAddNode(CType(cmbAddSelectedIndex + 2 NodeTypeEnum) cmbAddText)

VBNET

FlexGrid for WinForms

173 Copyright copy GrapeCity Inc All rights reserved

Delete NodeYou can delete a selected node from the Tree Grid using RemoveNode method of the Node class

Following code demonstrates how to delete a node from the WinForms Tree Grid

Move NodeThe Tree Grid allows you to move the node rows to a new position using Move method of the Node class Themethod takes NodeMoveEnum enumeration as an argument which lets you specify the direction in which node hasto be moved

Use the code below to move a node of the WinForms Tree Grid to a new position

flexFocus()End Sub

private void btnDelete_Click(object sender SystemEventArgs e) 現在のノードを取得します Node nd = null if ( flexRowsCount gt 0 ampamp flexRow gt= 0 ampamp flexRow lt flexRowsCount) nd = flexRows[flexRow]Node if (nd = null) FlexGridからノードを削除します ndRemoveNode() flexFocus()

C

Private Sub btnDelete_Click(ByVal sender As Object ByVal e As EventArgs) 現在のノードを取得します Dim nd As Node = Nothing

If flexRowsCount gt 0 AndAlso flexRow gt= 0 AndAlso flexRow lt flexRowsCount Then nd = flexRows(flexRow)Node End If

If nd IsNot Nothing Then FlexGridからノードを削除します ndRemoveNode() flexFocus() End IfEnd Sub

VBNET

private void btnMove_Click(object sender SystemEventArgs e) 現在の行のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択した動きを適用します

C

FlexGrid for WinForms

174 Copyright copy GrapeCity Inc All rights reserved

Select NodesIn Tree Grid you can select the nodes to perform different operations using GetNode method of the Node class Themethod takes a parameter called NodeTypeEnum enumeration which specifies a node with respect to another givennode

The code below specifies how to fetch a specific node of the WinForms Tree Grid and show it in selected state

(これにより選択したノードが移動します) if (sender == btnMoveOut) ndMove(NodeMoveEnumOut) else if (sender == btnMoveIn) ndMove(NodeMoveEnumIn) else if (sender == btnMoveUp) ndMove(NodeMoveEnumUp) else if (sender == btnMoveDown) ndMove(NodeMoveEnumDown) else if (sender == btnMoveFirst) ndMove(NodeMoveEnumFirst) else if (sender == btnMoveLast) ndMove(NodeMoveEnumLast) ノードがまだ表示されていることを確認します ndEnsureVisible() flexFocus()

Private Sub btnMove_Click(ByVal sender As Object ByVal e As EventArgs) 現在の行のノードを取得します Dim nd As Node = flexRows(flexRow)Node

ユーザーが選択した動きを適用します (これにより選択したノードが移動します) If sender Is btnMoveOut Then ndMove(NodeMoveEnumOut) ElseIf sender Is btnMoveIn Then ndMove(NodeMoveEnum[In]) ElseIf sender Is btnMoveUp Then ndMove(NodeMoveEnumUp) ElseIf sender Is btnMoveDown Then ndMove(NodeMoveEnumDown) ElseIf sender Is btnMoveFirst Then ndMove(NodeMoveEnumFirst) ElseIf sender Is btnMoveLast Then ndMove(NodeMoveEnumLast) End If

ノードがまだ表示されていることを確認します ndEnsureVisible() flexFocus()End Sub

VBNET

private void cmbSelect_SelectionChangeCommitted(object sender SystemEventArgs e) 現在の行のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択したノードを取得します nd = ndGetNode((NodeTypeEnum)cmbSelectSelectedIndex) 失敗した場合はメッセージを表示します if (nd == null) MessageBoxShow(Cant find + cmbSelectText + for this node) return ノードを選択しそれが表示されていることを確認します(スクロールして表示します)

C

FlexGrid for WinForms

175 Copyright copy GrapeCity Inc All rights reserved

Expand and Collapse NodesYou can expand and collapse all nodes in your Tree Grid application using the Collapsed property of Node class asshown in the code below This feature makes it convenient to navigate through node headers as a group whenrequired

Following code shows how to expand and collapse nodes of the WinForms Tree Grid

ndSelect() ndEnsureVisible() flexFocus()

Private Sub cmbSelect_SelectionChangeCommitted(ByVal sender As Object ByVal e As EventArgs) 現在の行のノードを取得します Dim nd As Node = flexRows(flexRow)Node ユーザーが選択したノードを取得します nd = ndGetNode(CType(cmbSelectSelectedIndex NodeTypeEnum))

失敗した場合はメッセージを表示します If nd Is Nothing Then MessageBoxShow(Cant find amp cmbSelectText amp for this node) Return End If

ノードを選択しそれが表示されていることを確認します(スクロールして表示します) nd[Select]() ndEnsureVisible() flexFocus()End Sub

VBNET

foreach (Row row in flexRowsCastltRowgt()Where(rw =gt rwIsNode == true)) Node node = rowNode nodeCollapsed = false

foreach (Row row in flexRowsCastltRowgt()Where(rw =gt rwIsNode == true)) Node node = rowNode nodeCollapsed = true

C

For Each row As Row In flexRowsCast(Of Row)()Where(Function(rw) rwIsNode = True) Dim node As Node = rowNode nodeCollapsed = False Next

For Each row As Row In flexRowsCast(Of Row)()Where(Function(rw) rwIsNode = True) Dim node As Node = rowNode nodeCollapsed = True Next

VBNET

FlexGrid for WinForms

176 Copyright copy GrapeCity Inc All rights reserved

Drag and Drop NodesIn Tree Grid you can drag and drop a selected node to a specific position by handling the MouseUp MouseDownand MouseMove events

The code below lets the user drag and drop nodes of the WinForms Tree Grid

private void flex_MouseDown(object sender MouseEventArgs e) m_DragInfocheckDrag = false 左ボタンを押すと移動しません ドラッグするマウスの追跡を開始します if (eButton = MouseButtonsLeft) return if (chkDragChecked || m_DragInfodragging) return if (flexMouseRow lt flexRowsFixed || flexMouseCol = 0) return 現在の行とマウスの位置を保存します m_DragInforow = flexRow m_DragInfomouseDown = new Point(eX eY) チェックを開始します m_DragInfocheckDrag = true

private void flex_MouseMove(object sender MouseEventArgs e) チェックしてユーザーが許容範囲を超えた場合はドラッグを開始します if (m_DragInfocheckDrag || eButton = MouseButtonsLeft) return if (MathAbs(eX - m_DragInfomouseDownX) + MathAbs(eY - m_DragInfomouseDownY) lt= DRAGTOL) return フラグを更新します m_DragInfodragging = true Sets cursor and highlight node CellStyle cs = flexStyles[SourceNode] flexCursor = CursorsNoMove2D flexSetCellStyle(m_DragInforow 0 cs) ここにドロップできるかどうかを確認します Cursor c = (NoDropHere()) CursorsNo CursorsNoMove2D if (c = flexCursor) flexCursor = c private bool NoDropHere() カーソルの下の行は無効です if (flexMouseRow lt flexRowsFixed) return true カーソルの下の列が無効です if (flexMouseCol lt flexColsFixed) return true if (flexGetDataDisplay(flexRow 0) == SKU) return true return false private void flex_MouseUp(object sender MouseEventArgs e) マウスが再び下がるまでチェックしないでください m_DragInfocheckDrag = false Not dragging were done if (m_DragInfodragging) return ドラッグを停止します m_DragInfodragging = false flexSetCellStyle(m_DragInforow 0 (CellStyle)null) flexCursor = CursorsDefault ドロップが許可されているかどうかをテストします

C

FlexGrid for WinForms

177 Copyright copy GrapeCity Inc All rights reserved

if (NoDropHere()) return ノードを新しい親ノードに移動します Node ndSrc = flexRows[m_DragInforow]Node Node ndDst = flexRows[flexRow]Node ndSrcMove(NodeMoveEnumChildOf ndDst) ndSrcSelect()

internal struct DRAGINFO public bool dragging 現在ドラッグ中 public bool checkDrag 現在マウスをチェックしてドラッグを開始しています public int row ドラッグされている行のインデックス public Point mouseDown マウスダウンの位置

Private Sub flex_MouseDown(ByVal sender As Object ByVal e As MouseEventArgs) m_DragInfocheckDrag = False 左ボタンを押すと移動しません ドラッグするマウスの追跡を開始します If eButton IsNot MouseButtonsLeft Then Return If Not chkDragChecked OrElse m_DragInfodragging Then Return If flexMouseRow lt flexRowsFixed OrElse flexMouseCol ltgt 0 Then Return 現在の行とマウスの位置を保存します m_DragInforow = flexRow m_DragInfomouseDown = New Point(eX eY) チェックを開始します m_DragInfocheckDrag = True End Sub

Private Sub flex_MouseMove(ByVal sender As Object ByVal e As MouseEventArgs) チェックしてユーザーが許容範囲を超えた場合はドラッグを開始します If Not m_DragInfocheckDrag OrElse eButton IsNot MouseButtonsLeft Then Return If MathAbs(eX - m_DragInfomouseDownX) + MathAbs(eY - m_DragInfomouseDownY) lt= DRAGTOL Then Return フラグを更新します m_DragInfodragging = True カーソルを設定しノードを強調表示します Dim cs As CellStyle = flexStyles(SourceNode) flexCursor = CursorsNoMove2D flexSetCellStyle(m_DragInforow 0 cs) ここにドロップできるかどうかを確認します Dim c As Cursor = If((NoDropHere()) CursorsNo CursorsNoMove2D) If c IsNot flexCursor Then flexCursor = c End Sub

Private Function NoDropHere() As Boolean カーソルの下の行は無効です If flexMouseRow lt flexRowsFixed Then Return True カーソルの下の列が無効です If flexMouseCol lt flexColsFixed Then Return True If flexGetDataDisplay(flexRow 0) Is SKU Then Return True Return False End Function

Private Sub flex_MouseUp(ByVal sender As Object ByVal e As MouseEventArgs) マウスが再び下がるまでチェックしないでください m_DragInfocheckDrag = False If Not m_DragInfodragging Then Return ドラッグを停止します m_DragInfodragging = False

VBNET

FlexGrid for WinForms

178 Copyright copy GrapeCity Inc All rights reserved

flexSetCellStyle(m_DragInforow 0 CType(Nothing CellStyle)) flexCursor = Cursors[Default] ドロップが許可されているかどうかをテストします If NoDropHere() Then Return ノードを新しい親ノードに移動します Dim ndSrc As Node = flexRows(m_DragInforow)Node Dim ndDst As Node = flexRows(flexRow)Node ndSrcMove(NodeMoveEnumChildOf ndDst) ndSrc[Select]() End Sub

Friend Structure DRAGINFO Public dragging As Boolean 現在ドラッグ中 Public checkDrag As Boolean 現在マウスをチェックしてドラッグを開始しています Public row As Integer ドラッグされている行のインデックス Public mouseDown As Point マウスダウンの位置 End Structure

データの操作

In Tree Grid just like a usual grid you can also perform various operations at data level such as sorting and retainingthe changes

SortingTo apply sorting in Tree Grid you can select the parent node and sort the child nodes using Sort Method of the NodeClass You can specify the sorting order by using the SortFlags enumeration

Following code applies sorting on the WinForms Tree Grid

FlexGrid for WinForms

179 Copyright copy GrapeCity Inc All rights reserved

Retain the ChangesSo far we have discussed how to create trees and totals using the high-level Subtotal method as well as lower-level InsertNode and Aggregate methods

At this point it is important to remember that the Tree Grid is created based on the data but is not bound to it in anyway and is not automatically maintained when there are changes to the grid or to the data

For example if the user modifies a value in the column the subtotals will not be automatically updated If the usersorts the grid it refreshes the data and the subtotals disappear

There are two common ways to maintain the Tree Grid

1 Prevent the user from making any changes that would invalidate the tree This is the easiest option You can setthe grids AllowEditing AllowDragging and AllowSorting properties to false and prevent any changes thatwould affect the tree

2 Update the tree when there are changes to the data or to the grid You can attach handlers to thegrids AfterDataRefresh AfterSort and AfterEdit events and re-generate the outline appropriately

The second option is usually more interesting as it provides a quick and simple tool for dynamic data analysis Thisapproach is illustrated by a product sample Analyze shipped with the FlexGrid control The sample creates an initialoutline and allows users to reorder the columns When the column order changes the sample automatically re-sortsthe data and re-creates the outline

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing

private void btnSort_Click(object sender SystemEventArgs e) 現在のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択した並べ替えを適用します (これにより選択したノードの子が並べ替えられます) if (sender == btnSortAscending) ndSort(SortFlagsAscending) else ndSort(SortFlagsDescending) 完了 flexFocus()

C

Private Sub btnSort_Click(ByVal sender As Object ByVal e As EventArgs) 現在のノードを取得します Dim nd As Node = flexRows(flexRow)Node

ユーザーが選択した並べ替えを適用します (これにより選択したノードの子が並べ替えられます) If sender Is btnSortAscending Then ndSort(SortFlagsAscending) Else ndSort(SortFlagsDescending) End If

完了 flexFocus()End Sub

VBNET

FlexGrid for WinForms

180 Copyright copy GrapeCity Inc All rights reserved

WinForms Edition using ComponentOneControlPanelexe

In Create Nodes section we also learnt about implementing GroupBy method that inserts node rows groupingidentical values on a given column The code scans all the columns skipping existing node rows so it can be called toadd several levels of nodes and keeps track of the current value for the column being grouped on When the currentvalue changes a node row is inserted showing the new group name in the first scrollable column

However there are some challenges to maintain the grouping like the method assumes that data is sorted accordingto the outline structure Also the GroupBy method may insert rows which would cause the grid to flicker To avoidthis you would normally set the Redraw property to false before making the updates and set it back to true whendone

The DeferRefresh class is a simple utility that sets the grids Redraw property to false and restores its original valuewhen it is disposed This ensures that Redraw is properly restored even when exceptions happen during the updatesThe BindGrid method ensures that the grid is sorted in the order required by our outline structure

ツリーグリッドのカスタマイズ

FlexGrid allows you to customize Tree Grid by styling as well as by using various elements like checkboxes toexpandcollapse nodes or images as node icons A customized Tree Grid can make the outline tree nodes look moredistinctive and structured making it visually appealing and more understandable

Style Tree GridStyling a Tree Grid is similar to styling the FlexGrid control The Tree property returns a reference to a GridTree objectthat exposes several methods and properties used to customize the Tree Grid Following is the list of some commonlyused properties

Column Gets or sets the index of the column that contains the outline tree Setting this property to -1 causesthe outline tree to be hidden from the usersIndent Gets or sets the indent in pixels between adjacent node levels Higher indent levels cause the tree tobecome widerStyle Gets or sets the type of outline tree to display Use this property to determine whether the tree shouldinclude a button bar at the top to allow users to collapseexpand the entire tree whether lines andor symbolsshould be displayed and whether lines should be displayed connecting the tree to data rows as well as noderowsLineColor Gets or sets the color of the connecting linesLineStyle Gets or sets the style of the connecting lines

For more information on styling the tree grid see Styling and Appearance topic in FlexGrid documentation

Display Tree with CheckBoxesTo create a custom Tree Grid with checkbox and images you need to first initialize FlexGrid for creating Tree Grid andthen add nodes to the tree by using AddNode method of the RowCollection class

Now to implement checkboxes in Tree Grid you need to maintain the checkboxes in parent and child nodes Thismethod uses Checked property of the Node class which defines whether to show a checkbox for the node or not

FlexGrid for WinForms

181 Copyright copy GrapeCity Inc All rights reserved

The code below shows how to display checkboxes on tree nodes of the WinForms Tree Grid

void c1FlexGrid1_CellChecked(object sender C1WinC1FlexGridRowColEventArgs e) すべての子にチェック値を適用します var node = thisc1FlexGrid1Rows[eRow]Node UpdateCheckChildren(node) 親にチェック値を適用します UpdateCheckParent(node)

void UpdateCheckChildren(C1WinC1FlexGridNode node) var checkState = nodeChecked foreach (C1WinC1FlexGridNode child in nodeNodes) childChecked = checkState UpdateCheckChildren(child)

void UpdateCheckParent(C1WinC1FlexGridNode node) このノードの親を取得します var parent = nodeParent if (parent = null)

C

FlexGrid for WinForms

182 Copyright copy GrapeCity Inc All rights reserved

チェックされたチェックされていない子をカウントします int cntChecked = 0 int cntUnchecked = 0 int cntGrayed = 0 foreach (C1WinC1FlexGridNode child in parentNodes) switch (childChecked) case C1WinC1FlexGridCheckEnumChecked cntChecked++ break case C1WinC1FlexGridCheckEnumUnchecked cntUnchecked++ break case C1WinC1FlexGridCheckEnumGrayed cntGrayed++ break 親のチェック状態を更新します if (cntGrayed gt 0 || (cntChecked gt 0 ampamp cntUnchecked gt 0)) parentChecked = C1WinC1FlexGridCheckEnumGrayed else if (cntChecked gt 0 ampamp cntUnchecked == 0) parentChecked = C1WinC1FlexGridCheckEnumChecked else if (cntUnchecked gt 0 ampamp cntChecked == 0) parentChecked = C1WinC1FlexGridCheckEnumUnchecked 祖父も更新します UpdateCheckParent(parent)

Private Sub c1FlexGrid1_CellChecked(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) すべての子にチェック値を適用します Dim node = Mec1FlexGrid1Rows(eRow)Node UpdateCheckChildren(node) 親にチェック値を適用します UpdateCheckParent(node) End Sub

Private Sub UpdateCheckChildren(ByVal node As C1WinC1FlexGridNode) Dim checkState = nodeChecked

For Each child As C1WinC1FlexGridNode In nodeNodes childChecked = checkState MeUpdateCheckChildren(child) Next End Sub

Private Sub UpdateCheckParent(ByVal node As C1WinC1FlexGridNode) このノードの親を取得します Dim parent = nodeParent

If parent IsNot Nothing Then チェックされたチェックされていない子をカウントします

VBNET

FlexGrid for WinForms

183 Copyright copy GrapeCity Inc All rights reserved

Display Tree with ImagesTo add the images as your Tree Grid node icons you can use the AddImageFolder method for creating nodes relatedto files and assigning images to the nodes

Dim cntChecked As Integer = 0 Dim cntUnchecked As Integer = 0 Dim cntGrayed As Integer = 0

For Each child As C1WinC1FlexGridNode In parentNodes

Select Case childChecked Case C1WinC1FlexGridCheckEnumChecked cntChecked += 1 Case C1WinC1FlexGridCheckEnumUnchecked cntUnchecked += 1 Case C1WinC1FlexGridCheckEnumGrayed cntGrayed += 1 End Select Next

親のチェック状態を更新します If cntGrayed gt 0 OrElse cntChecked gt 0 AndAlso cntUnchecked gt 0 Then parentChecked = C1WinC1FlexGridCheckEnumGrayed ElseIf cntChecked gt 0 AndAlso cntUnchecked = 0 Then parentChecked = C1WinC1FlexGridCheckEnumChecked ElseIf cntUnchecked gt 0 AndAlso cntChecked = 0 Then parentChecked = C1WinC1FlexGridCheckEnumUnchecked End If

祖父も更新します UpdateCheckParent(parent) End If End Sub

FlexGrid for WinForms

184 Copyright copy GrapeCity Inc All rights reserved

Use the code below to display images or icons along with nodes of the WinForms Tree Grid

void AddImageFolder(string path int level) int cnt = 0 try ディレクトリ内のすべてのファイルをループします foreach (string file in DirectoryGetFiles(path)) ファイルごとにノードを作成しFlexGridに追加します var node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(file) 画像をノードに割り当てるためのコード ShowImage(node file) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt++ if (cnt gt 20) break catch try パスのすべてのサブディレクトリをループします foreach (string subPath in DirectoryGetDirectories(path))

C

FlexGrid for WinForms

185 Copyright copy GrapeCity Inc All rights reserved

ファイルごとにノードを作成しFlexGridに追加します var node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(subPath) 画像をノードに割り当てるためのコード ShowImage(node subPath) 現在のディレクトリのサブディレクトリファイルをトラバースします AddImageFolder(subPath level + 1) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt++ if (cnt gt 20) break catch

Private Sub AddImageFolder(ByVal path As String ByVal level As Integer) Dim cnt As Integer = 0

Try

ディレクトリ内のすべてのファイルをループします For Each file As String In DirectoryGetFiles(path) ファイルごとにノードを作成しFlexGridに追加します Dim node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(file)

画像をノードに割り当てるためのコード ShowImage(node file) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt += 1 If cnt gt 20 Then Exit For Next

Catch End Try

Try

パスのすべてのサブディレクトリをループします For Each subPath As String In DirectoryGetDirectories(path) ファイルごとにノードを作成しFlexGridに追加します Dim node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(subPath) 画像をノードに割り当てるためのコード ShowImage(node subPath) 現在のディレクトリのサブディレクトリファイルをトラバースします AddImageFolder(subPath level + 1) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt += 1 If cnt gt 20 Then Exit For Next

Catch End TryEnd Sub

VBNET

FlexGrid for WinForms

186 Copyright copy GrapeCity Inc All rights reserved

The above code uses a custom method called ShowImage to set the image for nodes based on its file extensions

public void ShowImage(C1WinC1FlexGridNode node string path) パスからファイル拡張子を取得します string extension = PathGetExtension(path) パスがファイルに属している場合 if (extension = ) ファイル拡張子に基づいてノードの画像を設定します switch (extension) case txt nodeImage = PropertiesResourcesTxt break case resx nodeImage = PropertiesResourcesTxt break case licx nodeImage = PropertiesResourcesTxt break case cs nodeImage = PropertiesResourcesTxt break case vb nodeImage = PropertiesResourcesTxt break case exe nodeImage = PropertiesResourcesExe break case dll nodeImage = PropertiesResourcesDll break case sln nodeImage = PropertiesResourcesVS break case csproj nodeImage = PropertiesResourcesVS break case bmp nodeImage = PropertiesResourcesImg break case png nodeImage = PropertiesResourcesImg break case gif nodeImage = PropertiesResourcesVideo break case accdb nodeImage = PropertiesResourcesAccess break default nodeImage = PropertiesResourcesUnknown break それ以外のパスはディレクトリフォルダに属しています else nodeImage = PropertiesResourcesFolder

C

FlexGrid for WinForms

187 Copyright copy GrapeCity Inc All rights reserved

Public Sub ShowImage(ByVal node As C1WinC1FlexGridNode ByVal path As String) パスからファイル拡張子を取得します Dim extension As String = PathGetExtension(path)

パスがファイルに属している場合 If Not Equals(extension ) Then

ファイル拡張子に基づいてノードの画像を設定します Select Case extension Case txt nodeImage = PropertiesResourcesTxt Case resx nodeImage = PropertiesResourcesTxt Case licx nodeImage = PropertiesResourcesTxt Case cs nodeImage = PropertiesResourcesTxt Case vb nodeImage = PropertiesResourcesTxt Case exe nodeImage = PropertiesResourcesExe Case dll nodeImage = PropertiesResourcesDll Case sln nodeImage = PropertiesResourcesVS Case csproj nodeImage = PropertiesResourcesVS Case bmp nodeImage = PropertiesResourcesImg Case png nodeImage = PropertiesResourcesImg Case gif nodeImage = PropertiesResourcesVideo Case accdb nodeImage = PropertiesResourcesAccess Case Else nodeImage = PropertiesResourcesUnknown それ以外のパスはディレクトリフォルダに属しています End Select Else nodeImage = PropertiesResourcesFolder End IfEnd Sub

VBNET

FlexGrid for WinForms

188 Copyright copy GrapeCity Inc All rights reserved

クリップボード

FlexGrid provides flexibility to perform various clipboard operations such as cut copy and paste on the editable griddata To enable automatic handling of common clipboard keys you need to set the AutoClipboard property to trueThe property handles following clipboard operations and their corresponding keys

Copy CTRL+C Ctrl+INS

Cut CTRL+X SHIFT+DEL

Paste CTRL+V SHIFT+INS

Delete DEL

The abovementioned clipboard operations do not have any affect on the styles and images and only work on gridheaders and data You can choose which part of the selected content to copy out of row header column headerand data by using the ClipboardCopyMode property When a datamap or multicolumn combobox exists in thecopied range only the display value is copied Also note that hidden cells are also copied when copying a cellrange To exclude hidden cells from copying see Exclude Hidden Cells

The code below demonstrates how to enable clipboard operations in the WinForms FlexGrid

Clipboard Operations through CodeYou can also perform clipboard operations through code The example below shows how to perform copying andpasting operations on button click

Use the code below to perform the clipboard operations through code in the WinForms FlexGrid

キーボードからクリップボード操作を有効にします c1FlexGrid1AutoClipboard = true データとすべてのヘッダーをコピーするようにコピーモードを設定します c1FlexGrid1ClipboardCopyMode = C1WinC1FlexGridClipboardCopyModeEnumDataAndAllHeaders

C

キーボードからクリップボード操作を有効にしますc1FlexGrid1AutoClipboard = True

データとすべてのヘッダーをコピーするようにコピーモードを設定しますc1FlexGrid1ClipboardCopyMode = C1WinC1FlexGridClipboardCopyModeEnumDataAndAllHeaders

VBNET

private void CopyButton_Click(object sender EventArgs e) クリップボードにコピーするグリッドのデータのみをコピーできるようにします c1FlexGrid1ClipboardCopyMode = ClipboardCopyModeEnumDataOnly

Clipプロパティに改行コードを追加しクリップボードに設定します ClipboardSetDataObject(c1FlexGrid1Clip + r) MessageBoxShow($Copied Range [c1FlexGrid1Rowc1FlexGrid1Col]-[c1FlexGrid1RowSelc1FlexGrid1ColSel])

C

FlexGrid for WinForms

189 Copyright copy GrapeCity Inc All rights reserved

Exclude Hidden CellsIn FlexGrid by default hidden cells are also copied when copying a cell range through keyboard operations enabledusing the AutoClipboard property However you can exclude the hidden rows and columns by using the code below

Following code shows how you can exclude the hidden cells from clipboard operations performed on the WinFormsTree Grid

private void PasteButton_Click(object sender EventArgs e) クリップボードのテキストを取得します IDataObject data = ClipboardGetDataObject() if (dataGetDataPresent(DataFormatsText)) string str1 str2 クリップボードからデータを取得します str1 = (string)dataGetData(DataFormatsText)

クリップボードから最後の行のフィードコードを削除します str2 = str1Remove(str1Length - 1 1)

範囲を選択してデータを貼り付けます c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col c1FlexGrid1RowsCount - 1 c1FlexGrid1ColsCount - 1 true) c1FlexGrid1Clip = str2 c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col)

Private Sub CopyButton_Click(ByVal sender As Object ByVal e As EventArgs) クリップボードにコピーするグリッドのデータのみをコピーできるようにします c1FlexGrid1ClipboardCopyMode = ClipboardCopyModeEnumDataOnly

Clipプロパティに改行コードを追加しクリップボードに設定します ClipboardSetDataObject(c1FlexGrid1Clip amp MicrosoftVisualBasicConstantsvbCr) MessageBoxShow($Copied Range [c1FlexGrid1Rowc1FlexGrid1Col]-[c1FlexGrid1RowSelc1FlexGrid1ColSel])End Sub

Private Sub PasteButton_Click(ByVal sender As Object ByVal e As EventArgs) クリップボードのテキストを取得します Dim data As IDataObject = ClipboardGetDataObject()

If dataGetDataPresent(DataFormatsText) Then Dim str1 str2 As String クリップボードからデータを取得します str1 = CStr(dataGetData(DataFormatsText))

クリップボードから最後の行のフィードコードを削除します str2 = str1Remove(str1Length - 1 1)

範囲を選択してデータを貼り付けます c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col c1FlexGrid1RowsCount - 1 c1FlexGrid1ColsCount - 1 True) c1FlexGrid1Clip = str2 c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col) End If

VBNET

C

FlexGrid for WinForms

190 Copyright copy GrapeCity Inc All rights reserved

列を非表示にしますc1FlexGrid1Cols[2]Visible = falsec1FlexGrid1AutoClipboard = true

次にCtrl + Cを押す前に非表示の列を含むいくつかのセルを選択しますprivate void c1FlexGrid1_KeyDown_1(object sender KeyEventArgs e) [Ctrl + C]でコピーします if ((eControl == true) ampamp (eKeyCode == KeysC)) 自動処理が行われないためキー入力を無効にします eHandled = true 選択したセル範囲のCellRangeオブジェクトを取得します C1WinC1FlexGridCellRange cr cr = c1FlexGrid1Selection

string StrCopy = for (int i = crr1 i lt= crr2 i++) if (c1FlexGrid1Rows[i]Visible == true) for (int j = crc1 j lt= crc2 j++) if (c1FlexGrid1Cols[j]Visible == true) StrCopy = StrCopy + c1FlexGrid1[i j]ToString() if (j = crc2) StrCopy = StrCopy + t StrCopy = StrCopy + n クリップボードに設定します ClipboardSetDataObject(StrCopy) MessageBoxShow(Copied data n + StrCopy)

列を非表示にします c1FlexGrid1Cols(2)Visible = False c1FlexGrid1AutoClipboard = True

次にCtrl + Cを押す前に非表示の列を含むいくつかのセルを選択しますPrivate Sub c1FlexGrid1_KeyDown_1(ByVal sender As Object ByVal e As KeyEventArgs)

[Ctrl + C]でコピーします If eControl = True AndAlso eKeyCode = KeysC Then 自動処理が行われないためキー入力を無効にします eHandled = True 選択したセル範囲のCellRangeオブジェクトを取得します Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1Selection Dim StrCopy =

VBNET

FlexGrid for WinForms

191 Copyright copy GrapeCity Inc All rights reserved

For i = crr1 To crr2

If c1FlexGrid1Rows(i)Visible = True Then For j = crc1 To crc2

If c1FlexGrid1Cols(j)Visible = True Then StrCopy = StrCopy amp c1FlexGrid1(i j)ToString()

If j ltgt crc2 Then StrCopy = StrCopy amp MicrosoftVisualBasicConstantsvbTab End If End If Next

StrCopy = StrCopy amp MicrosoftVisualBasicConstantsvbLf End If Next クリップボードに設定します ClipboardSetDataObject(StrCopy) MessageBoxShow(Copied data amp MicrosoftVisualBasicConstantsvbLf amp StrCopy) End IfEnd Sub

FlexGrid for WinForms

192 Copyright copy GrapeCity Inc All rights reserved

保存ロードと印刷

FlexGrid provides various built-in options so that you can easily save a grid and its content in a text excel or an XML file You can even load these saved filesto another grid or can save it as backup of a particular state of the grid You can also save the grid image in your desired format Not just this you can alsoprint the grid or selected areas of the grid if you need to have a hard copy This topic discusses various options related save load and print available in thegrid

Topic Content

Save Discusses about how to save the grid and its contents in different formats

Save as Text FileSave as Excel FileSave as XMLSave as Image

Load Discusses about how to load grid content from various file formats

Load from Text FileLoad from Excel FileLoad from DatabaseLoad from XML

Print Discusses about how to print the grid and other print related options

Print GridPrint OptionsCustomize Print Preview Dialog

保存

FlexGrid provides various methods to save the grid in the desired format such as text excel xml and image formatsThis feature is enabled through an assembly named C1WinC1FlexGridImportExportdll hence you need to addreference to this assembly to save the grid

Save as Text FileTo save grid content as a text file you can use the SaveGrid method of the Extensions class The method hasparameters that let you choose delimiter encoding and also lets you specify which portion of grid should be savedThe resulting text files can later be loaded back into the control or into other applications that support comma or tab-delimited files such as Microsoft Excel

Following code shows how to save content of the WinForms FlexGrid as a text file

private void btnSaveTxt_Click(object sender EventArgs e) c1FlexGrid1SaveGrid(ExportedGridtxt FileFormatEnumTextComma FileFlagsAsDisplayed | FileFlagsIncludeFixedCells)

C

Private Sub btnSaveTxt_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1SaveGrid(ExportedGridtxt FileFormatEnumTextComma FileFlagsAsDisplayed Or FileFlagsIncludeFixedCells)End Sub

VBNET

FlexGrid for WinForms

193 Copyright copy GrapeCity Inc All rights reserved

Save as Excel FileTo save grid as an excel file you can use the abovementioned SaveGrid method and simply set the format parameterto FileFormatEnumExcel You dont need to have Microsoft Excel installed on your computer However SaveGridmethod can only save the data in a workbook with single worksheet

To get an additional control over how you save your data to an excel file you can use the SaveExcel method insteadIn this case the process of saving excel files converts most data types and formatting information including row andcolumn dimensions fonts colors formats and cell alignment However some other features such as frozen andmerged cells images data maps and cell borders are not translated while converting to an excel file

Use the code below to save the WinForms FlexGrid as an Excel file

Save as XMLTo serialize grid contents into an XML document you can simply call WriteXML method of the C1FlexGrid class andparse path of the XML document as a parameter The method serializes all grid contents into the Xml documentincluding the data stored in the cells row and column properties styles and images Objects of custom types storedin the grid are also serialized as long as they have an associated SystemComponentModelTypeConverter thatprovides conversions to and from string

Below code demonstrates how to save contents of the WinForms FlexGrid to an XML document

Save as ImageTo save a grid as an image you can create the grid image using CreateImage method of the C1FlexGrid class andsave that image object at the specified path You can also specify a cell range or pass a cell range object as itsparameter to save a specific portion of the grid as an image

Use the code below to save the WinForms FlexGrid as an image

private void btnSaveExcl_Click(object sender EventArgs e) c1FlexGrid1SaveExcel(ExportedGridxlsx FileFlagsAsDisplayed | FileFlagsIncludeFixedCells)

C

Private Sub btnSaveExcl_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1SaveExcel(ExportedGridxlsx FileFlagsAsDisplayed Or FileFlagsIncludeFixedCells)End Sub

VBNET

private void btnSaveXML_Click(object sender EventArgs e) c1FlexGrid1WriteXml(ExportedGridxml)

C

Private Sub btnSaveXML_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1WriteXml(ExportedGridxml)End Sub

VBNET

FlexGrid for WinForms

194 Copyright copy GrapeCity Inc All rights reserved

private void btnSaveImg_Click(object sender EventArgs e) Image gridImage = c1FlexGrid1CreateImage() gridImageSave(ExportedGridpng)

C

Private Sub btnSaveImg_Click(ByVal sender As Object ByVal e As EventArgs) Dim gridImaage As Image = c1FlexGrid1CreateImage() gridImaageSave(ExportedGridpng)End Sub

VBNET

ロード

FlexGrid not only lets you save the grid to various formats but also lets you load data from various formats such textexcel XML or databases This feature is enabled through an assembly named C1WinC1FlexGridImportExportdllhence you need to add reference to this assembly to load the grid with data from these sources

Load from Text FileTo load data from a text file FlexGrid provides LoadGrid method of the Extensions class The method has parametersthat let you choose delimiter encoding etc You can also load text files saved using SaveGrid method When loadingtext files rows and columns are added to the grid if needed to accommodate the file contents The method supportsformats such as comma-delimited text files (CSV format) tab-delimited text files and even MS Excel files (xls)

Following code shows how to populate data in the WinForms FlexGrid by loading it from a text file

Load from Excel FileTo load grid from an excel file you can use the abovementioned LoadGrid method and simply set the formatparameter to FileFormatEnumExcel You dont need to have Microsoft Excel installed on your computer However theLoadGrid method can only load the data from first worksheet of a workbook

To get an additional control over how you load your data from an excel file you can use the LoadExcel methodinstead In this case the process of loading excel files converts most data types and formatting information includingrow and column dimensions fonts colors formats and cell alignment However there are still some exceptions Forexample the grid loads the values in excel cells but cannot load the underlying formulas Other features such asfrozen and merged cells images data maps and cell borders are not translated either

Use the code below to load contents in the WinForms FlexGrid from an excel file

private void btnLoadTxt_Click(object sender EventArgs e) c1FlexGrid1LoadGrid(ExportedGridtxt FileFormatEnumTextComma )

C

Private Sub btnLoadTxt_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1LoadGrid(ExportedGridtxt FileFormatEnumTextComma)End Sub

VBNET

FlexGrid for WinForms

195 Copyright copy GrapeCity Inc All rights reserved

Load from DatabaseTo load grid data from a database you can use the DataReader objects This process is different from data bindingwhich keeps a live connection between one or more controls and the underlying data source

Below code demonstrates how to load contents in the WinForms FlexGrid from the database

private void btnLoadExcl_Click(object sender EventArgs e) c1FlexGrid1LoadExcel(ExportedGridxlsx)

C

Private Sub btnLoadExcl_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1LoadExcel(ExportedGridxlsx)End Sub

VBNET

private void btnLoadDB_Click(object sender EventArgs e) DataReaderを準備します string strConn = data source=MYMACHINEinitial catalog=Northwind SystemDataSqlClientSqlConnection myConn = new SystemDataSqlClientSqlConnection(strConn) SystemDataSqlClientSqlCommand myCMD = new SystemDataSqlClientSqlCommand(SELECT FROM Employees myConn) myConnOpen() SystemDataSqlClientSqlDataReader myReader = myCMDExecuteReader()

DBスキーマからグリッド構造を構築します DataTable dt = myReaderGetSchemaTable() c1FlexGrid1ColsCount = 1 foreach (DataRow dr in dtRows) Column c =c1FlexGrid1ColsAdd() cCaption = cName = (string)dr[ColumnName] cDataType = (Type)dr[DataType]

グリッドにデータを入力します c1FlexGrid1RowsCount = 1 int row = 1 int cols = dtColumnsCount object[] v = (object[])ArrayCreateInstance(typeof(object) cols) while (myReaderRead()) myReaderGetValues(v) c1FlexGrid1AddItem(v row++ 1)

クリーンアップします c1FlexGrid1AutoSizeCols() myReaderClose() myConnClose()

C

FlexGrid for WinForms

196 Copyright copy GrapeCity Inc All rights reserved

Load from XMLTo deserialize grid contents from an XML document you can simply call ReadXML method of the C1FlexGrid classand parse path of the XML document as a parameter

Use the code below to load contents for the WinForms FlexGrid from an XML document

Private Sub btnLoadDB_Click(ByVal sender As Object ByVal e As EventArgs) DataReaderを準備します Dim strConn As String = data source=MYMACHINEinitial catalog=Northwind Dim myConn As New SqlClientSqlConnection(strConn) Dim myCMD As New SqlClientSqlCommand(SELECT FROM Employees myConn) myConnOpen() Dim myReader As SqlClientSqlDataReader = myCMDExecuteReader() DBスキーマからグリッド構造を構築します Dim dt As DataTable = myReaderGetSchemaTable() _flexColsCount = 1 Dim dr As DataRow For Each dr In dtRows Dim c As C1WinC1FlexGridColumn = _flexColsAdd() cCaption =(cName lt= CStr(dr(ColumnName))) cDataType = CType(dr(DataType) Type) Next dr グリッドにデータを入力します _flexRowsCount = 1 Dim row As Integer = 1 Dim cols As Integer = dtColumnsCount Dim v As Object() = CType(ArrayCreateInstance(GetType(Object) cols) Object()) While myReaderRead() myReaderGetValues(v) _flexAddItem(v row + 1 1) End While クリーンアップします _flexAutoSizeCols() myReaderClose() myConnClose()End Sub

VBNET

private void btnLoadXML_Click(object sender EventArgs e) c1FlexGrid1ReadXml(ExportedGridxml)

C

Private Sub btnLoadXML_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1ReadXml(ExportedGridxml)End Sub

VBNET

FlexGrid for WinForms

197 Copyright copy GrapeCity Inc All rights reserved

印刷

FlexGrid lets you print the grid and perform various basic and advanced print settings using its built-in methods andproperties

Print GridFlexGrid provides PrintGrid method of the C1FlexGrid class which lets you print the grid contents with some basicprinting options The method has an optional parameter PrintGridFlags that allows you to specify how to print thegrid such as its scaling mode and whether to display various print related dialog boxes You can also set text in headerand footer of the printed grid using this method

Following code shows how to use PrintGrid method to print the WinForms FlexGrid

Print OptionsTo set advanced printing options such as header and footer fonts page margins and page orientation you can usePrintParameter property of the C1FlexGrid class

Use the code below to print the WinForms FlexGrid with advanced print options

プレビューダイアログを表示し指定したヘッダとフッターでグリッドを印刷しますc1FlexGrid1PrintGrid(C1FlexGrid PrintGridFlagsFitToPageWidth | PrintGridFlagsShowPreviewDialog C1FlexGridtt + StringFormat(DateTimeNowToString() d) ttPage 0 of 1)

C

プレビューダイアログを表示し指定したヘッダとフッターでグリッドを印刷しますc1FlexGrid1PrintGrid(C1FlexGrid PrintGridFlagsFitToPageWidth Or PrintGridFlagsShowPreviewDialog C1FlexGrid amp vbTab amp vbTab amp StringFormat(DateNowToString() d) vbTab amp vbTab amp Page 0 of 1)

VBNET

FlexGrid for WinForms

198 Copyright copy GrapeCity Inc All rights reserved

Customize Print Preview DialogYou can customize the print preview dialog by using PrintPreviewDialog property of the GridPrinter class Theproperty can be accessed through PrintParameter property of the C1FlexGrid class The code below uses thePrintPreviewDialog property to display a maximized preview dialog with a custom caption

Below code demonstrates how to customize the print preview dialog of the WinForms FlexGrid

グリッドのPrintDocumentオブジェクトを取得しますSystemDrawingPrintingPrintDocument pd = c1FlexGrid1PrintParametersPrintDocument

ページを設定します(横向き15 左マージン)pdDefaultPageSettingsLandscape = truepdDefaultPageSettingsMarginsLeft = 150

ヘッダとフッタのフォントを設定しますc1FlexGrid1PrintParametersHeaderFont = new Font(Arial Black 14 FontStyleBold)c1FlexGrid1PrintParametersFooterFont = new Font(Arial Narrow 8 FontStyleItalic)

C

グリッドのPrintDocumentオブジェクトを取得しますDim pd As DrawingPrintingPrintDocument = c1FlexGrid1PrintParametersPrintDocument

ページを設定します(横向き15 左マージン)pdDefaultPageSettingsLandscape = TruepdDefaultPageSettingsMarginsLeft = 150

ヘッダとフッタのフォントを設定しますc1FlexGrid1PrintParametersHeaderFont = New Font(Arial Black 14 FontStyleBold)c1FlexGrid1PrintParametersFooterFont = New Font(Arial Narrow 8 FontStyleItalic)

VBNET

Form dlg = c1FlexGrid1PrintParametersPrintPreviewDialog as Form dlgText = Order Details dlgStartPosition = FormStartPositionCenterParent dlgWindowState = FormWindowStateMaximized c1FlexGrid1PrintGrid(Orders PrintGridFlagsShowPreviewDialog)

C

Dim dlg As Form = TryCast(c1FlexGrid1PrintParametersPrintPreviewDialog Form) dlgText = Order Details dlgStartPosition = FormStartPositionCenterParent dlgWindowState = FormWindowStateMaximized c1FlexGrid1PrintGrid(Orders PrintGridFlagsShowPreviewDialog)

VBNET

FlexGrid for WinForms

199 Copyright copy GrapeCity Inc All rights reserved

外観とスタイル設定

FlexGrid provides built-in visual styles as well as various design time and run time options so that you can style the grid and its elements as per the needsand appearance of your application The grid also provides style editors to let you customize appearance of your grid without writing a single line of codeFor more information about these editors and design time styling see Editors

This section discusses the built-in options provided by FlexGrid as well as various other ways to customize the appearance of grid and its elements

Topic Snapshot Content

Built-in Options Discusses about the available visual styles and built-in collection of styles

Visual StylesStyles Collection

Custom Styles Discusses how to create and apply the custom styles

Approach 1 Style an ObjectApproach 2 Create Re-usable Style

Customize Grid Discusses about customization at grid level

Set Alternate RowSet Background Image

Customize Border Discusses about customization of cell borders at row column or grid level

Customize Grid BorderCustomize RowColumn BorderCustomize Cell Border

Customize Text Discusses about various aspects of styling the grid text

Change FontSet MarginSet Vertical TextWrap TextDisplay Trimmed TextAlign TextApply Text Effect

Custom Glyphs Discusses about applying custom glyphs in the grid

組み込みオプション

Visual StylesFlexGrid provides six built-in visual styles so that you can easily customize the appearance of FlexGrid based on any ofthe Microsoft Office 2007 and 2010 themes These visual styles can be accessed through VisualStyle property ofthe C1FlexGrid class Apart from MS Office based visual styles you can also set this property to Custom and SystemWhen set to Custom the grid does not apply any visual styles and uses the grid properties for rendering When theproperty is set to System the grid renders its appearance based on current system settings

FlexGrid for WinForms

200 Copyright copy GrapeCity Inc All rights reserved

The property can be set using designer as well as through code To set the property at design time click smart tag toopen the C1FlexGrid Tasks menu and select a visual style from the VisualStyle combobox To apply visual style in theWinForms FlexGrid through code use the code below

Styles CollectionFlexGrid provides built-in collection of styles for predefined cell types and states such as normal cells fixed cellsfocused cells and so on You can use these built-in styles at design time as well as through code In design view youcan access these styles through the C1FlexGrid Style Editor which can be opened by clicking Styles option in Tasksmenu This collection of styles is represented by the CellStyleCollection class which can be accessed through Stylesproperty of the C1FlexGrid class Each built-in style is an object of the CellStyle class and holds various propertiessuch as BackColor DataType and Format

Following code shows how to use the styles from Styles collection of the WinForms FlexGrid

視覚スタイルをOffice2010Blueスキームに設定しますc1FlexGrid1VisualStyle = VisualStyleOffice2010Blue

C

視覚スタイルをOffice2010Blueスキームに設定しますc1FlexGrid1VisualStyle = VisualStyleOffice2010Blue

VBNET

組み込みセルスタイルNormalのプロパティを設定しますc1FlexGrid1Styles[Normal]BackColor = ColorAzurec1FlexGrid1Styles[Normal]ForeColor = ColorBlueViolet

固定セルの背景色を設定しますc1FlexGrid1Styles[Fixed]BackColor = ColorAqua

C

FlexGrid for WinForms

201 Copyright copy GrapeCity Inc All rights reserved

You can also add your own custom styles to Styles collection by using the Add method For more information abouthow to create and apply custom styles to grid cells see Custom Styles

組み込みセルスタイルNormalのプロパティを設定しますc1FlexGrid1Styles(Normal)BackColor = ColorAzurec1FlexGrid1Styles(Normal)ForeColor = ColorBlueViolet

固定セルの背景色を設定しますc1FlexGrid1Styles(Fixed)BackColor = ColorAqua

VBNET

カスタムのスタイル

Approach 1 Style an ObjectTo style a specific row column or a cell range of the WinForms FlexGrid you can use StyleNew property of the rowcolumn or cell range object

This approach is useful for styling a particular object when style is not expected to be reused To reuse a particularstyle you must create a style using the CellStyle object as discussed in the section below

Approach 2 Create Re-usable StyleIn this approach you can create a custom style as an object of CellStyle class and add it to the Styles collection usingthe Add method Then define its properties and apply it to a row column or cell range whenever required Asmentioned above this approach is very useful when you need to repeatedly use a particular style

Use the code below to create re-usable custom styles for your WinForms FlexGrid

特定の行にカスタムスタイルを適用しますc1FlexGrid1Rows[1]StyleNewBackColor = ColorAzurec1FlexGrid1Rows[1]StyleNewForeColor = ColorBlueViolet

C

特定の行にカスタムスタイルを適用しますc1FlexGrid1Rows(1)StyleNewBackColor = ColorAzurec1FlexGrid1Rows(1)StyleNewForeColor = ColorBlueViolet

VBNET

新しいスタイルを作成しスタイルコレクションに追加しますCellStyle cs = thisc1FlexGrid1StylesAdd(Custom) 新しいカスタムスタイルのプロパティを定義しますcsBackColor = ColorAzurecsForeColor = ColorBlueViolet

行にカスタムスタイルを適用しますc1FlexGrid1Rows[1]Style = cs

C

VBNET

FlexGrid for WinForms

202 Copyright copy GrapeCity Inc All rights reserved

新しいスタイルを作成しスタイルコレクションに追加しますDim cs As CellStyle = Mec1FlexGrid1StylesAdd(Custom)

新しいカスタムスタイルのプロパティを定義しますcsBackColor = ColorAzurecsForeColor = ColorBlueViolet

行にカスタムスタイルを適用しますc1FlexGrid1Rows(1)Style = cs

グリッドのカスタマイズ

FlexGrid also lets you customize overall look of the grid not to just increase its aesthetic value but also increases itsreadability You can add the alternate rows which make the grid more readable Also you can set image for instance awatermark or a company logo in background of the grid

Set Alternate RowTo set the alternate row color and styles in the grid you can use the built-in style Alternate either at design time orat runtime To apply style at design time you need to access the FlexGrid Style Editor and set properties for Alternatestyle

To apply alternate row style in the WinForms FlexGrid through code you need to use the CellStyle item Alternate ofthe CellStyleCollection class and set various properties for setting the alternate style

代替行の前色を設定します c1FlexGrid1Styles[Alternate]ForeColor = ColorWhite

代替行の背景色を設定します c1FlexGrid1Styles[Alternate]BackColor = ColorCadetBlue

C

FlexGrid for WinForms

203 Copyright copy GrapeCity Inc All rights reserved

Set Background Image in GridTo set the background image on a grid you can use the BackgroundImage property and assign the path of the imagefile to it Another property called BackgroundImageLayout property lets you choose whether and how to renderimage on the grid

Use the code below to set the background image on the WinForms FlexGrid

代替行の前色を設定しますc1FlexGrid1Styles(Alternate)ForeColor = ColorWhite

代替行の背景色を設定しますc1FlexGrid1Styles(Alternate)BackColor = ColorCadetBlue

VBNET

背景画像をグリッドに設定しますc1FlexGrid1BackgroundImage = ImageFromFile(CIMG-20190524-WA0037png)c1FlexGrid1BackgroundImageLayout = ImageLayoutStretch

C

背景画像をグリッドに設定しますc1FlexGrid1BackgroundImage = ImageFromFile(CIMG-20190524-WA0037png)c1FlexGrid1BackgroundImageLayout = ImageLayoutStretch

VBNET

境界線のカスタマイズ

The FlexGrid control lets you customize the border of grid row column and even cells by changing its style colordirection and so on

FlexGrid for WinForms

204 Copyright copy GrapeCity Inc All rights reserved

Customize Grid BorderTo customize border of the grid control you can use the BorderStyle property which accepts valuesfrom BorderStyleEnum provided by the C1WinFlexGridUtilBaseControls namespace

Following code shows how to customize border of the WinForms FlexGrid control

Customize RowColumn BorderTo customize the border style of a particular row or column you must access the Border item of CellStyle classusing StyleNew property and set its properties such as border style direction and color The grid controlprovides BorderStyleEnum as well as BorderDirEnum to set the border style and direction respectively

Use the below code to change border of rows or columns of the WinForms FlexGrid

Customize Cell BorderTo customize border of every cell in the grid you can access the built-in style Normal and set its border propertiesSimilarly you can change the style of specific types of cells such fixed or frozen by accessing their correspondingstyles from Styles collection

Below code lets you customize the border of normal cells of the WinForms FlexGrid

グリッドの境界線を3次元の境界線に変更しますc1FlexGrid1BorderStyle = C1WinC1FlexGridUtilBaseControlsBorderStyleEnumFixed3D

C

グリッドの境界線を3次元の境界線に変更しますc1FlexGrid1BorderStyle = C1WinC1FlexGridUtilBaseControlsBorderStyleEnumFixed3D

VBNET

最初の列の境界線スタイルを設定しますc1FlexGrid1Cols[1]StyleNewBorderStyle = BorderStyleEnumGroovec1FlexGrid1Cols[1]StyleNewBorderColor = ColorRedc1FlexGrid1Cols[1]StyleNewBorderDirection = BorderDirEnumVertical

最初の行の境界線スタイルを設定しますc1FlexGrid1Rows[1]StyleNewBorderStyle = BorderStyleEnumRaisedc1FlexGrid1Rows[1]StyleNewBorderColor = ColorBlue

C

最初の列の境界線スタイルを設定しますc1FlexGrid1Cols(1)StyleNewBorderStyle = BorderStyleEnumGroovec1FlexGrid1Cols(1)StyleNewBorderColor = ColorRedc1FlexGrid1Cols(1)StyleNewBorderDirection = BorderDirEnumVertical

最初の行の境界線スタイルを設定しますc1FlexGrid1Rows(1)StyleNewBorderStyle = BorderStyleEnumRaisedc1FlexGrid1Rows(1)StyleNewBorderColor = ColorBlue

VBNET

FlexGrid for WinForms

205 Copyright copy GrapeCity Inc All rights reserved

すべてのグリッドセルの境界線スタイルを設定しますc1FlexGrid1StylesNormalBorderStyle = BorderStyleEnumDouble

C

すべてのグリッドセルの境界線スタイルを設定しますc1FlexGrid1StylesNormalBorderStyle = BorderStyleEnumDouble

VBNET

テキストのカスタマイズ

FlexGrid lets you customize text in various ways such as changing its font margin orientation alignment effects and soon This topic caters to various aspects of text styling by taking a particular row object However if you wish to use anexisting built-in style or want to create your own custom style to re-use it see the corresponding topics

Change FontTo change font of text in a particular row or column object you can use Font property of its CellStyle Following codeshows how to change font of the WinForms FlexGrid row

カスタムスタイルを特定の行に適用しますc1FlexGrid1Rows[1]StyleNewFont = new Font(verdana 10 FontStyleUnderline)c1FlexGrid1Rows[0]StyleNewFont = new Font(verdana 10 FontStyleBold)

C

カスタムスタイルを特定の行に適用しますc1FlexGrid1Rows(1)StyleNewFont = new Font(verdana 10 FontStyleUnderline)c1FlexGrid1Rows(0)StyleNewFont = new Font(verdana 10 FontStyleBold)

VBNET

FlexGrid for WinForms

206 Copyright copy GrapeCity Inc All rights reserved

However if you want to change font of the whole grid you can set Font property of the C1FlexGrid class Followingcode shows how to change font of the entire WinForms FlexGrid

Set MarginTo set margin on text of a particular row or column you can set Margins property of the CellStyle Use the code belowto change margins in WinForms FlexGrid row

Set Vertical TextTo change the orientation and display a text as vertical text you can set TextDirection property of CellStyle of theobject Also to display the vertical text properly you may have to adjust height of the target cells depending upon thetext length Below code lets you set vertical text in the WinForms FlexGrid row

Wrap TextTo wrap a text which is longer than the available cell width you can set the WordWrap property of its CellStyle to trueFollowing code demonstrates how to apply text wrap in the WinForms FlexGrid row

グリッドの内容全体のフォントを変更しますc1FlexGrid1Font = new Font(verdana 10 FontStyleItalic)

C

グリッドの内容全体のフォントを変更しますc1FlexGrid1Font = New Font(verdana 10 FontStyleItalic)

VBNET

右側のマージンを設定しますc1FlexGrid1Rows[1]StyleNewMarginsRight = 10

C

右側のマージンを設定しますc1FlexGrid1Rows(1)StyleNewMarginsRight = 10

VBNET

行の内容のテキスト方向を設定しますc1FlexGrid1Rows[1]StyleNewTextDirection = TextDirectionEnumDown 行の高さを設定して垂直方向のテキストを表示しますc1FlexGrid1Rows[1]Height = 60

C

行の内容のテキスト方向を設定しますc1FlexGrid1Rows(1)StyleNewTextDirection = TextDirectionEnumDown

行の高さを設定して垂直方向のテキストを表示しますc1FlexGrid1Rows(1)Height = 60

VBNET

C

FlexGrid for WinForms

207 Copyright copy GrapeCity Inc All rights reserved

Display Trimmed TextTo display trimmed text when text is longer than the cell width set Trimming property of the style which takes its valuesfrom StringTrimming enumeration Use the code below to trim the long text to display ellipsis character in theWinForms FlexGrid row

Align TextYou can set the text alignment or position of the text with respect to cell by using the TextAlign property The propertyaccepts values from the TextAlignEnum enumeration

Use the code below to apply text alignment on the WinForms FlexGrid row

Apply Text EffectTo set various effects on the text you can use the TextEffect property which accepts its values from TextEffectEnumenumeration

Apply text on the WinForms FlexGrid row using the following code

セルの幅に応じて特定の行のテキストを折り返しますc1FlexGrid1Rows[1]StyleNewWordWrap = true

セルの幅に応じて特定の行のテキストを折り返しますc1FlexGrid1Rows(1)StyleNewWordWrap = True

VBNET

長いテキストをトリミングして最後に省略記号を表示しますc1FlexGrid1Rows[1]StyleNewTrimming = StringTrimmingEllipsisCharacter

C

長いテキストをトリミングして最後に省略記号を表示しますc1FlexGrid1Rows(1)StyleNewTrimming = StringTrimmingEllipsisCharacter

VBNET

テキストの配置を設定しますc1FlexGrid1Rows[1]StyleNewTextAlign = TextAlignEnumLeftCenter

C

テキストの配置を設定しますc1FlexGrid1Rows(1)StyleNewTextAlign = TextAlignEnumLeftCenter

VBNET

上げ表示するテキストを設定しますc1FlexGrid1Rows[1]StyleNewTextEffect = TextEffectEnumRaised

C

上げ表示するテキストを設定します c1FlexGrid1Rows(1)StyleNewTextAlign = TextAlignEnumLeftCenter

VBNET

FlexGrid for WinForms

208 Copyright copy GrapeCity Inc All rights reserved

カスタムのグリフ

FlexGrid lets you change the default glyph images used in the grid to indicate various actions such as column filteringand sorting This behavior of grid is exposed through GridGlyphs class which is a collection of images used by the gridto represent filtered state sorting order checkbox states and so on These images can be accessed through Glyphsproperty of the C1FlexGrid class which accepts values from GlyphEnum enumeration

Change the default glyphs used for filter editor and filtered column in the WinForms FlexGrid to a custom image usingthe code below

Note that setting this property to null restores the default glyph In order to hide a glyph you can set the Glyphproperty to a blank image

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilterEditor] = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilteredColumn] = ImageFromFile(filterico)

C

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilterEditor) = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilteredColumn) = ImageFromFile(filterico)

VBNET

FlexGrid for WinForms

209 Copyright copy GrapeCity Inc All rights reserved

永続的な状態

Grid persistence refers to saving the current state of the grid for later use and then restoring it back when needed Forinstance the user may apply grouping sorting filtering or some styling to the grid which he wants to use after fewmore operations or on opening the application again This behavior can be achieved by persisting the grids state

There are two steps to implement persistence of the grid state First we have to serialize the grid state and then werestore it In this topic we discuss how to persist the filtered sorted and grouped state of the FlexGrid control

You can implement persisting grid states by using XMLWriter and XMLReader class of the SystemXML namespace Tosave the grid state you can use the WriteStartElement method to write the specified start tag andWriteAttributeString method to write the filter sort and group attributes Finally call WriteEndElement method toclose the WriteStartElement method and save the state in the form of stream string or a file

Use the code below to serialize the state of WinForms FlexGrid to an XML file for later use

フィルタグループ並べ替えの定義をファイルに書き込みますprivate void WriteStateToXML(string filePath) using (XmlWriter writer = XmlWriterCreate(filePath)) writerWriteStartElement(FlexGrid) writerWriteStartElement(Definition ) writerWriteAttributeString(Filter flexGridFilterDefinition) writerWriteAttributeString(Sort flexGridSortDefinition) writerWriteAttributeString(Group flexGridGroupDefinition) writerWriteEndElement() writerWriteEndElement() writerFlush()

C

フィルタグループ並べ替えの定義をファイルに書き込みますPrivate Sub WriteStateToXML(ByVal filePath As String)

VBNET

FlexGrid for WinForms

210 Copyright copy GrapeCity Inc All rights reserved

To load the saved state back into the grid you can use the GetAttribute method of the object to read the filter sortand group attributes Then assign them to the FilterDefinition SortDefinition or GroupDefinition properties of theFlexGrid respectively

Use the code below to load saved state of the WinForms FlexGrid

Using writer = XmlWriterCreate(filePath) writerWriteStartElement(FlexGrid) writerWriteStartElement(Definition ) writerWriteAttributeString(Filter flexGridFilterDefinition) writerWriteAttributeString(Sort flexGridSortDefinition) writerWriteAttributeString(Group flexGridGroupDefinition) writerWriteEndElement() writerWriteEndElement() writerFlush() End UsingEnd Sub

保存したファイルからフィルタ並べ替えグループの定義を読み取りFlexGridに適用しますprivate void ReadStateXML(string filePath)

using (XmlReader reader = XmlReaderCreate(filePath)) readerReadToFollowing(Definition) flexGridSortDefinition = readerGetAttribute(Sort) flexGridFilterDefinition = readerGetAttribute(Filter) flexGridGroupDefinition = readerGetAttribute(Group) readerClose()

C

保存したファイルからフィルタ並べ替えグループの定義を読み取りFlexGridに適用しますPrivate Sub ReadStateXML(ByVal filePath As String) Using reader = XmlReaderCreate(filePath) readerReadToFollowing(Definition) flexGridSortDefinition = readerGetAttribute(Sort) flexGridFilterDefinition = readerGetAttribute(Filter) flexGridGroupDefinition = readerGetAttribute(Group) readerClose() End Using

VBNET

FlexGrid for WinForms

211 Copyright copy GrapeCity Inc All rights reserved

NET 5 リファレンス

FlexGrid for WinForms

212 Copyright copy GrapeCity Inc All rights reserved

NET 452 リファレンス

FlexGrid for WinForms

213 Copyright copy GrapeCity Inc All rights reserved

  • 目次
  • FlexGrid for WinForms
  • 主な特長
  • 機能比較
    • FlexGrid の比較
    • WinFormsグリッドの比較
      • クイックスタート
      • 設計時サポート
        • タスクメニュー
        • エディタ
          • データ
            • 非連結モード
            • 連結モード
              • 連結モードでの操作
                    • 基本操作
                    • ユーザー操作
                    • エディタ
                      • チェックボックス
                      • 数値
                      • 日付
                      • コンボボックス
                      • マスク
                      • マップリスト
                      • セルボタン
                        • 検証
                        • データ注釈
                        • スパークライン
                        • ヘッダとフッタ
                        • サイズ変更
                            • 基本操作
                            • ユーザー操作
                            • ヘッダ
                            • 行の詳細
                            • サイズ変更
                              • セル
                                • 基本操作
                                • セルの書式設定
                                  • グリッド
                                    • 基本操作
                                    • キーボードによる移動
                                    • パフォーマンスの向上
                                      • スクロールバー
                                      • 選択
                                      • 編集
                                        • 編集モード
                                        • 編集の無効化
                                          • 並べ替え
                                            • 並べ替えの操作
                                            • 並べ替えのインジケータ
                                              • フィルタ
                                                • フィルタの操作
                                                  • フィルタの種類
                                                    • フィルタUI
                                                      • 検索
                                                      • マージ
                                                        • 自動マージ
                                                        • はみ出して表示されるセルの処理
                                                        • カスタムのマージ
                                                          • グループ
                                                          • 集計
                                                          • ツリーグリッド
                                                            • ノードの操作
                                                            • データの操作
                                                            • ツリーグリッドのカスタマイズ
                                                              • クリップボード
                                                              • 保存ロードと印刷
                                                                • 保存
                                                                • ロード
                                                                • 印刷
                                                                  • 外観とスタイル設定
                                                                    • 組み込みオプション
                                                                    • カスタムのスタイル
                                                                    • グリッドのカスタマイズ
                                                                    • 境界線のカスタマイズ
                                                                    • テキストのカスタマイズ
                                                                    • カスタムのグリフ
                                                                      • 永続的な状態
                                                                      • NET 5 リファレンス
                                                                      • NET 452 リファレンス
Page 2: FlexGrid for WinForms

目次

FlexGrid for WinForms 4

主な特長 5-6

機能比較 7

FlexGrid の比較 7-9

WinFormsグリッドの比較 9-12

クイックスタート 13-19

設計時サポート 20

タスクメニュー 20-23

エディタ 23-26

データ 27

非連結モード 27

連結モード 27-30

連結モードでの操作 30-35

列 36

基本操作 36-39

ユーザー操作 40-45

エディタ 45-48

チェックボックス 48-50

数値 50-52

日付 52-56

コンボボックス 56-62

マスク 62-63

マップリスト 63-65

セルボタン 65-67

検証 67-70

データ注釈 70-72

スパークライン 72-73

ヘッダとフッタ 73-76

サイズ変更 76-78

行 79

基本操作 79-83

FlexGrid for WinForms

1 Copyright copy GrapeCity Inc All rights reserved

ユーザー操作 83-85

ヘッダ 85-88

行の詳細 88-93

サイズ変更 93-95

セル 96

基本操作 96-99

セルの書式設定 100-104

グリッド 105

基本操作 105-107

キーボードによる移動 107-109

パフォーマンスの向上 109-114

スクロールバー 115-116

選択 117-119

編集 120

編集モード 120-121

編集の無効化 121-122

並べ替え 123

並べ替えの操作 123-127

並べ替えのインジケータ 127

フィルタ 128

フィルタの操作 128-132

フィルタの種類 132-139

フィルタUI 139-141

検索 142-143

マージ 144

自動マージ 144-147

はみ出して表示されるセルの処理 147-149

カスタムのマージ 149-151

グループ 152-155

集計 156-159

ツリーグリッド 160-172

ノードの操作 172-179

データの操作 179-181

FlexGrid for WinForms

2 Copyright copy GrapeCity Inc All rights reserved

ツリーグリッドのカスタマイズ 181-188

クリップボード 189-192

保存ロードと印刷 193

保存 193-195

ロード 195-197

印刷 197-199

外観とスタイル設定 200

組み込みオプション 200-202

カスタムのスタイル 202-203

グリッドのカスタマイズ 203-204

境界線のカスタマイズ 204-206

テキストのカスタマイズ 206-208

カスタムのグリフ 209

永続的な状態 210-211

NET 5 リファレンス 212

NET 452 リファレンス 213

FlexGrid for WinForms

3 Copyright copy GrapeCity Inc All rights reserved

FlexGrid for WinForms

FlexGrid for WinForms is one of the fastest datagrids available in the market that renders and displays large data sets quicker than any other NET datagrid It is a powerfulgrid packed with basic as well as advanced features like in-cell editing sorting filtering merging grouping and much more Moreover it displays the hierarchical dataefficiently using tree grids with multiple columns aggregates subtotals and row details Not just this the control offers robust API and extensive design-time support sothat you can give your end-users a familiar Excel-like experience

The FlexGrid control binds with any of the NET data sources such as ADONET data source objects and custom business objects It also lets you work in the unbound modegiving you the power to manually add each row or column and set the cell values

One of the main strengths of FlexGrid is the ability to customize almost every aspect of appearance of the entire grid and individual cells In addition to standard formatstrings and cell styling FlexGrid goes above and beyond most NET datagrid components by providing complete control over the cell drawing using its OwnerDrawCell event

Besides the main C1FlexGrid control FlexGrid for WinForms also contains a C1FlexGridClassic control derived from C1FlexGrid It provides an object model that is virtuallyidentical to the VSFlexGrid ActiveX control and is mainly targeted for customers who want to migrate their existing VSFlexGrid projects from ActiveX to the latest technology

Not just this if you are developing your own custom grid control you can use C1FlexGridClassic as a reference The C1FlexGridClassic control is a perfect example of customgrid control created with C1FlexGrid control as base class We ship its source code as a product sample named Classic

Release Notes Product Samples

See the version-wise updates for all controls here Product samples are located at DocumentsComponentOne SamplesWinFormsvxxxC1FlexGridCS onyour system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

Documentation Blogs

Create your First Application with FlexGrid

FlexGrid at Design-time

Work with Columns and Editors

Filter Grid Data

Enable Merging in FlexGrid

Create Groups

Create a Tree Grid

Financial Data Displays using FlexGrid

FlexGrid Performance Compare WinForms WPF UWP

Creating Custom Styles for FlexGrid

Add Dynamic Grouping to your WinForms Data Grid

Implement responsive columns in a WinForms data grid

Creating a Derived Accordion Control with FlexGrid

Show RadioButton in a ComponentOne FlexGrid Tree

Videos Demo Samples

Meet FlexGrid WinForms and WPF Grid Demo

Note ComponentOne FlexGrid for WinForms is compatible with both NET 452 and NET 5

API Reference

C1WinFlexGrid452 Assembly C1WinFlexGrid5 Assembly

FlexGrid for WinForms

4 Copyright copy GrapeCity Inc All rights reserved

主な特長

Code-free Development

Why write code when a click is enough With rich design-time options beginning from binding to styling whichare accessible through the tasks menu and various editors FlexGrid lets you do a lot even without writing a single lineof code

Advanced Cell Editing

Choose from a variety of built-in editors or just create one for yourself FlexGrid offers various built-in cell editors sothat you can choose from simple text editing drop-down lists combo lists cell buttons masks and so on Not justthis with an option to create your own custom cell editors you can change your cells to accept or display almostany type of data

Work in Bound Mode or Unbound Mode

Bound grid or unbound populate the data seamlessly FlexGrid lets you bind the grid with any of the NET datasources such as ADONET and DataObjects for NET You can also work in unbound mode and let FlexGrid manage thedata itself

Present Hierarchical Data

View data the way that is best for you and your users When FlexGrid is bound to a hierarchical data source eachmaster record can be expanded or collapsed to show or hide the details in child grids which may contain moredetails The result is a data tree similar to the type of grid presented by Microsoft Access when displayinghierarchical data When bound the control detects subordinate data sources and creates additional instances of itselfto display child tables

Summarize Data and Show Aggregates

Get a quick outline of your grid data by summarizing it FlexGrid allows you to summarize data by adding a subtotalrow and display aggregates such as sum average count and so on for the specified column

Make it a Tree

Easily display your hierarchical data by converting your grid into a tree FlexGrid lets you represent your bound orunbound hierarchical data in Tree Grid which is similar to a TreeView control and gives a clean yet accessible structureto the data

Built-in Data Filtering

Let your users filter the data by value by condition or just give them both the options to choose from FlexGridprovides advanced built-in filtering with column filter value filter and condition filter already in place Still does notwork for you Create your own custom filter using rich FlexGrid API

Grouping

Group programmatically or at run-time With FlexGrid both are possible FlexGrid lets you group either through codeand even give your users an option to group at run-time using the FlexGridGroupPanel control or through contextmenu

Instant Search

Search the entire grid in one go and locate entries among millions of records instantly FlexGridprovides FlexGridSearchPanel control which lets the user type in the search box filters the records that match thetyped text and also highlights the search results

Merge Cells

Give your grid a tidy look by merging the cells with the same values FlexGrid lets you merge the contiguous cells withthe same values the way you want With free and restricted auto-merge options the grid can intelligently decidewhich cells to merge

Save and Load Multiple Formats

Back up the grid data or load it back in a jiffy FlexGrid lets you save the grid in your favorite format be it a text fileexcel file or XML You can even load content from these formats Not just this you can also load grid data from a

FlexGrid for WinForms

5 Copyright copy GrapeCity Inc All rights reserved

database using DataReader objects

Show Sparklines

Perk up your grid with the tiny charts FlexGrid allows you to add sparklines to grid columns so that you can easilydisplay trends and fluctuations in a single cell and make your grid data more useful and attractive at the same time

Perform Clipboard Operations

Move your text easily with Ctrl+C and Ctrl+V FlexGrid lets you perform clipboard operations on the grid data andheaders using your favorite keys

Assign Field Names to Columns

No need to remember the index of columns just call them by name FlexGrid automatically assigns column keysto field names when the grid is data-bound or you may assign them through code You can refer to a column using aColIndex(ColKey) syntax later which will retrieve the column you want even if your user has moved it to a differentposition on the grid

Use Data Annotations

Hint the user with data annotations FlexGrid lets you add data annotations in the form of metadata tags to theclasses and other objects to display messages and tips for the users

UI Automation and Support

Enable accessible and rich client applications through UI Automation (UIA) FlexGrid control supports UI Automationusing frameworks such as TestStackWhite You can enable applications such as screen readers coded UI testing toexamine user-interface elements and even simulated user interaction through code

Note UI Automation works only for the 452 version of C1FlexGrid and NET framework 47 or above applicationtarget frameworks

Add Special Drawing Effects

Make your grid look different and attractive with special drawing effects FlexGrid lets you paint special drawingeffects such as lines bitmaps and icons in the grid cells Additionally you can even scale images and addtransparency to them

Display Images in Cells

Need to display images in columns not an issue at all With FlexGrid you can display images along with data You caneven bind grid columns to image lists an easy and efficient way to display graphical information from data sources

Integrated Printing

Print the grid with a single statement FlexGrid gives you control over paper orientation margins header and footertext as well as the dialog boxes to set up the printer or see a preview You can even implement advanced printingoptions such as adding page breaks or custom elements to each page by using printing events

Styling

Use the visual styles or create your own custom styling use the designer or write your own code FlexGrid gives youenormous options to customize the appearance of the grid to match your requirements You can customize everyelement of the FlexGrid starting from headers and icons to borders and subtotal rows

FlexGrid for WinForms

6 Copyright copy GrapeCity Inc All rights reserved

機能比較

This section compares the features of various FlexGrids available across different platforms as well as shows acomparison with MS DataGridView

Topic Content

ComparingFlexGrids

Lists the difference between ActiveX version(VSFlexGrid control) and NET version of the FlexGridcontrol making it easy to migrate your grid from AciveX to NET

VSFlexGrid (ActiveX) and C1FlexGrid (NET)

ComparingWinForms Grids

Shows comparison between features of grids available in ComponentOne WinForms Edition andMS DataGridView

FlexGrid or True DBGridComparing ComponentOne Grids with MS DataGridView

FlexGrid の比較

VSFlexGrid (ActiveX) and C1FlexGrid (NET)ComponentOne provides ActiveX as well as NET version of the FlexGrid control While the ActiveX version is known asVSFlexGrid the NET version is shipped in the name of C1FlexGrid Being a NET version C1FlexGrid came laterinto the picture and instead of porting from the already existing VSFlexGrid we decided to create a brand new gridcontrol written from the ground up in C with the same design principles but with a new object model that is moremodern clean and powerful than the one in the ActiveX control

This section caters to original users of the VSFlexGrid control who want to migrate their applications from ActiveX tothe NET version that is the C1FlexGrid control To facilitate the hassle-free migration and a smooth learning curvethe NET version provides the C1FlexGridClassic control that derives from the C1FlexGrid class and provides an objectmodel that is virtually identical to the VSFlexGrid control The C1FlexGridClassic control is available in the form of aproduct sample Classic so that you may know exactly how to use the new object model This sample can also beused as a reference for creating the custom grid controls based on the C1FlexGrid class

Note The Classic sample is located at DocumentsComponentOne SamplesWinFormsv452C1FlexGridCS onyour system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

For users creating new applications we recommend using the new C1FlexGrid control However for the users who areporting their existing applications from ActiveX to NET we recommend using the C1FlexGridClassic control tominimize the programming effort Following table highlights some of the key differences between VSFlexGrid andC1FlexGrid

VSFlexGrid (ActiveX) C1FlexGrid (NET)

RowsCols1 Rows and Cols properties are used to

get or set the number of rows andcolumns

2 VSFlexGrid uses the TextMatrixproperty to represent the rows andcolumns

1 In C1FlexGrid Rows and Cols propertiesreturn the rows and column collectionsThe collections have readwriteproperties that return the number ofelements and fixed elements in eachcollection

FlexGrid for WinForms

7 Copyright copy GrapeCity Inc All rights reserved

For instance in ActiveX you would write

Dim r c c = 1

For r = c1FlexGrid1FixedRows To

c1FlexGrid1Rows - 1

DebugPrint

c1FlexGrid1TextMatrix(rc)

Next

2 C1FlexGrid uses indexers to representrows and columns

For instance in NET you would write

Dim r c c = 1

For r = c1FlexGrid1RowsFixed To

c1FlexGrid1RowsCount - 1

DebugPrint(c1FlexGrid1(r c))

Next

CellCell range The Cell property is one of the mostpowerful elements of the VSFlexGrid objectmodel It allows you to get or set anyproperty of any cell or cell range with asingle command Using a single propertymeans using variants and this prevents thecompiler from catching many subtleproblems in case you make mistakes whilecoding

For instance in ActiveX you would write

flexCell(flexcpPicture 5 5

10 10)

= theImage

In C1FlexGrid CellRange object has replacedthe Cell property to expose type-safeproperties and methods for accessing cellrange So if variable theImage contained astring instead of an image you get a compilererror and not a runtime error Also you getcommand-completion when writing the codebecause the types for each property are known

For instance in NET you would write

Dim rg As CellRange

rg =

c1FlexGrid1GetCellRange(551010)

rgImage = theImage

Typed Columns In the ActiveX version the ColDataTypeproperty allows you to set the type of datathat each column contains This informationis used mainly for sorting columns thatcontain dates or numbers

In the NET version Cols[i]DataType propertydetermines the type of data the column holdsBy default the DataType property for allcolumns is set to object that is you can storeany type of data in any column You can set thedata type to specific types however the gridtries to coerce any data stored in the grid tothe proper type

For instance in NET you would write

c1FlexGrid1Cols(2)DataType =

GetType(Integer)

Sets the value to 12

c1FlexGrid1(1 2) = 12

Can not convert hello string to

integer

Fires the GridError event

Retains the original value

c1FlexGrid1(2 2) = hello

Styles In VSFlexGrid you can customize theappearance of individual cells or cell rangesusing the Cell property

For instance in ActiveX you would write

Set the backcolor of second row

c1FlexGrid1Cell(flexcpBackColor

In C1FlexGrid cell appearance can becustomized using the CellStyle object

For instance in NET you would write

Create a cell style

Dim redStyle As CellStyle =

c1FlexGrid1Styles

FlexGrid for WinForms

8 Copyright copy GrapeCity Inc All rights reserved

2 0 2

c1FlexGrid1Cols-1) = vbRed

Demerit

To change the appearance of all red cellsyou need to clear all styles and start again oryou need to scan for red cells and thenchange their appearance

Add(Red)

redStyleBackColor = ColorRed

Set the backcolor of second row

c1FlexGrid1Rows(2)Style =

redStyle

Merit

The main advantage of this approach is that thenew style is an object that can be changed orassigned to new ranges For instance tochange the fore-color and text font of red cellsyou would write

c1FlexGrid1Styles(Red)ForeColor

= ColorWhite

c1FlexGrid1Styles(Red)Font =

new Font(Arial 9)

The VSFlexGrid control had many propertiesthat affected the way the grid was displayed(eg BackColor BackColorAlternateBackColorBkg BackColorFixedBackColorFrozen BackColorSel and so on)

The C1FlexGrid control replaces all theseproperties with a collection of CellStyle objectsso you can write something likeStylesFixedBackColor orStylesHighlightForeColor This makes theobject model simpler more consistent andmore powerful You can change the built-instyles or define your own and assign them torows columns or arbitrary cell ranges

WinFormsグリッドの比較

FlexGrid or True DBGridComponentOne offers two grid components in WinForms Edition FlexGrid and True DBGrid While both of these are robust and easy-to-usegrids allowing you to browse edit add delete and manipulate tabular data they still have their own strengths and capabilities

Both ComponentOne WinForms Edition grids can be used in bound as well as unbound mode but C1FlexGrid allows you to work more easilyin unbound mode With C1FlexGrid you can customize trees and make use of its cell merging capabilities FlexGrid is also apt for deriving acustomized grid

If you are planning to develop or migrate to NET 5 or higher it is recommended to use C1FlexGrid While we will continue to supportC1TrueDBGrid in NET 5 it no longer receives new enhancements and features like C1FlexGrid

Comparing ComponentOne Grids with MS DataGridViewThis section gives you a quick comparison between the two ComponentOne WinForms Edition grids and the standard MS DataGridViewavailable for WinForms platform For easy navigation we have broadly divided these features into different categories Click on thecorresponding category in the right hand pane or scroll down to know more about availability of a particular feature

Data Binding

Features FlexGrid TrueDBGrid MS DataGridView

Binding Data Sources

Binding Data Sources with hierarchical datarelations

With custom code

Unbound data storage and manipulations

Data Presentation

FlexGrid for WinForms

9 Copyright copy GrapeCity Inc All rights reserved

Features FlexGrid TrueDBGrid MS DataGridView

Hierarchical Styles With custom code

TreeView-like Styles

MultiLine Data View

Grouping

Built-in Drag And Drop

Horizontal and Vertical Interactive Splits

Child grids within master grid support

Drop-Down Objects Support

Drop-Down Multicolumn Object support

Drop-Down Multicolumn Bindable and SortableObject support

Data Exchange

Features FlexGrid TrueDBGrid MS DataGridView

Export Data (Delimited Text XLS and XLSX)

Export Data in other formats (PDF HTML RTFJPG and other)

Load data from Excel files

Enhanced Printing data from grid and PrintPreview support

Cell Manipulations

Features FlexGrid TrueDBGrid MS DataGridView

In-Cell Objects

Enhanced Cell Editing with Custom Editors

Merging Cells and Rows

Customize Cells Merging

Drag And Drop Columns and rows

Automatic Cell Sizing

Fixed Non-scrolling Columns

Excel-style Cell Selection

Customize each Cell Rendering

Zooming Cells

Run-Time CellTips

Data Manipulations with Cell Ranges

Layout and Styling

Features FlexGrid TrueDBGrid MS DataGridView

Visual Styles Support

Dynamic Support of 38 Decoration Themes

Office 2007 and 2010 Styling

Alternating Row Colors

Customizable Cell Border Style

FlexGrid for WinForms

10 Copyright copy GrapeCity Inc All rights reserved

Add Special Drawing Effects

Data-Sensitive Display

Input and Navigation

Features FlexGrid TrueDBGrid MS DataGridView

Input Masking

Simplify Data Input

Automatic Data Translation

Spell Checking support

Customizable Keyboard Navigation and keysbehavior

Right-To-Left navigation

Touch Support

Clipboard support

Rich Scrolling Capabilities

Data Manipulations

Features FlexGrid TrueDBGrid MS DataGridView

Sorting

Multi-column Sorting

Built-in Data Filtering

Extended and Conditional Filtering

Customizable filter form

Additional Filter Bar row

Multi-language Filtering

AutoSearch

Range Aggregates

Localization

Features FlexGrid TrueDBGrid MS DataGridView

Right-To-Left support

Net localization support

Regional settings support

Other Features

Features FlexGrid TrueDBGrid MS DataGridView

Optimize performance for displaying largeamount of data in bound and unbound mode

Just-In-Time Data Loading

Server-side Data Virtualization withC1DataSource

Automatic Lookup Columns with C1DataSource

Design-time extended support

Assembly size 1508 K 2108 K Part of

FlexGrid for WinForms

11 Copyright copy GrapeCity Inc All rights reserved

SystemWindowsForms

FlexGrid for WinForms

12 Copyright copy GrapeCity Inc All rights reserved

クイックスタート

This quick start will guide you through the steps of creating a simple grid application using the FlexGrid control Follow thesteps below to get started

FlexGrid for WinForms

13 Copyright copy GrapeCity Inc All rights reserved

This section demonstrates how to create a FlexGrid application in NET 452 by binding it to an externaldatasource You can also create a class to supply data to the grid as shown in the NET 5 tab Similarly you can usebelow steps to bind FlexGrid to a datasource in NET 5 However note that some design-time steps may vary in caseof NET 5

Set Up the Application1 Create a new Windows Forms app(NET Framework)2 Configure your project and set the Framework property3 Drag and drop the FlexGrid control from the Visual Studio toolbox onto the form

Observe An empty grid is added to the form at design time

Bind FlexGrid to a Data SourceThere are two ways to bind data with the FlexGrid control either choose to bind at design time or through code atrun time

Binding at Design Time

1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Click the Choose Data Source drop down button and select Add Project Data Source option to open the

Data Source Configuration Wizard3 On Choose a Data Source Type page select Database and click Next4 On Choose a Database Model page select Dataset and click Next5 On Choose Your Data Connection page click New Connection to open the Add Connection dialog6 Against the DataSource field click Change button to open the Change Data Source dialog7 Select Microsoft Access Database File and click OK to return to the Add Connection dialog8 Against the Database file name field click Browse and navigate to the database file Provide the User name

and Password if required to connect to the database file This example uses C1NWindmdb file located atthe following location by defaultDocumentsComponentOne SamplesCommon

9 Click Test Connection to make sure that you have successfully connected to the database or server and clickOK

NET 452

FlexGrid for WinForms

14 Copyright copy GrapeCity Inc All rights reserved

10 Click OK again to close the Add Connection dialog box11 Click Next 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 Choose the appropriate option as per your requirement12 Save the connection string in the application configuration file by checking the Yes save the connection as

box and entering a name13 Click Next to switch to the Choose Your Database Objects page14 Choose a table say Products from the Tables node and click Finish15 The above steps add a dataset and connection string to your project Also Visual Studio automatically creates

the following code to fill the datasetC

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて

移動または削除できます

thisproductsTableAdapterFill(thisc1NWindDataSetProducts)

VBNET

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移

動または削除できます

MeProductsTableAdapterFill(Mec1NWindDataSetProducts)

Binding at Run Time

To bind the grid through code first we need to create a database connection string Then use an object of dataadapter (in this case OleDbDataAdapter) to create a query to fetch products from the data table and fill it in thedata table which is assigned to the DataSource property of C1FlexGrid class

C

グリッドをデータソースに連結します

string conn = GetConnectionString()OleDbDataAdapter da = new OleDbDataAdapter(select from products conn)DataTable dt = new DataTable(Products)daFill(dt)c1FlexGrid1DataSource = dt

VBNET

グリッドをデータソースに連結します

Dim conn As String = GetConnectionString()Dim da As OleDbDataAdapter = New OleDbDataAdapter(select from products conn)Dim dt As DataTable = New DataTable(Products)daFill(dt)c1FlexGrid1DataSource = dt

Note that the above sample code uses a custom method named GetConnectionString to create a connection stringwith database

C

static string GetConnectionString() string path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) + ComponentOne SamplesCommon string conn = provider=microsoftjetoledb40data source=0c1nwindmdb return stringFormat(conn path)

VBNET

Private Shared Function GetConnectionString() As String Dim path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) amp

FlexGrid for WinForms

15 Copyright copy GrapeCity Inc All rights reserved

ComponentOne SamplesCommon Dim conn = provider=microsoftjetoledb40data source=0c1nwindmdb Return StringFormat(conn path)End Function

Configure the FlexGrid controlThis section walks you through the design-time and run-time steps to configure the grid with some basic settingsThese settings and features are explained in detail in the topics below

Configuring Grid at Design Time

Click smart tag to open the C1FlexGrid Tasks MenuClick the Styles option to open C1FlexGrid Styles EditorSelect Fixed from Built-in Styles pane customize some settings such as Backcolor Font and ForeColor andclick OKTo fit the grid to the form click the Dock in Parent Container optionFor customizing a column click the column (say Unit Price column) to open C1FlexGrid Column TasksMenuClick the ellipsis alongside Format field to open the Format String dialogSelect Currency as Format Type and click OK

Configuring Grid at Run Time

Add following code to configure the grid and its columns at run time

C

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = new Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols[6]Format = c

VBNET

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = New Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols(6)Format = c

FlexGrid for WinForms

16 Copyright copy GrapeCity Inc All rights reserved

This section demonstrates how to create a FlexGrid application in NET 5 by populating its data from a custom classYou can also use an external datasource to supply data to the grid as shown in NET 452 tab However note thatsome design-time steps given in the aforementioned tab may vary in case of NET 5 Similarly you can use belowsteps to bind FlexGrid to an internal datasource in NET 452

Set Up the Application1 Create a new Windows Forms app(NET Framework)2 Configure your project and set the Framework property3 Initialize the FlexGrid control and add it to the form

C

コントロールを初期化します

C1FlexGrid flexGrid = new C1FlexGrid() フォームにコントロールを追加します

thisControlsAdd(flexGrid)

VBNET

コントロールを初期化します

Dim flexGrid As C1FlexGrid = New C1FlexGrid() フォームにコントロールを追加します

MeControlsAdd(flexGrid)

Bind FlexGrid to a Data Source1 Create a custom class Product to be used as a data source

C

カスタムクラスProductを作成します

public class Product static Random _rnd = new Random()

NET 5

FlexGrid for WinForms

17 Copyright copy GrapeCity Inc All rights reserved

static string[] _names = Macko|Surfair|Pocohey|StudebySplit(|) static string[] _lines = Computers|Washers|Stoves|CarsSplit(|) static string[] _colors = Red|Green|Blue|WhiteSplit(|) public Product() Name = _names[_rndNext() _namesLength] Line = _lines[_rndNext() _linesLength] Color = _colors[_rndNext() _colorsLength] Price = 30 + _rndNextDouble() 1000 Cost = 3 + _rndNextDouble() 300 Discontinued = _rndNextDouble() lt 2 Introduced = DateTimeTodayAddDays(_rndNext(-600 0)) public string Name get set public string Color get set public string Line get set public double Price get set public double Cost get set public DateTime Introduced get set public bool Discontinued get set

VBNET

カスタムクラスProductを作成します

Public Class Product Private Shared _rnd As Random = New Random() Private Shared _names As String() = Macko|Surfair|Pocohey|StudebySplit(|c) Private Shared _lines As String() = Computers|Washers|Stoves|CarsSplit(|c) Private Shared _colors As String() = Red|Green|Blue|WhiteSplit(|c)

Public Sub New() Name = _names(_rnd[Next]() Mod _namesLength) Line = _lines(_rnd[Next]() Mod _linesLength) Color = _colors(_rnd[Next]() Mod _colorsLength) Price = 30 + _rndNextDouble() 1000 Cost = 3 + _rndNextDouble() 300 Discontinued = _rndNextDouble() lt 2 Introduced = DateTodayAddDays(_rnd[Next](-600 0)) End Sub

Public Property Name As String Public Property Color As String Public Property Line As String Public Property Price As Double Public Property Cost As Double Public Property Introduced As Date Public Property Discontinued As BooleanEnd Class

2 Initialize a list of type ProductC

Productがクラス型であるProduct型のリストを初期化します

ListltProductgt _products = new ListltProductgt()

FlexGrid for WinForms

18 Copyright copy GrapeCity Inc All rights reserved

VBNET

Productがクラス型であるProduct型のリストを初期化します

Dim _products As List(Of Product) = New List(Of Product)()

3 Initialize a For loop and add products to the list

C

forループを初期化し製品をリストに追加します

for (int i = 0 i lt100 i++) _productsAdd(new Product())

VBNET

forループを初期化し製品をリストに追加します

For i As Integer = 0 To 100 - 1 _productsAdd(New Product())Next

4 Bind FlexGrid to the created data sourceC

FlexGridにデータを連結します flexGridDataSource = _products

VBNET

FlexGridにデータを連結します flexGridDataSource = _products

Configure the FlexGrid controlAdd following code to configure the grid and its columns at run time

C

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = new Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols[6]Format = c

VBNET

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = New Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols(6)Format = c

FlexGrid for WinForms

19 Copyright copy GrapeCity Inc All rights reserved

設計時サポート

FlexGrid for WinForms comes with various design time options to make your programming tasks a lot easier In addition to smart tag context menu andproperty grid FlexGrid provides tasks menus and editors as well While C1FlexGrid Tasks menu lets you work on the entire grid in design time the ColumnTasks menu provides options to set some common properties for each column of the grid At the same time various editors such as C1FlexGrid ColumnEditor and C1FlexGrid Style Editor provide detailed properties to customize the columns and styles

This section discusses about various design-time options available in the FlexGrid control

Topic Snapshot Content

Tasks Menus Discusses about the C1FlexGrid Tasks menu the Column Tasks menu and their options

C1FlexGrid Tasks MenuC1FlexGrid Column Tasks Menu

Editors Discusses about the various editors and how to access them

C1FlexGrid Column EditorC1FlexGrid Style EditorCaption Style EditorColumn Style Editor

タスクメニュー

C1FlexGrid Tasks MenuC1FlexGrid Tasks menu provides you an easy access to the commonly used properties of FlexGrid It also providesoptions to open various editors such as C1FlexGrid Column Editor C1FlexGrid Style Editor

To access the C1FlexGrid Tasks menu click the smart tag ( ) in the upper right corner of the grid Following tableexplains various options available through the C1FlexGrid Tasks menu

Option Description

ChooseDataSource

The dropdown opens the list of available data sourcesand gives you Add Project Data Source option to openData Source Configuration Wizard

For more information on how to add a new data sourceto the project see Bound Mode

EnableAddingRows

The checkbox toggles the AllowAddNew propertywhich allows users to add new row to the grid at runtime When checked ON it displays a template row withstar at the bottom of the grid to enter the new record

EnableDeletingRows

The checkbox toggles the AllowDelete property whichallows users to delete the selected rows by pressing theDelete key

EnableEditing

The checkbox toggles the AllowEditing property whichallows users to edit the grid

Enable Column Reordering The checkbox sets the AllowDragging property toColumns which allows users to re-order the columns by draggingthe column headers

Enable Column Filtering The checkbox toggles the FlexGridAllowFiltering property to

FlexGrid for WinForms

20 Copyright copy GrapeCity Inc All rights reserved

enable or disable the filtering on grid columns

VisualStyle The dropdown lets you choose the built-in visual styles availablein the grid By default the value is set to Custom

Designer The option opens C1FlexGrid Column Editor which allows you toset the properties of each column of the grid

Styles The option opens C1FlexGrid Style Editor which allows youto customize the various pre-defined styles or create the newstyles at design time

Display Hidden Columns The checkbox lets you display or hide grid columns in the designview Note that this option is NOT associated with the run-timevisibility of columns Hence even if this checkbox is checked ONcolumns with Visible property set to False still remain hiddenwhen the application is run

Column Tasks The option switches the task menu to C1FlexGrid Column Tasksmenu which provides options to set the properties for theselected column

About C1FlexGrid The option displays a dialog box displaying the information suchas version of the FlexGrid control

Dock in Parent Container This option sets the Dock property of the grid to Fill which resizesthe grid to occupy the whole form space Clicking the option alsoswitches the text and provides option to Undock in ParentContainer which restores the grid to its original size

C1FlexGrid Column Tasks MenuC1FlexGrid Column Tasks menu provides you an easy access to the commonly used properties of grid columns Italso provides options to open editors named Caption Style and Column Style

To access the C1FlexGrid Column Tasks menu double-click header of the column to be configured at design-timeAnother way to open C1FlexGrid Column Tasks menu is to click on the smart tag ( ) in the upper right corner of thegrid and then navigate to the Column Tasks option Following table explains various options available through theC1FlexGrid Column Tasks menu

FlexGrid for WinForms

21 Copyright copy GrapeCity Inc All rights reserved

Option Description

ColumnCaption

The field allows you to specify the value of Captionproperty which sets text in header cell of the column

DataField

The dropdown opens a list of available fields in the datasource to choose from and sets value of Name property ofthe column

DataType

The dropdown opens a list of available data types and letsyou set the data type of the selected column This fieldcorresponds to the DataType property of the column

EditMask

The field lets you specify value of EditMask property whichsets mask for the selected column The ellipsis button onthe right side of the field opens the Input Mask dialog boxwhere you can select from the list of pre-defined masks

FormatString

The field lets you specify the value of Format propertywhich sets format string to display data value from source

ComboList

The field lets you specify the list of multiple values fromwhich user can choose The ellipsis button on the right sideof the field lets you open the Combo List dialog box whereyou can specify the value options

Allow Sorting The checkbox toggles the AllowSorting property to enable ordisable sorting in the column By default sorting is enabled for allcolumns

Allow Editing The checkbox toggles the AllowEditing property to make thecolumn read-only or editable By default editing is enabled for allcolumns

Allow Resizing The checkbox toggles the AllowResizing property which allows usersto adjust the size of column at run time By default resizing isenabled for all columns

Allow Dragging The checkbox toggles the AllowDragging property to enable ordisable re-ordering of the column at run time By default dragging isenabled for all columns

Allow Merging The checkbox toggles the AllowMerging property to enable ordisable merging two adjacent column cells having same values Bydefault merging is disabled for all columns

Allow Filtering The dropdown lets you specify the value of ColumnAllowFilteringproperty and choose the type of filter for each column The availableoptions are Default ByValue ByCondition Custom or None

Visible The checkbox lets you set the visibility of the column in the grid atrun time by toggling value of its Visible property

FlexGrid for WinForms

22 Copyright copy GrapeCity Inc All rights reserved

Caption Style The option opens the Caption Style editor which gives you options tostyle the text alignment background and border for the header cellof column

Column Style The option opens the Column Style editor which gives you options tostyle the text alignment background and border for the column text

C1FlexGrid Tasks The option switches the task menu to C1FlexGrid Tasks menu whichprovides options to set the properties for the entire grid

Dock in Parent Container The option sets the Dock property of the grid to Fill which resizes thegrid to occupy the whole form Clicking the option also switches thetext and provides option to Undock in Parent Container whichrestores the grid to its original size by setting the Dock property toNone

エディタ

Apart from the tasks menu FlexGrid also provides various editors that help you set a number of properties related togrid its columns and their styles

C1FlexGrid Column EditorFlexGrid provides the C1FlexGrid Column Editor making it easy to work with columns at design-time instead ofwriting code The editor lets you set various properties related to columns such as Caption DataTypeAllowFiltering and AllowMerging through its property pane on left hand side Toolbar on the top of this editorgives you options such as reloading data from the data source adding removing and resizing columns You can evenstyle the column text using the options given in this toolbar For further customization of column text you can usethe Column Style editor to access more specific properties

FlexGrid for WinForms

23 Copyright copy GrapeCity Inc All rights reserved

There are three ways in which you can access the C1FlexGrid Column Editor at design time

Smart Tag Click the smart tag ( ) in the upper right corner of the grid and select Designer from theC1FlexGrid Tasks menuProperty Window Select the grid go to the Properties window and click the ellipsis button (hellip) next to theCols propertyContext Menu Right-click the grid and select Designer from the context menu

C1FlexGrid Style EditorFlexGrid provides the C1FlexGrid Style editor which lets you style the grid at design time by customizing the built-instyles and creating the new ones The editor offers a list of styles for specific types of cell on left hand side and aproperty window on right hand side to customize these styles The list of styles is divided into two sections thedefault Built-in Styles and Custom Styles Towards the bottom there are Add and Remove buttons to add anddelete the custom styles and a Clear button to revert the editor to default settings The AutoFormat button in theend opens a secondary dialog C1FlexGrid Auto Format which lists the pre-defined set of styles and also shows apreview in the Preview pane

FlexGrid for WinForms

24 Copyright copy GrapeCity Inc All rights reserved

There are three ways in which you can access the C1FlexGrid Style Editor at design-time

Smart Tag Click the smart tag ( ) in the upper right corner of the grid and select Styles from theC1FlexGrid Tasks menuProperty Window Select the grid go to the Properties window and click the ellipsis button (hellip) next to theStyles propertyContext Menu Right-click the grid and select Styles from the context menu

Caption Style EditorFlexGrid provides the Caption Style editor which allows you to set styling related properties of the column header celland its text The editor comprises of four tabs Text Alignment Border and Background for customizing variousaspects of the header cells

To access the Caption Style editor click smart tag ( ) click the C1FlexGrid Column Tasks option on the task menu toopen column tasks and then go to Caption Style option

FlexGrid for WinForms

25 Copyright copy GrapeCity Inc All rights reserved

Column Style EditorSimilar to Caption Style editor FlexGrid provides another editor the Column Style editor for styling the column textThe editor has got the same options as that of Caption Style editor The only difference is that Caption Style editorcustomizes the column header text while this editor works on the general text in the column cells

To access the Column Style editor click smart tag ( ) click the C1FlexGrid Column Tasks option on the task menu toopen column tasks and then go to Column Style option

FlexGrid for WinForms

26 Copyright copy GrapeCity Inc All rights reserved

データ

This section discusses about various ways to populate data in the FlexGrid control

Topic Snapshot Content

Unbound Mode Discusses how to populate data in the unbound grid

Bound Mode Discusses ways of populating data in the grid through data binding and various operations on bound grid

Binding at design timeBinding at run time using DataSource propertyBinding at run time using SetDataBinding methodOperations in Bound Mode

非連結モード

As the name suggests in unbound mode grid is not bound to any data source and data is stored in the control itselfIn this case you need to provide data by adding rows and columns either at design time or programmatically throughrow and column collections You can also create an empty grid to let user enter the data

An unbound grid is not a very common scenario as grid does not store the data and hence user needs to manage itmanually However unbound grids suits better to some business scenarios like creation and maintenance of recordsFor instance you can use the grid in unbound mode for recording the date-wise sales data or to maintain the dailyinventory changes Below example demonstrates a grid with data populated through code

In C1FlexGrid you can add empty rows or columns by setting the Count property of row or column objects Also youcan use the Add method of these collections to add the empty rows and columns to a grid To set data in the cellsyou can either use the familiar index notation(Item property) or the SetData method For more information on settingdata in the cells see Storing and Retrieving Data

Use the code below to populate data in unbound FlexGrid for WinForms

連結されていない列を追加しますColumn col = _flexColsAdd()colName = colCaption = Unbound_flex[1 Unbound] = 123

C

連結されていない列を追加しますDim col As Column = C1FlexGrid1ColsAdd()colName = UnboundcolCaption = Unbound

VBNET

FlexGrid for WinForms

27 Copyright copy GrapeCity Inc All rights reserved

連結モード

Bound mode as the name suggests refers to a state where grid fetches its data from an underlying data source Databinding also allows multiple data consumers to be connected to a data provider in the synchronized manner

FlexGrid supports data binding to most of the commonly used data sources such as ObservableCollection IListltTgtListltTgt Array BindingSource ADONET objects such as DataSet DataTable etc

There are three ways of binding FlexGrid to a data source

Binding at design timeBinding at run time using DataSource propertyBinding at run time using SetDataBinding method

Binding at Design Time1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Click the Choose Data Source drop down button and select Add Project Data Source option to open the

Data Source Configuration Wizard3 On Choose a Data Source Type page select Database and click Next4 On Choose a Database Model page select Dataset and click Next5 On Choose Your Data Connection page click New Connection to open the Add Connection dialog6 Against the DataSource field click Change button to open the Change Data Source dialog7 Select Microsoft Access Database File and click OK to return to the Add Connection dialog8 Against the Database file name field click Browse and navigate to the database file Provide the User name

and Password if required to connect to the database file This example uses C1NWindmdb file located at thefollowing location by defaultDocumentsComponentOne SamplesCommon

FlexGrid for WinForms

28 Copyright copy GrapeCity Inc All rights reserved

9 Click Test Connection to make sure that you have successfully connected to the database or server and clickOK

10 Click OK again to close the Add Connection dialog box11 Click Next 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 Choose the appropriate option as per your requirement12 Save the connection string in the application configuration file by checking the Yes save the connection as

box and entering a name13 Click Next to switch to the Choose Your Database Objects page14 Choose a table say Products from the Tables node and click Finish15 The above steps add a dataset and connection string to your project Also Visual Studio automatically creates

the following code to fill the dataset

Binding at Run Time Using DataSource PropertyFlexGrid provides the DataSource property to bind the FlexGrid control to a data source at run time You need toassign a data source object to the DataSource property of FlexGrid If the data source object contains more than onetable you can set the DataMember property to table name to specify the target table

Following code uses DataSource property to bind data to the WinForms FlexGrid

Note that the above sample code uses a custom method named GetData to supply data You can set up the datasource as per your requirements Following code shows an example of creating data for WinForms FlexGrid

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移動または削除できます thisproductsTableAdapterFill(thisc1NWindDataSetProducts)

C

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移動または削除できます MeProductsTableAdapterFill(Mec1NWindDataSetProducts)

VBNET

c1FlexGrid1BeginUpdate()C1DataCollectionltCustomergt c1DataCollection = new C1DataCollectionltCustomergt(GetData())c1FlexGrid1DataSource = new C1DataCollectionBindingList(c1DataCollection)c1FlexGrid1EndUpdate()

C

c1FlexGrid1BeginUpdate()Dim c1CollectionView As C1DataCollectionC1DataCollection(Of Customer) = New C1DataCollectionC1DataCollection(Of Customer)(GetData())c1FlexGrid1DataSource = New C1DataCollectionBindingListC1DataCollectionBindingList(c1CollectionView)c1FlexGrid1EndUpdate()

VBNET

ObservableCollectionltCustomergt GetData() var data = new ObservableCollectionltCustomergt() for (int i = 0 i lt 25 i++)

C

FlexGrid for WinForms

29 Copyright copy GrapeCity Inc All rights reserved

Binding at Run Time Using SetDataBinding MethodFlexGrid also provides the SetDataBinding method using which you can set DataSource and DataMember propertiesboth using a single call The following code demonstrates an example of rendering a parent table and its child tablesin different grids with the help of the SetDataBinding method

Below code demonstrates how to bind data to WinForms FlexGrid using SetDataBinding method

dataAdd(new Customer()) return data

Private Function GetData() As ObservableCollection(Of Customer) Dim data = New ObservableCollection(Of Customer)()

For i = 0 To 25 - 1 dataAdd(New Customer()) Next

Return dataEnd Function

VBNET

グリッドにデータセットを連結します_flexCustomersBeginUpdate()_flexCustomersSetDataBinding(ds Customers)_flexCustomersEndUpdate()

_flexOrdersBeginUpdate()_flexOrdersSetDataBinding(ds CustomersCustomerOrders)_flexOrdersEndUpdate()

_flexOrderDetailsBeginUpdate()_flexOrderDetailsSetDataBinding(ds CustomersCustomerOrdersOrderDetails)_flexOrderDetailsEndUpdate()

C

グリッドにデータセットを連結します_flexCustomersBeginUpdate()_flexCustomersSetDataBinding(ds Customers)_flexCustomersEndUpdate() _flexOrdersBeginUpdate()_flexOrdersSetDataBinding(ds CustomersCustomerOrders)_flexOrdersEndUpdate() _flexOrderDetailsBeginUpdate()_flexOrderDetailsSetDataBinding(ds CustomersCustomerOrdersOrderDetails)_flexOrderDetailsEndUpdate()

VBNET

連結モードでの操作

Adding Unbound Column in Bound ModeIn the bound mode grid fetches the data from data source and display it as records and bound columns To add a column to

FlexGrid for WinForms

30 Copyright copy GrapeCity Inc All rights reserved

display data that does not exist in the data source you need to add unbound columns at design time or through code

Adding unbound column at design time

1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Bind the grid control with a data source For detailed steps about how to bind FlexGrid to a data source see Bound

Mode3 Click the Designer option to open the C1FlexGrid Column Editor4 In the right hand side pane select an existing column from the grid preview5 Click Insert Column options in the toolbar to add a column before or after the selection

Adding unbound column through code

FlexGrid provides Add Insert and InsertRange method of the ColumnCollection class to add an unbound column to the gridWhile Add method adds a column at the end the Insert method lets you specify the position where you want to add a newcolumn Similarly you can add multiple columns at a specified position by using the InsertRange method

Use the code below to add unbound column in a bound WinForms FlexGrid

連結されていない列を追加しますColumn col = _flexColsAdd()colName = colCaption = Unbound_flex[1 Unbound] = 123

C

連結されていない列を追加しますDim col As Column = C1FlexGrid1ColsAdd()colName = UnboundcolCaption = Unbound

VBNET

FlexGrid for WinForms

31 Copyright copy GrapeCity Inc All rights reserved

Set Values in Unbound ColumnTo define values in the unbound column of bound grid you need to usethe SetUnboundValue and GetUnboundValue events of the C1FlexGrid class First create a hash table to store the enteredvalues then use the SetUnboundValue event to set unbound value in the hash table using a unique key to identify therecord and use GetUnboundValue event to get the value stored in the hash table using its unique key and set unboundvalue to be displayed in the cell

Following code shows how to set values in an unbound column added to a bound WinForms FlexGrid

Displaying Data in Fixed ColumnTo set values in the fixed columns you need to set DrawMode property of the C1FlexGrid class to OwnerDraw in the formload event and then create the OwnerDrawCell event to set values in the fixed column cells In this example we are settingrow numbers in the fixed column of a bound WinForms FlexGrid

get value from hashtable using ProductID as keyvoid _flex_GetUnboundValue(object sender C1WinC1FlexGridUnboundValueEventArgs e) DataRowView drv = (DataRowView)_flexRows[eRow]DataSource eValue = _hash[drv[ProductID]]

store value in hashtable using ProductID as keyvoid _flex_SetUnboundValue(object sender C1WinC1FlexGridUnboundValueEventArgs e) DataRowView drv = (DataRowView)_flexRows[eRow]DataSource _hash[drv[ProductID]] = eValue

C

Private Sub C1FlexGrid1_GetUnboundValue(sender As Object e As C1WinC1FlexGridUnboundValueEventArgs) Handles C1FlexGrid1GetUnboundValue Dim drv As DataRowView = DirectCast(C1FlexGrid1Rows(eRow)DataSource DataRowView) eValue = _hash(drv(ProductID))End Sub

Private Sub C1FlexGrid1_SetUnboundValue(sender As Object e As C1WinC1FlexGridUnboundValueEventArgs) Handles C1FlexGrid1SetUnboundValue Dim drv As DataRowView = DirectCast(C1FlexGrid1Rows(eRow)DataSource DataRowView) _hash(drv(ProductID)) = eValueEnd Sub

VBNET

FlexGrid for WinForms

32 Copyright copy GrapeCity Inc All rights reserved

Auto-adjust Column WidthFlexGrid provides AutoResize property of the C1FlexGrid class to adjust the width of columns automatically according tothe text length You need to set the property to true before binding it to the data source to load the grid with appropriatecolumn width You can also call AutoSizeCol method to adjust the width of the specified column

Use the code below auto-adjust the column width according to the text in WinForms FlexGrid

Display Bitmap Image in FieldIn most of the scenarios grid directly fetches the images from the data source However if the grid is bound to a databasewhich stores images as OLE objects such as Microsoft Access a little bit of extra processing is required to fetch bitmapimages In such case you need to convert the image data stored as byte array to a memory stream and then usethe OwnerDrawCell event to load the image In the form load event you need to set the DrawMode property toOwnerDraw Also adjust the height of row to display the image properly

Following code demonstrates how to display bitmap image in fields of WinForms FlexGrid

private void C1FlexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if ((eRow gt= thisc1FlexGrid1RowsFixed) amp (eCol == (thisc1FlexGrid1ColsFixed - 1))) eText = eRowToString() または任意のテキスト

C

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If eRow gt= Mec1FlexGrid1RowsFixed And eCol Is Mec1FlexGrid1ColsFixed - 1 Then eText = eRowToString() または任意のテキスト End IfEnd Sub

VBNET

すべての列の幅を自動的に調整します c1FlexGrid1AutoResize = true

4列目の幅を自動調整します c1FlexGrid1AutoSizeColumns(3)

C

すべての列の幅を自動的に調整します c1FlexGrid1AutoResize = True

4列目の幅を自動調整します c1FlexGrid1AutoSizeColumns(3)

VBNET

private void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) if(eMeasuring ampamp eRowgt=c1FlexGrid1RowsFixed ampamp eCol gt=

C

FlexGrid for WinForms

33 Copyright copy GrapeCity Inc All rights reserved

Note that the above sample code uses a custom method LoadImage method to convert the images from byte array to amemory stream

c1FlexGrid1ColsFixed) 「Photo」はblob(byte [])に保存された画像です if (c1FlexGrid1Cols[eCol]Name == Picture) mdbからロードしてみてください eImage = LoadImage(c1FlexGrid1[eRow eCol] as byte[])

画像が表示された場合はテキストを入力しないでください if (eImage = null) eText = null

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) If Not eMeasuring AndAlso eRow gt= c1FlexGrid1RowsFixed AndAlso eCol gt= c1FlexGrid1ColsFixed Then

「Photo」はblob(byte [])に保存された画像です If c1FlexGrid1Cols(eCol)Name Is Picture Then mdbからロードしてみてください eImage = LoadImage(TryCast(c1FlexGrid1(eRow eCol) Byte()))

画像が表示された場合はテキストを入力しないでください If eImage IsNot Nothing Then eText = Nothing End If End IfEnd Sub

VBNET

Image LoadImage(byte[] picData) static Image LoadImage(byte[] picData) これが埋め込みオブジェクトであることを確認してください const int bmData = 78 if (picData == null || picDataLength lt bmData + 2) return null if (picData[0] = 0x15 || picData[1] = 0x1c) return null

現在点ではビットマップのみを処理します if (picData[bmData] = B || picData[bmData + 1] = M) return null

画像をロードします Image img = null try MemoryStream ms = new MemoryStream(picData bmData picDataLength - bmData) img = ImageFromStream(ms) catch

画像を返します return img

C

Private Function LoadImageMethod(ByVal picData As Byte()) As Image

VBNET

FlexGrid for WinForms

34 Copyright copy GrapeCity Inc All rights reserved

Private Shared Function LoadImage(ByVal picData As Byte()) As Image これが埋め込みオブジェクトであることを確認してください Const bmData As Integer = 78 If picData Is Nothing OrElse picDataLength lt bmData + 2 Then Return Nothing If picData(0) ltgt ampH15 OrElse picData(1) ltgt ampH1c Then Return Nothing

現在点ではビットマップのみを処理します If picData(bmData) ltgt Bc OrElse picData(bmData + 1) ltgt Mc Then Return Nothing

画像をロードします Dim img As Image = Nothing

Try Dim ms As MemoryStream = New MemoryStream(picData bmData picDataLength - bmData) img = ImageFromStream(ms) Catch End Try

画像を返します Return imgEnd Function

FlexGrid for WinForms

35 Copyright copy GrapeCity Inc All rights reserved

A grid control is a collection of rows and columns Columns generally contain a particular type of information through out while rows are used to recorddifferent types of information about a particular item

In FlexGrid the collection of columns is represented by the ColumnCollection class which can be accessed through Cols property of the C1FlexGrid class Thissection discusses the various operations that can be performed on columns

Topic Snapshot Content

BasicOperations

Discusses about how to perform basic column operations

Set Column CountAdd ColumnDelete ColumnInsert ColumnSet Data TypeSet Fixed ColumnSet Frozen Column

UserInteraction

Discusses about operations that can be performed by the end user at run time

Allow EditingAllow DraggingAllow FreezingAllow SortingAllow FilteringAllow Resizing

Editors Discusses about various built-in editors of FlexGrid and operations related to them Also discusses how to use customeditors in the FlexGrid

CheckBoxNumericDateComboBoxMaskMapped ListCell Button

Validation Discusses how to apply validation and show error information on FlexGrid cells

Sparkline Discusses about how to display Sparkline charts in FlexGrid cells

Header andFooter

Discusses about how to set column header and footer

Set Header TextMerge column headerWrap column header textStyle Column HeaderSet Column Footer

Sizing Discusses about various aspects of column sizing

Set Column WidthAuto-adjust Column WidthSet MinMax Column WidthStar Sizing

基本操作

This topic discusses various basic operations which can be performed on a column

FlexGrid for WinForms

36 Copyright copy GrapeCity Inc All rights reserved

Set Column CountWhen grid is bound to a data source the number of columns is determined by the number of fields available in thedata source However in the case of unbound mode you can set any arbitrary value in the Count property ofthe ColumnCollection class to set the number of columns to be displayed in the grid

Use the code below to set the number of columns to be added to WinForms FlexGrid in unbound mode

Add ColumnFlexGrid provides two ways to add a new column using the ColumnCollection class You can either use Add methodor increment the value of Count property provided by the class to add new columns Also note that if a new columnis added to a bound grid using these methods it is added as an unbound column only

Following are the two approaches to add column to a WinForms FlexGrid

Delete ColumnTo delete a particular column from the grid you can use Remove method of the ColumnCollection class and specifythe column you want to delete as its parameter In the unbound grid you can also reduce the number of columns bychanging the value of Count property This removes columns from the end of the column collection TheColumnCollection class also provides RemoveRange method which allows you to remove a range of columns

列数を設定します c1FlexGrid1ColsCount = 4

C

列数を設定しますc1FlexGrid1ColsCount = 4

VBNET

方法1 列コレクションのAddメソッドを使用します C1WinC1FlexGridColumn c c = c1FlexGrid1ColsAdd() cCaption = New Column

方法2 列コレクションのCountプロパティを変更します c1FlexGrid1ColsCount += 1 c1FlexGrid1Cols[c1FlexGrid1ColsCount - 1]Caption = New Column

C

方法1 列コレクションのAddメソッドを使用します Dim c As C1WinC1FlexGridColumn c = c1FlexGrid1ColsAdd() cCaption = New Column

方法2 列コレクションのCountプロパティを変更します c1FlexGrid1ColsCount += 1 c1FlexGrid1Cols(c1FlexGrid1ColsCount - 1)Caption = New Column

VBNET

FlexGrid for WinForms

37 Copyright copy GrapeCity Inc All rights reserved

Below code snippet shows all the three approaches to delete column from the WinForms FlexGrid

Insert ColumnTo insert a column in FlexGrid at a specific location you can use Insert method of the ColumnCollection class whichlets you specify the position where columns are to be inserted You can also insert multiple columns in the grid byusing the InsertRange method These methods add the unbound columns only even if the grid is a bound grid

Use any of the following approaches to insert a column in the WinForms FlexGrid at the specified location

方法1 列コレクションのRemoveメソッドを使用して2番目の列を削除します c1FlexGrid1ColsRemove(2)

方法2 Countプロパティを変更して最後の列を削除します c1FlexGrid1ColsCount -= 1

方法3 RemoveRangeメソッドを使用して2番目から始まる4つの列を削除します c1FlexGrid1ColsRemoveRange(2 4)

C

方法1 列コレクションのRemoveメソッドを使用して2番目の列を削除します c1FlexGrid1ColsRemove(2)

方法2 Countプロパティを変更して最後の列を削除します c1FlexGrid1ColsCount -= 1

方法3 RemoveRangeメソッドを使用して2番目から始まる4つの列を削除します c1FlexGrid1ColsRemoveRange(2 4)

VBNET

C1WinC1FlexGridColumn c

方法1 Insertメソッドを使用して2番目の位置に列を挿入します c = c1FlexGrid1ColsInsert(2) cCaption = Inserted Column

方法2 InsertRangeメソッドを使用して2番目の位置に3つの列を挿入します c1FlexGrid1ColsInsertRange(2 3)

C

Dim c As C1WinC1FlexGridColumn 方法1 Insertメソッドを使用して2番目の位置に列を挿入します c = c1FlexGrid1ColsInsert(2) cCaption = Inserted Column 方法2 InsertRangeメソッドを使用して2番目の位置に3つの列を挿入します c1FlexGrid1ColsInsertRange(2 3)

VBNET

FlexGrid for WinForms

38 Copyright copy GrapeCity Inc All rights reserved

Set Data TypeIn case of a bound FlexGrid data type of each bound column is automatically picked from the data source dependingon the data However in the case of unbound mode you can set the data type of columns by specifyingthe DataType property of Column class You can also set the Data Type property at design time by using theColumn Tasks menu For more information on tasks menus see Tasks Menus Note that when a particular data type isset to a FlexGrid column its cells accept the user input of keys accepted by the data type only For instance you cannot input alphabets in a Numeric type cell

Set the data type of an unbound column in WinForms FlexGrid as shown in the code below

Set Fixed ColumnFixed columns refer to the columns with non-editable cells which are always visible in the left hand side of the grideven if user scrolls the grid horizontally In FlexGrid fixed columns can be set using Fixed property ofthe ColumnCollection class This property accepts an integer value that specifies the number of columns to be fixed

Use the code below to set one column as fixed in the WinForms FlexGrid

Set Frozen ColumnFrozen columns similar to fixed columns are non-scrollable but can be edited by the user In FlexGrid frozen columnscan be set by using Frozen property provided by the ColumnCollection class

To set frozen columns in the WinForms FlexGrid use the code below

最初の列のデータ型を設定します c1FlexGrid1Cols[1]DataType = typeof(int)

C

最初の列のデータ型を設定しますc1FlexGrid1Cols(1)DataType = GetType(Integer)

VBNET

1つの列を固定列として設定しますc1FlexGrid1ColsFixed = 1

C

1つの列を固定列として設定しますc1FlexGrid1ColsFixed = 1

VBNET

最初の4列を静止として設定しますc1FlexGrid1ColsFrozen = 4

C

最初の4列を静止として設定しますc1FlexGrid1ColsFrozen = 4

VBNET

FlexGrid for WinForms

39 Copyright copy GrapeCity Inc All rights reserved

ユーザー操作

This topic discusses how you can let end users interact with the FlexGrid columns

Allow EditingBy default FlexGrid allows to edit all columns of the grid However you can choose to disable editing of a particularcolumn by setting AllowEditing property of the Column object to false You can also disable editing of the whole gridby setting the C1FlexGridAllowEditing property to false For more information on editing see Edit

Following code shows how to disable editing of WinForms FlexGrid while keeping only one column editable

Allow DraggingFlexGrid by default allows user to reorder columns by dragging a column header and dropping it to the targetposition However you can change this behavior by using the FlexGridAllowDragging propertyand ColumnAllowDragging property To disable dragging of a particular column you can set theColumnAllowDragging property of that column to false On the other hand setting the FlexGridAllowDraggingproperty to either Rows or None disables the column reordering at grid level This property accepts the valuesfrom AllowDraggingEnum You can also disable column reordering at design time by checking off the Enable ColumnReordering checkbox in the C1FlexGrid Tasks menu For more information on tasks menus see Tasks Menus

グリッド全体で編集を無効にしますc1FlexGrid1AllowEditing = false

3列目でのみ編集を有効にしますc1FlexGrid1Cols[3]AllowEditing = true

C

グリッド全体で編集を無効にしますc1FlexGrid1AllowEditing = False

3列目でのみ編集を有効にしますc1FlexGrid1Cols(3)AllowEditing = True

VBNET

FlexGrid for WinForms

40 Copyright copy GrapeCity Inc All rights reserved

Below code demonstrates how to enable dragging of columns in WinForms FlexGrid

Allow FreezingTo allow end user to freeze the columns at runtime you can use the AllowFreezing property of the C1FlexGrid classwhich accepts values from AllowFreezingEnum When this property is set to Columns or Both a lock sign appearswhen mouse is hovered over the edge of header column User can click and drag the lock sign to freeze the columns

Following code shows how to allow users to freeze the columns in WinForms FlexGrid

Allow PinningFlexGrid lets you allow your users to pin a particular column or column range at run time by using the AllowPinningproperty of the C1FlexGrid class Setting the property adds a Pin button( ) in the column header which allows usersto pin columns at run-time so they remain in view as the user scrolls the grid horizontally The property accepts itsvalues from AllowPinning enumeration which lets you set pinning for a single column or a column range Whenproperty is set to ColumnRange user can pin or unpin all the columns starting from left till the clicked column in onego

グリッド全体ですべての列のドラッグを許可します c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumColumns

特定の列のドラッグを無効にしますc1FlexGrid1Cols[3]AllowDragging = false

C

グリッド全体ですべての列のドラッグを許可します c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumColumns

特定の列のドラッグを無効にします c1FlexGrid1Cols(3)AllowDragging = False

VBNET

実行時に列のフリーズを許可します c1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumColumns

C

実行時に列のフリーズを許可しますc1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumColumns

VBNET

FlexGrid for WinForms

41 Copyright copy GrapeCity Inc All rights reserved

Use the code below to let user pin multiple columns in the WinForms FlexGrid

Allow SortingIn FlexGrid column sorting is enabled for the whole grid by default and value of AllowSorting property of theC1FlexGrid class is set to Auto In this mode user can sort a single column by clicking the column header andmultiple columns by holding the CTRL key while clicking the column headers On sorting multiple columns the gridshows sort index in the column header next to the sort direction glyph You can also choose to prevent sorting orsimply change the way the columns are sorted through AllowSortingEnum enumeration The AllowSortingEnumenumeration allows you to choose whether to auto sort columns sort single column multiple columns or columnrange or just prevent sorting

You can enable multi-column sorting in the WinForms FlexGrid using the code below When AllowSorting propertyis set to MultiColumn user may sort multiple columns by simply clicking on their headers one after the other

ユーザーが列範囲を固定できるようにしますc1FlexGrid1AllowPinning = C1WinC1FlexGridAllowPinningColumnRange

C

ユーザーが列範囲を固定できるようにしますc1FlexGrid1AllowPinning = C1WinC1FlexGridAllowPinningColumnRange

VBNET

グリッドで複数列の並べ替えを有効にしますc1FlexGrid1AllowSorting = C1WinC1FlexGridAllowSortingEnumMultiColumn

1列のみの並べ替えを無効にしますc1FlexGrid1Cols[1]AllowSorting = false

C

グリッドで複数列の並べ替えを有効にしますc1FlexGrid1AllowSorting = C1WinC1FlexGridAllowSortingEnumMultiColumn

1列のみの並べ替えを無効にしますc1FlexGrid1Cols(1)AllowSorting = False

VBNET

FlexGrid for WinForms

42 Copyright copy GrapeCity Inc All rights reserved

To disable sorting on a particular column you need to set the ColumnAllowSorting property of that column to falseFor more information on sorting see Sort

Allow FilteringFlexGrid doesnt allow filtering at runtime by default However you can enable it by settingthe C1FlexGridAllowFiltering property to true To define the type of filter you want to apply on a particularcolumn you can use the ColumnAllowFiltering property which accepts following values from the AllowFilteringenumeration

AllowFiltering Values Description

Default The grid automatically creates a filter of type ColumnFilter This filteris the combination of a value filter and a condition filter

ByValue The grid automatically creates a filter of type ValueFilter This filteroffers a checkbox list of values to choose from Values that are notchecked in the list are excluded from the filter output

ByCondition The grid automatically creates a filter of type ConditionFilter Thisfilter provides several options such as Equals is Greater thanContains Begins with etc to create conditions You can also combinetwo conditions by using the And and Or operators available in thefilter

Custom The grid does not create a filter automatically and allows you to defineyour own filter and then explicitly assign it to Filter property of theColumn class

None Filtering is disabled for the column

For more information on filtering see Filter

Following code shows how to enable filtering in the WinForms FlexGrid and how to apply filters

Allow ResizingBy default FlexGrid allows resizing of all columns of the grid To change this behavior you can use AllowResizingproperty of the C1FlexGrid class This property accepts values from the AllowResizingEnum enumeration which letsyou resize columns rows both or none The enumeration also gives you options to uniformly resize the rows columnsor both that is if you resize one of the columns or rows the grid automatically resizes rest of the columns or rows as

グリッドレベルでのフィルタリングを許可します c1FlexGrid1AllowFiltering = true

最初の列に条件フィルターを適用します c1FlexGrid1Cols[1]AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

C

グリッドレベルでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = True

最初の列に条件フィルターを適用しますc1FlexGrid1Cols(1)AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

VBNET

FlexGrid for WinForms

43 Copyright copy GrapeCity Inc All rights reserved

well FlexGrid also provides ColumnAllowResizing property which is a Boolean type property and lets you enable ordisable resizing of a particular row or column

Below code shows how to allow users to resize columns of WinForms FlexGrid

Enable Context MenuFlexGrid provides support for column context menu at run-time to facilitate quick actions related to columnoperations To enable the column context menu on right-click you need to set ColumnContextMenuEnabled propertyprovided by the C1FlexGrid class to true By default this property is set to false

The column context menu provides following options

Option Description

Sort Ascending Sorts the column in ascending order

Sort Descending Sorts the column in descending order

Group by This Groups the grid data based on column under mouse pointer

列と行のサイズを均一に変更できますc1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumBoth

最初の列のサイズ変更のみを無効にしますc1FlexGrid1Cols[1]AllowResizing = false

C

列と行のサイズを均一に変更できますc1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumBoth

最初の列のサイズ変更のみを無効にしますc1FlexGrid1Cols(1)AllowResizing = False

VBNET

FlexGrid for WinForms

44 Copyright copy GrapeCity Inc All rights reserved

Column

Ungroup Removes grouping from the grid data The option displays only when grid is in groupedstate

Hide this Column Hides the column under mouse pointer

Auto size Resizes the column according to the length of longest value

Auto size (allcolumns)

Resizes all columns according to the length of longest value in each of them

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = true

C

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = True

VBNET

Option Description

エディタ

This topic discusses various built-in editors of FlexGrid and operations related to them The topic also takes you through thesteps to apply custom editors in the FlexGrid columns

Built-in EditorsFlexGrid provides several built-in editors to enable efficient in-cell editing The grid uses TextBox control as its default editorHowever other built-in editors such as numeric date checkbox and combo box are also supported These editors areautomatically assigned generally based on the value of some specific properties such as DataType property of the column Thetable below summarizes the built-in editors provided by FlexGrid their brief description and the example codes demonstratingthem For more information about built-in editors and their customization click the corresponding hyperlink

Built-inEditor

Snapshot Description Sample Code

Checkbox Gets enabledautomatically whenDataType propertyof the Columnobject is set to

c1FlexGrid1Cols[colIndex]DataType =

typeof(Boolean)

FlexGrid for WinForms

45 Copyright copy GrapeCity Inc All rights reserved

Boolean

Numeric Gets enabledautomatically whenDataType propertyis set to a numericdata type such asInt or Decimal

c1FlexGrid1Cols[colIndex]DataType =

typeof(Int32)

Date Gets enabledautomatically if theDataType propertyof column is set toDate or DateTime

c1FlexGrid1Cols[colIndex]DataType =

typeof(DateTime)

ComboBox Gets enabled bysetting multiplevalues separated bypipe inthe ComboListproperty

c1FlexGrid1Cols[colIndex]ComboList =

Red|Green|Blue|Red|White

Mask Gets enabled whenthe EditMaskproperty of columnis set

c1FlexGrid1Cols[colIndex]EditMask =

(999) 999-9999

Mappedlist

Gets enabled whenthe DataMapproperty is set to anIDictionary objectwhich establishesmapping betweenvalues stored in thegrid and thosevisible to a user

ListDictionary customerNames = new

ListDictionary()

customerNamesAdd(AJK18F Sam

Anders)

customerNamesAdd(BBK21D Daneil)

customerNamesAdd(AEF25N Henry

Hussain)

customerNamesAdd(BZD42S Owen

Romanov)

customerNamesAdd(AKC16G Serena

Nguyen)

c1flexGrid1Cols[Name]DataMap =

customerNames

c1flexGrid1ShowButtons =

ShowButtonsEnumWithFocus

Cell Button Gets enabled whenthe ComboListproperty is set to anellipsis() whichautomaticallydisplays a cellbutton in editmode You can then

c1flexGrid1Cols[colIndex]ComboList

=

c1flexGrid1CellButtonClick +=

C1flexGrid1_CellButtonClick

FlexGrid for WinForms

46 Copyright copy GrapeCity Inc All rights reserved

capturethe CellButtonClickevent either toshow a dialog boxor to perform anyother operation

Custom EditorsFlexGrid control provides most of the commonly used editing options through the above-mentioned built-in editors However inaddition you can also use external controls as editors to meet the specialized editing needs Any control that derives from thebase Control class can be easily used as an editor This can be done at design time as well as through code In the examplebelow we are setting the C1ColorPicker control as a cell editor

At Design Time

1 Add the C1FlexGrid control and C1ColorPicker control to the form2 Select Designer option from the C1FlexGrid Tasks menu to open the C1FlexGrid Column Editor3 Select a column and switch to Properties pane on left hand side4 Navigate to the Editor property and set its value to instance of the C1ColorPicker control

At Run Time

To set an external control as editor through code create an instance of the control and assign it to the Editor property ofthe Column object

See the code below to know how to set an external control as editor in WinForms FlexGrid column

カスタムエディタとして使用するC1ColorPickerコントロールのインスタンスを作成します C1WinC1InputC1ColorPicker customeditor = new C1WinC1InputC1ColorPicker() カスタムエディタにEditorプロパティを割り当てます c1FlexGrid1Cols[1]Editor = customeditor

C

FlexGrid for WinForms

47 Copyright copy GrapeCity Inc All rights reserved

For controls which are not derived from the Control base class it is still possible to use them as editors usingIC1EmbeddedEditor interface You can even use the UITypeEditor classes as grid editors This way the FlexGrid control canuse virtually any control as a cell editor For more information about the implementation see the product sample named CustomEditors

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

カスタムエディタとして使用するC1ColorPickerコントロールのインスタンスを作成します Dim customeditor As C1WinC1InputC1ColorPicker = New C1WinC1InputC1ColorPicker()

カスタムエディタにEditorプロパティを割り当てます c1FlexGrid1Cols(1)Editor = customeditor

VBNET

チェックボックス

Display Checkbox for Boolean ValuesFlexGrid by default uses the checkbox editor for representing the Boolean values That is when the DataTypeproperty of a Row or Column object is set to Bool type a checkbox appears in the cells and user can toggle the valueof an editable cell simply by clicking it

To disable this default behavior and display text value instead of a checkbox in a Bool type you can set the Formatproperty of Row or Column object to string values

Default Checkbox Checkbox with Text Checkbox with Non-Boolean Value Three-state Checkbox

Use the code below to set checkbox type editor in a WinForms FlexGrid column and configure it further

データ型をブール値に設定します(チェックボックスを自動的に表示します)c1FlexGrid1Cols[Verified]DataType = typeof(Boolean)

チェックボックスを表示する代わりに文字列値を表示しますc1flexGrid1Cols[Verified]Format = YesNo ブール列のチェックボックスの横にあるテキストを有効にしますc1flexGrid1Cols[Verified]ImageAndText = true

C

データ型をブール値に設定します(チェックボックスを自動的に表示します)c1FlexGrid1Cols(Verified)DataType = GetType(Boolean)

チェックボックスを表示する代わりに文字列値を表示しますc1flexGrid1Cols(Verified)Format = YesNo

ブール列のチェックボックスの横にあるテキストを有効にしますc1flexGrid1Cols(Verified)ImageAndText = True

VBNET

FlexGrid for WinForms

48 Copyright copy GrapeCity Inc All rights reserved

Display Checkbox for Non-Boolean ValuesIn unbound mode you can display a checkbox along with any non-boolean text as well You can use the SetCellCheckmethod to add checkbox to any kind of cells Along with row and column index this method takes valueof CheckEnum enumeration as one of its parameters to specify the state of checkbox at the time of rendering

Following code demonstrates how you can display checkbox for non-boolean values

Set Checkbox AlignmentTo set position of checkbox in the cell you need to use ImageAlign property of the Row or Column object Thisproperty accepts values from the ImageAlignEnum enumeration which lets you hide tile stretch or position the image

Align the checkbox to display in center of a WinForms FlexGrid column using the code below

Change the Checkbox ImageTo change icon image of different states of checkbox you can use the GlyphEnum which can be accessed usingthe Glyphs property For more information about changing glyphs see Custom Glyphs

You can change the images to be used for various checkbox states in WinForms FlexGrid using the code below

チェックオン状態のセル(32)に2つの状態のチェックボックスを設定します c1flexGrid1SetCellCheck(3 2 CheckEnumChecked)

C

チェックオン状態のセル(32)に2つの状態のチェックボックスを設定しますc1flexGrid1SetCellCheck(3 2 CheckEnumChecked)

VBNET

チェックボックスをセルの右中央に揃えますc1flexGrid1Cols[Verified]ImageAlign = ImageAlignEnumRightCenter

C

チェックボックスをセルの右中央に揃えますc1flexGrid1Cols(Verified)ImageAlign = ImageAlignEnumRightCenter

VBNET

カスタム画像をチェックボックスアイコンとして設定します Image imgChk = new Bitmap(ResourcesImagescheckedpng) Image imgUnchk = new Bitmap(ResourcesImagesuncheckedpng) Image imgGray = new Bitmap(ResourcesImagesnullpng) c1flexGrid1Glyphs[GlyphEnumChecked] = imgChk c1flexGrid1Glyphs[GlyphEnumUnchecked] = imgUnchk c1flexGrid1Glyphs[GlyphEnumGrayed] = imgGray

C

カスタム画像をチェックボックスアイコンとして設定します Dim imgChk As Image = New Bitmap(ResourcesImagescheckedpng) Dim imgUnchk As Image = New Bitmap(ResourcesImagesuncheckedpng)

VBNET

FlexGrid for WinForms

49 Copyright copy GrapeCity Inc All rights reserved

Use Three State CheckboxIn addition to usual two state checkbox FlexGrid lets you create three state checkbox as well The simplest way ofenabling the third state is through the CheckEnum While a Boolean checkbox togglesbetween CheckEnumChecked and CheckEnumUnchecked states the three states of a three state checkbox arerepresented by CheckEnumTSChecked CheckEnumTSUnchecked and CheckEnumTSGrayed However in thiscase by default user can not go back to null after switching to checked or unchecked state once In order to cycle acheckbox between three states you need to handle the ValidateEdit event

Use the code below to create a three state checkbox in the WinForms FlexGrid

Dim imgGray As Image = New Bitmap(ResourcesImagesnullpng) c1flexGrid1Glyphs(GlyphEnumChecked) = imgChk c1flexGrid1Glyphs(GlyphEnumUnchecked) = imgUnchk c1flexGrid1Glyphs(GlyphEnumGrayed) = imgGray

private void c1FlexGrid1_ValidateEdit(object sender ValidateEditEventArgs e) if (c1FlexGrid1Cols[eCol]Name == Done) eCancel = true if (c1FlexGrid1[eRow eCol]Equals(false)) c1FlexGrid1[eRow eCol] = true else if (c1FlexGrid1[eRow eCol]Equals(true)) c1FlexGrid1[eRow eCol] = DBNullValue else if (c1FlexGrid1[eRow eCol]Equals(DBNullValue)) c1FlexGrid1[eRow eCol] = false

C

Private Sub c1FlexGrid1_ValidateEdit(ByVal sender As Object ByVal e As ValidateEditEventArgs) If c1FlexGrid1Cols(eCol)Name Is Done Then eCancel = True

If c1FlexGrid1(eRow eCol)Equals(False) Then c1FlexGrid1(eRow eCol) = True ElseIf c1FlexGrid1(eRow eCol)Equals(True) Then c1FlexGrid1(eRow eCol) = DBNullValue ElseIf c1FlexGrid1(eRow eCol)Equals(DBNullValue) Then c1FlexGrid1(eRow eCol) = False End If End IfEnd Sub

VBNET

数値

FlexGrid by default uses the numeric editor to edit the numeric data that is when the data type is set to any of the numeric types such as Int and Decimal Thisbehavior of FlexGrid is controlled by the EditOptions property which provides various editing options through the EditFlags enumeration One of the flagsprovided is UseNumericEditor As the default value of EditOptions property is All UseNumericEditor flag is always ON and hence grid automatically enablesthe numeric editor while editing the numeric data You can access the EditOptions property at design time as well as through code

FlexGrid for WinForms

50 Copyright copy GrapeCity Inc All rights reserved

Numeric Editor Numeric Editor with Format = C0 Numeric Editor with Spin Button Numeric Editor with Calculator

At Design Time

To enable or disable the numeric editor at design time you can access the EditOptions property from the Properties window

At Run Time

At run-time you need to set the UseNumericEditor flag On in the EditOptions property Use the code below to set EditOptions property in the WinFormsFlexGrid

Format Numeric CellTo format the data in a numeric cell FlexGrid provides the Format property of Column as well as Row object In case of the formats that support decimal valuessuch as numeric currency and exponential FlexGrid displays values up to two decimal places by default However you can specify the number of decimals todisplay by appending the value of Format property with that number For instance in order to display values up to three decimal places in a Number type cellyou specify value of Format property as N3 or n3

Note This property doesnt have any effect on the stored value but only on how value is displayed at the run time You can access the formatted valueof a cell using GetDataDisplay(Int32 Int32) method of the C1FlexGrid class

You can set the Format property at design time as well as through code Following table lists the commonly used formats for numeric cells

Format Value Description

Number N or n Specifies the formatting for simple numeric values

Currency C or c Specifies the formatting for monetary values

Exponential or Scientific E or e Specifies the formatting for values using scientific notations

Percentage P or p Specifies the formatting for percentage values

Custom User-defined Takes the value of format string from user

A custom string might require handling in the code

At Design Time

1 In design view click on the FlexGrid smart tag to open the C1FlexGrid Tasks menu2 Click the Column Tasks option and navigate to Format String property3 Click ellipsis button to open the Format String dialog

すべてのフラグをオンに設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsAll

UseNumericEditorフラグのみを設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsUseNumericEditor

C

すべてのフラグをオンに設定しますc1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsAll

UseNumericEditorフラグのみを設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsUseNumericEditor

VBNET

FlexGrid for WinForms

51 Copyright copy GrapeCity Inc All rights reserved

4 Select the required format from the list box on left say Currency5 Set the format specific properties on the right hand side of the dialog Decimal places in this case

At Run Time

To specify the format of a particular numeric type column set the Format property to any of the above mentioned values In this example we have set theformat of column 3 as currency without decimals

Following code shows how to set the format of a WinForms FlexGrid column

Input using Spin ButtonTo create a numeric editor which uses a spin button for input you need to assign instance of an external control such as NumericUpDown to the Editorproperty

Use the code below to create a numeric editor with spin button in the WinForms FlexGrid

Input using CalculatorTo allow user to give input using a calculator in a numeric editor you can use the C1NumericEdit control of C1Input library as an editor So just add thereference to C1WinC1Input and assign an instance of C1NumericEdit control to the Editor property For more information about using an external controlas editor see Custom Editors

To create a numeric editor with calculator use the code below

小数点なしの通貨形式を設定します c1FlexGrid1Cols[3]Format = C0

C

小数点なしの通貨形式を設定しますc1FlexGrid1Cols(3)Format = C0

VBNET

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols[2]Editor = new NumericUpDown()

C

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols(2)Editor = New NumericUpDown()

VBNET

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols[2]Editor = new C1NumericEdit()ShowUpDownButtons=false

C

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols(2)Editor = New C1NumericEdit() With ShowUpDownButtons = False

VBNET

日付

FlexGrid by default uses the Date editor for all the Date and DateTime type of data The Date editor consists of adropdown which opens a calendar when clicked and user can select the desired date by navigating through it Usercan also change the date month or year by simply selecting the corresponding part in the editor and pressing the upand down arrow keys

FlexGrid for WinForms

52 Copyright copy GrapeCity Inc All rights reserved

Default Date Editor Date Editor Without Calendar Date Editor with Spin Button

Use the code below to create a Date editor in a WinForms FlexGrid column

Input without Displaying CalendarAs mentioned earlier in FlexGrid a DateTime type cell automatically displays a dropdown calendar to receive theinput from user However in order to get a date input from user without displaying a calendar you can set a maskusing the EditMask property and then validate the input value using the ValidateEdit event

Following code demonstrates how to create a Date editor without calendar in WinForms FlexGrid

For more information about cell masks and validation see topics Mask and Validation respectively Another way ofhiding the calendar is to get user input using the spin buttons

Input using Spin ButtonBelow code shows how to create Date editor with spin button

To display spin buttons in a Date editor use the SetupEditor event to convert the editor into DateTimePicker and setits ShowUpDown property to true

Set the data type property to DateTime c1FlexGrid1Cols[1]DataType = typeof(DateTime)

C

Set the data type property to DateTimec1FlexGrid1Cols(1)DataType = GetType(Date)

VBNET

Set a mask on column c1flexGrid1Cols[3]EditMask = 00000000

C

Set a mask on columnc1flexGrid1Cols(3)EditMask = 00000000

VBNET

private void C1flexGrid1_SetupEditor(object sender RowColEventArgs e)

C

FlexGrid for WinForms

53 Copyright copy GrapeCity Inc All rights reserved

Set Date FormatTo set the format in a Date type column you need to set the Format property of the Column object

Following table lists the pre-defined formats

Format Value Example

Short Date d 11192003

Long Date D Friday November 19 2003

Short Time t 1215 AM

Long Time T 121530 AM

You can also create a custom format using the various custom format specifiers supported in the Net framework Fordetails see Custom date and time format strings on Microsoft website

Use the following code to create a custom date format in WinForms FlexGrid column

if (c1flexGrid1Cols[eCol]Name == DOB) Cast FlexGrids current cell editor var dateEditor = c1flexGrid1Editor as DateTimePicker

Show UpDown button (replacing the drop-down button for calendar) dateEditorShowUpDown = true

Private Sub C1flexGrid1_SetupEditor(ByVal sender As Object ByVal e As RowColEventArgs) If c1flexGrid1Cols(eCol)Name Is DOB Then Cast FlexGrids current cell editor Dim dateEditor = TryCast(c1flexGrid1Editor DateTimePicker)

Show UpDown button (replacing the drop-down button for calendar) dateEditorShowUpDown = True End IfEnd Sub

VBNET

Set a pre-defined format c1FlexGrid1Cols[DOB]Format = d Set a custom format c1FlexGrid1Cols[OrderDate]Format = ddMMyyyy

C

Set a pre-defined format c1FlexGrid1Cols(DOB)Format = d

Set a custom format c1FlexGrid1Cols(OrderDate)Format = ddMMyyyy

VBNET

FlexGrid for WinForms

54 Copyright copy GrapeCity Inc All rights reserved

Display Country-specific Date FormatAlthough abovementioned formats are the most commonly used date formats but there are cultures which preferusing their specific calendar and date formats in some cases such as Japan You can display those specific calendarsand date formats by using OwnerDrawCell event of the C1FlexGrid class and the SystemGlobalization namespaceThe namespace provides various classes to define culture related information including calendars and date formatsFor instance to display Japanese calendar and Japanese date format you can leveragethe SystemGlobalizationJapaneseCalendar class Similarly you can also display other calendars such as GregorianHebrew Hijri and Korean

Set the country specific date format in WinForms FlexGrid using the code below

Set MinMax DateTo set a range of valid values you can use the DateTimePicker control as editor and set its MinDate and MaxDate

c1flexGrid1Cols[DOB]Format = ddMMyyyy c1flexGrid1DrawMode = DrawModeEnumOwnerDraw c1flexGrid1OwnerDrawCell += C1flexGrid1_OwnerDrawCell private void C1flexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if (c1flexGrid1Cols[eCol]DataType == typeof(DateTime) ampamp eRow gt= c1flexGrid1RowsFixed) eText = DateTimeParse(eText)ToString(yyyy年MM月dd日(dddd) c)

C

C1FlexGrid1Cols(DOB)Format = ddMMyyyy C1FlexGrid1DrawMode = DrawModeEnumOwnerDraw

AddHandler C1FlexGrid1OwnerDrawCell AddressOf C1flexGrid1_OwnerDrawCell

Private Sub C1flexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If C1FlexGrid1Cols(eCol)DataType = GetType(DateTime) AndAlso eRow gt= C1FlexGrid1RowsFixed Then eText = DateTimeParse(eText)ToString(yyyy年MM月dd日(dddd) c) End If End Sub

VBNET

FlexGrid for WinForms

55 Copyright copy GrapeCity Inc All rights reserved

property

Use the code below to set a range of valid dates in WinForms FlexGrid

DateTimePicker dateTimePicker = new DateTimePicker() dateTimePickerFormat = DateTimePickerFormatShort

Sets Max and Min dates dateTimePickerMinDate = new DateTime(2015 05 01) dateTimePickerMaxDate = DateTimeToday

Assigns DateTimePicker control as editor for FirstOrderDate(date) column c1flexGrid1Cols[FirstOrderDate]Editor = dateTimePicker

C

Dim dateTimePicker As DateTimePicker = New DateTimePicker() dateTimePickerFormat = DateTimePickerFormat[Short]

Sets Max and Min dates dateTimePickerMinDate = New DateTime(2015 05 01) dateTimePickerMaxDate = DateToday

Assigns DateTimePicker control as editor for FirstOrderDate(date) column c1flexGrid1Cols(FirstOrderDate)Editor = dateTimePicker

VBNET

コンボボックス

ComboBox cell is a common way of providing the user with a well-defined list of possible values in the form of a drop-down list FlexGrid providesthis multi-option editor in various forms such as dropdown list dropdown combo ellipsis button or a textbox with ellipsis button

Default ComboBox Multi-column ComboBox ComboBox with custom BackColor ComboBox with Images

Display Dropdown List or ComboIn FlexGrid you can create a dropdown list by creating a string containing all the choices separated by pipe characters (for exampleTrue|False|Dont know) and assign it to the ComboList property of Row or Column object This causes the grid to display a drop-down buttonnext to the cell The user can click the dropdown button (or press F2) to display the list of choices available for that cell

Another common situation is where cells have a list of common values but users should be allowed to type a custom value as well This can beaccomplished with drop-down combos a combination of text box and drop-down list In FlexGrid you can create combos by starting the choicelist with a pipe character (for example |True|False|Dont know) and then assign it to the ComboList property

Following code shows how to create a dropdown list or combo editor in the WinForms FlexGrid

FlexGrid for WinForms

56 Copyright copy GrapeCity Inc All rights reserved

The ComboList property can also be set using the Combo List dialog at design time To access the Combo List dialog

1 Open the Column Tasks menu for column for which editor is to be set2 Go to the Combo List option and click the ellipsis button on the right hand side of the field3 Combo List dialog opens where you can specify the option values each in a new line4 You can also choose whether you want to display these values as a Dropdown List or Dropdown Combo Note that it also lets you create

cell button using Ellipsis Button or Textbox amp Ellipsis Button option

Display Multi-column ComboBoxIn FlexGrid you can also display multiple columns in a ComboBox using the MultiColumnDictionary class This class implementsthe IC1MultiColumnDictionary interface and has multiple overloads These overloads let you specify the data source object the key columncolumns that are to be displayed in multiple columns and the column to be displayed when ComboBox is closed

Display a multi-column combobox in a WinForms FlexGrid column using the code below

Note that the above code uses the data source object dt to supply data to the grid You can set up the data source as per your requirements

ドロップダウンリストとしてCustomerIDを割り当てますc1flexGrid1Cols[CustomerID]ComboList = AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

ドロップダウンコンボボックスとしてCustomerIDを割り当てパイプ文字|でリストを開始します c1flexGrid1Cols[CustomerID]ComboList = |AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

C

ドロップダウンリストとしてCustomerIDを割り当てますc1flexGrid1Cols(CustomerID)ComboList = AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

ドロップダウンコンボボックスとしてCustomerIDを割り当てパイプ文字|でリストを開始します c1flexGrid1Cols(CustomerID)ComboList = |AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

VBNET

string[] columnRange = new string[] City Country c1FlexGrid1Cols[City]DataMap = new MultiColumnDictionary(dt City columnRange 0)

C

Dim columnRange = New String() City Countryc1FlexGrid1Cols(City)DataMap = New MultiColumnDictionary(dt City columnRange 0)

VBNET

DataTable dt = new DataTable() dtColumnsAdd(CustomerID typeof(int)) dtColumnsAdd(ContactName typeof(string)) dtColumnsAdd(Designation typeof(string)) dtColumnsAdd(City typeof(string)) dtColumnsAdd(Country typeof(object))

サンプルデータ

C

FlexGrid for WinForms

57 Copyright copy GrapeCity Inc All rights reserved

Set Mapped Data in the ComboBoxTo set a ComboBox having display values different from the actual values you need to use the C1ComboBox as editor and leverageits ItemsDisplayMember and ItemsValueMember properties For instance the example below uses country names as display values while actualvalue is the dialing code of the corresponding country

Following code shows how to set the mapped data in combobox column of the WinForms FlexGrid

dtRowsAdd(1 Maria Anders Sales Representative Madrid Spain ) dtRowsAdd(2 Ana Trujillo Sales Associate Monterrey Mexico ) dtRowsAdd(3 Antonio Moreno Owner Dublin Ireland) dtRowsAdd(4 Thomas Hardy Sales Representative Bristol UK) dtRowsAdd(5 Patricio Simpson Marketing Manager Munich Germany) dtRowsAdd(6 Paolo Accorti Sales Representative Barcelona Spain) dtRowsAdd(7 Martine Ranceacute Owner Puebla Mexico) dtRowsAdd(8 Elizabeth Brown Marketing Manager London UK) dtRowsAdd(9 Jaime Yorres Order Administrator Vienna Austria) dtRowsAdd(10 Yvonne Moncada Marketing Manager Mexico Mexico) dtRowsAdd(11 Helen Bennett OwnerMarketing Cork Ireland) dtRowsAdd(12 Sergio Gutieacuterrezy Order Administrator Sao Paulo Brazil)

c1FlexGrid1DataSource = dt

Dim dt As DataTable = New DataTable()dtColumnsAdd(CustomerID GetType(Integer))dtColumnsAdd(ContactName GetType(String))dtColumnsAdd(Designation GetType(String))dtColumnsAdd(Country GetType(Object))dtColumnsAdd(City GetType(String))

サンプルデータdtRowsAdd(1 Maria Anders Sales Representative Spain Madrid)dtRowsAdd(2 Ana Trujillo Sales Associate Mexico Monterrey)dtRowsAdd(3 Antonio Moreno Owner Ireland Dublin)dtRowsAdd(4 Thomas Hardy Sales Representative UK Bristol)dtRowsAdd(5 Patricio Simpson Marketing Manager Germany Munich)dtRowsAdd(6 Paolo Accorti Sales Representative Spain Barcelona)dtRowsAdd(7 Martine Ranceacute Owner Mexico Puebla)dtRowsAdd(8 Elizabeth Brown Marketing Manager UK London)dtRowsAdd(9 Jaime Yorres Order Administrator Austria Vienna)dtRowsAdd(10 Yvonne Moncada Marketing Manager Mexico Mexico)dtRowsAdd(11 Helen Bennett OwnerMarketing Ireland Cork)dtRowsAdd(12 Sergio Gutieacuterrezy Order Administrator Brazil Sao Paulo)c1FlexGrid1DataSource = dt

VBNET

private void Form1_Load(object sender EventArgs e) 顧客データを取得します Customers = GetCustomers()

FlexGridにデータを入力します c1FlexGrid1DataSource = Customers

国とその国コードのコレクションを作成します ObservableCollectionltCountrygt countries = new ObservableCollectionltCountrygt() countriesAdd(new Country(1 USA)) countriesAdd(new Country(91 India)) countriesAdd(new Country(7 Russia))

C

FlexGrid for WinForms

58 Copyright copy GrapeCity Inc All rights reserved

Set ComboBox DimensionsTo set the height and width of combo box dropdown you need to assign an instance of ComboBox as an editor and then setthe DropDownHeight and DropDownWidth property of that instance

countriesAdd(new Country(54 Argentina)) countriesAdd(new Country(81 Japan)) countriesAdd(new Country(380 Ukraine)) countriesAdd(new Country(98 Iran)) countriesAdd(new Country(45 Denmark)) countriesAdd(new Country(84 Vietnam)) countriesAdd(new Country(49 Germany)) BindingSource countryBS = new BindingSource() countryBSDataSource = countries

C1Comboboxコントロールをインスタンス化して設定します C1ComboBox countryCodeCombo = new C1ComboBox() countryCodeComboItemsDataSource = countryBS

region Mapped Data using C1Combobox

国コードと国名をマッピングするためにプロパティを設定します countryCodeComboItemsDisplayMember = CountryName countryCodeComboItemsValueMember = CountryCode countryCodeComboTextDetached = true countryCodeComboTranslateValue = true

C1ComboboxをDiallingCode列のエディタとして設定します c1FlexGrid1Cols[DiallingCode]Editor = countryCodeCombo endregion

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) 顧客データを取得します Customers = GetCustomers()

FlexGridにデータを入力します c1FlexGrid1DataSource = Customers

国とその国コードのコレクションを作成します Dim countries As ObservableCollection(Of Country) = New ObservableCollection(Of Country)() countriesAdd(New Country(1 USA)) countriesAdd(New Country(91 India)) countriesAdd(New Country(7 Russia)) countriesAdd(New Country(54 Argentina)) countriesAdd(New Country(81 Japan)) countriesAdd(New Country(380 Ukraine)) countriesAdd(New Country(98 Iran)) countriesAdd(New Country(45 Denmark)) countriesAdd(New Country(84 Vietnam)) countriesAdd(New Country(49 Germany)) Dim countryBS As BindingSource = New BindingSource() countryBSDataSource = countries

C1Comboboxコントロールをインスタンス化して設定します Dim countryCodeCombo As C1ComboBox = New C1ComboBox() countryCodeComboItemsDataSource = countryBS

国コードと国名をマッピングするためにプロパティを設定します countryCodeComboItemsDisplayMember = CountryName countryCodeComboItemsValueMember = CountryCode countryCodeComboTextDetached = True countryCodeComboTranslateValue = True

C1ComboboxをDiallingCode列のエディタとして設定します c1FlexGrid1Cols(DiallingCode)Editor = countryCodeComboEnd Sub

VBNET

FlexGrid for WinForms

59 Copyright copy GrapeCity Inc All rights reserved

Use the code below to specify the height and width of the combobox to be displayed in the WinForms FlexGrid

Change Background Color or Font ColorTo change the background color or font color of the ComboBox list create an instance of ComboBox to assign it as editor Then set the BackColorand ForeColor property of that instance

Customize combobox in the WinForms FlexGrid by using the code below

Display Image in the ListTo display images in the ComboBox list you need to use the C1ComboBox as an editor and leverage its ItemsImageList property This property isof type ImageList class that acts as a container for the images which are stored in its Images collection First access the images stored in theproject resources through the ResourceManagerGetResourceSet method and create a collection of mapping between images and itscorresponding names The collection acts as a data source for ComboBox Now create an instance of the ImageList class add images to itsImages collection from data source and assign that instance of ImageList class to the ItemsImageList property to render images in the ComboBoxlist

Following code shows how to display images in the combobox lists of WinForms FlexGrid

ComboBox cb = (ComboBox)c1flexGrid1Editor cbDropDownWidth = 250 cbDropDownHeight = 200

C

Dim cb As ComboBox = CType(c1flexGrid1Editor ComboBox) cbDropDownWidth = 250 cbDropDownHeight = 200

VBNET

ComboBox comboBox = new ComboBox() comboBoxBackColor = ColorBlack comboBoxForeColor = ColorWhite

C

Dim comboBox As ComboBox = New ComboBox() comboBoxBackColor = ColorBlack comboBoxForeColor = ColorWhite

VBNET

コンボボックスに画像を入力します var itemsSource = new ListltFlaggt() ImageList imgFlag = new ImageList() imgFlagImagesClear() var rsrSet = ResourcesResourceManagerGetResourceSet(CultureInfoCurrentCulture true true)

foreach(DictionaryEntry entry in rsrSet) var img = entryValue as Image itemsSourceAdd(new Flag(entryKeyToString() img)) itemsSourceSort(new CompareFlag())

foreach (Flag entry in itemsSource) imgFlagImagesAdd(entryCountryName entryCountryFlag)

countryComboItemsImageList = imgFlag

C

FlexGrid for WinForms

60 Copyright copy GrapeCity Inc All rights reserved

Set Number of Displayed ItemsTo set the number of items to be displayed in a combo box you can use ComboBoxMaxDropDownItems property

Use the code below to limit the number of items to be displayed in combobox list of the WinForms FlexGrid

Sort the ComboBox ListTo sort the items in the ComboBox dropdown list you can use the C1ComboBox as editor and call the Sort method to sort the dropdown itemsgetting displayed in the ComboBox

To display sorted items in comboboxlist of the WinForms FlexGrid use the code below

countryComboItemMode = ComboItemModeHtmlPattern countryComboHtmlPattern = ltdiv ltdiv style=padding0pxgtltimg src=CountryName style=padding-right14pxgtCountryNameltdivgt

コンボボックスに画像を入力します Dim itemsSource = New List(Of Flag)()Dim imgFlag As ImageList = New ImageList()imgFlagImagesClear()Dim rsrSet = ResourcesResourceManagerGetResourceSet(CultureInfoCurrentCulture True True)

For Each entry As DictionaryEntry In rsrSet Dim img = TryCast(entryValue Image) itemsSourceAdd(New Flag(entryKeyToString() img))Next

itemsSourceSort(New CompareFlag())

For Each entry In itemsSource imgFlagImagesAdd(entryCountryName entryCountryFlag)Next

countryComboItemsImageList = imgFlagcountryComboItemMode = ComboItemModeHtmlPatterncountryComboHtmlPattern = ltdiv ltdiv style=padding0pxgtltimg src=CountryName style=padding-right14pxgtCountryNameltdivgt

VBNET

コンボボックスのドロップダウンに表示する国の数を設定します countryComboMaxDropDownItems = 10

C

コンボボックスのドロップダウンに表示する国の数を設定しますcountryComboMaxDropDownItems = 10

VBNET

C1ComboBox countryCombo = new C1ComboBox() countryComboDropDownStyle = DropDownStyleDropDownList Listltstringgt countries = new Listltstringgt USA Canada India Russia Japan Germany countriesSort() countryComboItemsDataSource = countries

C1ComboboxをCountry列のエディタとして設定します c1FlexGrid1Cols[Country]Editor = countryCombo

C

FlexGrid for WinForms

61 Copyright copy GrapeCity Inc All rights reserved

Get the Selected IndexTo get the selected index or value of the selected item you can use the SelectedIndex property or SelectedItem property of the ComboBoxEditorclass The example below uses the ComboCloseUp event to show a message box displaying the selected index and the selected item

Use the code below to fetch the index and value of selected item in combobox list of the WinForms FlexGrid

Dim countryCombo As C1ComboBox = New C1ComboBox() countryComboDropDownStyle = DropDownStyleDropDownList Dim countries As List(Of String) = New List(Of String) From USA Canada India Russia Japan Germany countriesSort() countryComboItemsDataSource = countries

C1ComboboxをCountry列のエディタとして設定します c1FlexGrid1Cols(Country)Editor = countryCombo

VBNET

private void C1FlexGrid1_ComboCloseUp(object sender C1WinC1FlexGridRowColEventArgs e) MessageBoxShow(Selected Index + c1FlexGrid1ComboBoxEditorSelectedIndex + n + Selected Item + c1FlexGrid1ComboBoxEditorSelectedItem)

C

Private Sub C1FlexGrid1_ComboCloseUp(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) MessageBoxShow(Selected Index amp c1FlexGrid1ComboBoxEditorSelectedIndex amp vbLf amp Selected Item + c1FlexGrid1ComboBoxEditorSelectedItem)End Sub

VBNET

マスク

Mask editor refers to pre-defined templates for getting input from users which also automatically validates the userinput as it is typed Mask strings have two types of characters literal characters and template characters While literalcharacters are the ones which become part of the input the template characters serve as placeholders for charactersbelonging to specific categories (for example digits or alphabets) For example the code below assigns a (999) 999-9999 editing mask to the first column which holds phone numbers Here special characters such as braces (()) andhyphen (-) are the literals and the digit 9 is a placeholder that stands for any digit

FlexGrid for WinForms

62 Copyright copy GrapeCity Inc All rights reserved

The FlexGrid control supports masked editing through the EditMask property which can be used with regular textfields and with drop-down combo fields To apply different masks within the same column you can trap the BeforEditevent and set the EditMask property to appropriate value

You can also set the EditMask property at design time using the Input Mask dialog You can access the dialog byclicking the ellipsis button against Edit Mask field in Column Tasks menu It also means that the Edit Mask field isspecific to the column selected at that time

Note that when the EditMask property is set to a non-empty string the grid uses the masked editor even if thecolumn contains DateTime values Usually grid uses the built-in Date editor to edit DateTime type cells

電話番号の編集マスクを設定します c1FlexGrid1Cols(1)EditMask = (999) 999-9999

C

電話番号の編集マスクを設定します c1FlexGrid1Cols(1)EditMask = (999) 999-9999

VBNET

マップリスト

Mapped lists refer to the mapping of data stored in the grid to the values visible to the user Such mapping is oftenused to display user-friendly values when actual data stored in the grid is either encoded or difficult to understand bythe user For instance in an employee record table it would be more convenient for administrative executive to seenames of the employees while database stores the employee IDs

FlexGrid for WinForms

63 Copyright copy GrapeCity Inc All rights reserved

Display Data MappingIn FlexGrid data mapping can be achieved by using the DataMap property This property contains reference to anIDictionary object that establishes mapping between database values and values to be displayed in the gridHashTable ListDictionary and SortedList are some examples of IDictionary objects which provide valid data maps

Following code demonstrates how to display the data mapped list in the WinForms FlexGrid

There is a difference in how HashTable ListDictionary and SortedList classes order the items So when these tables areused with editable columns the order of items rendering in the mapped list also differs depending upon the keys andclass used to create the list

Note that the keys in the data map must be of the same type as the cells being edited For example if a columncontains short integers (Int16) then any data maps associated with the column should have short integer keys

Display Image MappingTo display image mapping in a FlexGrid column you need to set the ImageMap property of Row or Column object toan IDictionary object that establishes mapping between images and the corresponding text values For example if acolumn contains country names you can use this property to display the corresponding flags You can controlwhether to show only images or images with text by using the ImageAndText property of the object

Create an image mapping in the WinForms FlexGrid using the code below

データマップを作成しますListDictionary customerNames = new ListDictionary()customerNamesAdd(AJK18F Sam Anders)customerNamesAdd(BBK21D Daneil)customerNamesAdd(AEF25N Henry Hussain)customerNamesAdd(BZD42S Owen Romanov)customerNamesAdd(AKC16G Serena Nguyen)

データマップをflexgrid列に割り当てますc1flexGrid1Cols[Name]DataMap = customerNames

C

データマップを作成しますDim customerNames As ListDictionary = New ListDictionary()customerNamesAdd(AJK18F Sam Anders)customerNamesAdd(BBK21D Daneil)customerNamesAdd(AEF25N Henry Hussain)customerNamesAdd(BZD42S Owen Romanov)customerNamesAdd(AKC16G Serena Nguyen)

データマップをflexgrid列に割り当てますc1flexGrid1Cols(Name)DataMap = customerNames

VBNET

Hashtable ht = new Hashtable() foreach (Row row in c1flexGrid1Rows) htAdd(row[CustomerID] LoadImage(row[Photo] as byte[])) ImageMapをPhoto列に割り当てます c1flexGrid1Cols[Photo]ImageMap = ht

C

FlexGrid for WinForms

64 Copyright copy GrapeCity Inc All rights reserved

アスペクト比を維持しながら画像をセルに合わせます c1flexGrid1Cols[Photo]ImageAlign = ImageAlignEnumScale c1flexGrid1Cols[Photo]Width = 80

Dim ht As Hashtable = New Hashtable()

For Each row As Row In c1flexGrid1Rows htAdd(row(CustomerID) LoadImage(TryCast(row(Photo) Byte()))) Next

ImageMapをPhoto列に割り当てます c1flexGrid1Cols(Photo)ImageMap = ht

アスペクト比を維持しながら画像をセルに合わせます c1flexGrid1Cols(Photo)ImageAlign = ImageAlignEnumScale c1flexGrid1Cols(Photo)Width = 80

VBNET

セルボタン

Cell button editor refers to a cell with an ellipsis button This editor comes to use when you need to get an operationdone or open a dialog on a button click Such dialogs generally contain multiple different options or settings for a userto choose from

Default Cell Button Cell Button with Text Cell Button with Custom Image

Display Cell ButtonIn FlexGrid you can display a cell button by setting the ComboList property to an ellipsis character You can alsouse a pipe character before ellipsis button to display an ellipsis with text box to let user enter his inputThe CellButtonClick event is fired when user clicks the cell button You can capture this event to implement thedesired operation or display a dialog of your choice

By default the cell button gets displayed when cell enters the edit mode However you can set the ShowButtonsproperty to Always to display the cell button even in non-edit mode

Use the code below to display cell button in a WinForms FlexGrid column

Mark列のComboListプロパティを設定してセルボタンを表示するようにします c1flexGrid1Cols[Mark]ComboList = セルボタンを常に表示できるようにします c1flexGrid1Cols[Mark]ShowButtons = ShowButtonsEnumAlways

エンドユーザーがセルボタンをクリックしたときに処理します c1flexGrid1CellButtonClick += C1flexGrid1_CellButtonClick

C

Mark列のComboListプロパティを設定してセルボタンを表示するようにしますc1flexGrid1Cols(Mark)ComboList =

VBNET

FlexGrid for WinForms

65 Copyright copy GrapeCity Inc All rights reserved

The ComboList property can also be set using the Combo List dialog at design time To access the Combo List dialog

1 Open the Column Tasks menu for column for which editor is to be set2 Go to the Combo List option and click the ellipsis button on the right hand side of the field3 Combo List dialog opens where you can specify the option values each in a new line4 You can also choose whether you want to display these values as an Ellipsis Button or Textbox amp Ellipsis

Button Note that it also gives you options to create Dropdown List and Dropdown Combo

The example below demonstrates change in back color and fore color of the current row on click of the cell buttonSimilarly you can perform the desired operation in the CellButtonClick event

セルボタンを常に表示できるようにしますc1flexGrid1Cols(Mark)ShowButtons = ShowButtonsEnumAlways

エンドユーザーがセルボタンをクリックしたときに処理しますc1flexGrid1CellButtonClick += C1flexGrid1_CellButtonClick

private void C1flexGrid1_CellButtonClick(object sender RowColEventArgs e) 次のコードは色を変更して現在の行をマークします if (c1flexGrid1Rows[eRow]StyleDisplayBackColor == ColorFromName(Window)) c1flexGrid1Rows[eRow]StyleNewBackColor = ColorGreen c1flexGrid1Rows[eRow]StyleNewForeColor = ColorWhite c1flexGrid1Rows[eRow]StyleNewBackColor = ColorFromName(Window) c1flexGrid1Rows[eRow]StyleNewForeColor = ColorFromName(WindowText)

C

FlexGrid for WinForms

66 Copyright copy GrapeCity Inc All rights reserved

Change Image of Cell ButtonBy default cell button displays an ellipsis However you can change the image of cell button usingthe CellButtonImage property

Set the image of cell button in the WinForms FlexGrid as shown in the code below

Private Sub C1flexGrid1_CellButtonClick(ByVal sender As Object ByVal e As RowColEventArgs) 次のコードは色を変更して現在の行をマークします If c1flexGrid1Rows(eRow)StyleDisplayBackColor Is ColorFromName(Window) Then c1flexGrid1Rows(eRow)StyleNewBackColor = ColorGreen c1flexGrid1Rows(eRow)StyleNewForeColor = ColorWhite End If

If True Then c1flexGrid1Rows(eRow)StyleNewBackColor = ColorFromName(Window) c1flexGrid1Rows(eRow)StyleNewForeColor = ColorFromName(WindowText) End IfEnd Sub

VBNET

CellButtonImageプロパティを設定してセルボタンの画像を定義しますImage imgCellBtn = new Bitmap(ResourcesImagesbuttonpng)c1flexGrid1CellButtonImage = imgCellBtn

C

CellButtonImageプロパティを設定してセルボタンの画像を定義しますDim imgCellBtn As Image = New Bitmap(ResourcesImagesbuttonpng)c1flexGrid1CellButtonImage = imgCellBtn

VBNET

検証

Data validation lets you control the data that a user can enter into a column cell There are various ways in which adata can be validated such as restricting invalid input keys showing the error or warning information or revert thevalue to original on getting an invalid input from the user

FlexGrid for WinForms

67 Copyright copy GrapeCity Inc All rights reserved

To implement validations such as specifying the range of acceptable values or defining the minimum string length ofinput FlexGrid provides EditorValidation property of the Column class The property is oftype ValidationRuleCollection class which consists of pre-defined rules for implementing enhanced data validation inFlexGrid columns For instance the sample code below demonstrates StringLength and Required validation rulesapplied to the Customer column using the EditorValidation property

Refer the code below to know how to add validation rules in WinForms FlexGrid columns

private void SetupGridColumns() var customerNameColumn = _flexCols[CustomerName] customerNameColumnCaption = Customer customerNameColumnEditorValidationAdd(new RequiredRule()) customerNameColumnEditorValidationAdd(new StringLengthRule() MinimumLength = 2 ) var customerIDColumn = _flexCols[CustomerID] customerIDColumnVisible = false var frequencyColumn = _flexCols[Frequency] frequencyColumnFormat = 0 frequencyColumnAllowEditing = false var ageColumn = _flexCols[Age] ageColumnEditorValidationAdd(new RequiredRule()) ageColumnEditorValidationAdd(new RangeRule() Minimum = 10 Maximum = 90 )

C

FlexGrid for WinForms

68 Copyright copy GrapeCity Inc All rights reserved

Another way of applying validation is by capturing the ValidateEdit event and checking the value of EditorTextproperty If value obtained is invalid set the Cancel parameter to true to keep the grid in editing mode until userenters a valid value Such validation can be used in scenarios such as setting the range of valid values validating thecurrent cell value based on another cell value For example the below sample code validates input into a currencycolumn to ensure that values entered are between 1000 and 10000

Use ValidateEdit event to check for valid values during edit mode of the WinForms FlexGrid cell as shown in the codebelow

Private Sub SetupGridColumns() Dim customerNameColumn = _flexCols(CustomerName) customerNameColumnCaption = Customer customerNameColumnEditorValidationAdd(New RequiredRule()) customerNameColumnEditorValidationAdd(New StringLengthRule() With MinimumLength = 2 ) Dim customerIDColumn = _flexCols(CustomerID) customerIDColumnVisible = False Dim frequencyColumn = _flexCols(Frequency) frequencyColumnFormat = 0 frequencyColumnAllowEditing = False Dim ageColumn = _flexCols(Age) ageColumnEditorValidationAdd(New RequiredRule()) ageColumnEditorValidationAdd(New RangeRule() With Minimum = 10 Maximum = 90 )End Sub

VBNET

private void _flex_ValidateEdit( object sender ValidateEditEventArgs e) 金額を検証します if (_flexCols[eCol]DataType == typeof(Decimal)) try Decimal dec = DecimalParse(_flexEditorText) if ( dec lt 1000 || dec gt 10000 ) MessageBoxShow(Value must be between 1000 and 10000) eCancel = true catch MessageBoxShow(Value not recognized as a Currency) eCancel = true

C

Private Sub _flex_ValidateEdit(ByVal sender As Object ByVal e As ValidateEditEventArgs)

VBNET

FlexGrid for WinForms

69 Copyright copy GrapeCity Inc All rights reserved

金額を検証します If _flexCols(eCol)DataType Is GetType(Decimal) Then

Try Dim dec As Decimal = DecimalParse(_flexEditorText)

If dec lt 1000 OrElse dec gt 10000 Then MessageBoxShow(Value must be between 1000 and 10000) eCancel = True End If

Catch MessageBoxShow(Value not recognized as a Currency) eCancel = True End Try End IfEnd Sub

データ注釈

Data annotation means adding meaningful metadata tags to the classes and other objects making it easier to bridgethe gap between models and views by performing data validation and displaying appropriate messages to the endusers For example you may use data annotations to specify how items should be formatted what their captionsshould be whether they should be editable or not

FlexGrid supports multiple data annotation attributes used for customizing data classes displaying data from sourceand setting validation rules To use the attributes in your project you need to add a reference to theSystemComponentModelDataAnnotations assembly and then add the attributes to your data objects in the code

Note The C1FlexGrid supports the annotations defined in NET 4SystemComponentModelDataAnnotations should be version 4000 or higher

Listed below are some of the major annotation attributes that are supported in FlexGrid control Cilck herefor complete list of DataAnnotation attributes

FlexGrid for WinForms

70 Copyright copy GrapeCity Inc All rights reserved

Attribute Name Functionality in FlexGrid

Association Specifies that an entity member represents a data relationship such as a foreignkey relationship

Display Provides a general-purpose attribute that lets you specify localizable strings fortypes and members of entity partial classes

DisplayFormat Specifies how data fields are displayed and formatted by ASPNET Dynamic Data

DisplayColumn Specifies the column that is displayed in the referred table as a foreign-keycolumn

Editable Indicates whether a data field is editable

Key Denotes one or more properties that uniquely identify an entity

Validation

RequiredAttributeStringLengthAttributeRangeAttributeRegularExpressionAttributeMinLengthAttributeMetaDataAttributeMaxLengthAttributeEmailAddressAttributeCompareAttributeDataTypeAttribute

The data annotation validation attributes are used as validation rules in FlexGridoperations

The following code example shows how data annotation feature works in WinForms FlexGrid control

自動生成されたCustomerName列ヘッダに「Customer」と表示されます この列には少なくとも2つの記号の長さが最小の空でない文字列も必要です[Display(Name = Customer)][Required][StringLength(intMaxValue MinimumLength = 2)]

public string CustomerName get set 自動生成されたCustomerID列は非表示になります[Display(AutoGenerateField = false)]public int CustomerID get set

自動生成された「Frequency」列にはパーセンテージで書式設定された値が表示されます また編集を許可しません[DisplayFormat(DataFormatString = 0)][Editable(false)]public double Frequency get set

自動生成された「Age」列は事前定義された範囲の値を許可します[Required][Range(10 90)]public int Age get set サンプルデータを作成しますpublic static BindingListltDatagt GetSampleData(int cnt) var list = new BindingListltDatagt() var rnd = new Random()

C

FlexGrid for WinForms

71 Copyright copy GrapeCity Inc All rights reserved

for (int i = 0 i lt cnt i++) var item = new Data() itemCustomerName = _firstNames[rndNext(0 _firstNamesLength)] + + _lastNames[rndNext(0 _lastNamesLength)] itemCustomerID = i itemFrequency = rndNextDouble() itemAge = rndNext(10 91) listAdd(item) return list

自動生成されたCustomerName列ヘッダに「Customer」と表示されます この列には少なくとも2つの記号の長さが最小の空でない文字列も必要です ltDisplay(Name=Customer)gt ltRequiredgt ltStringLength(IntegerMaxValue MinimumLength=2)gt Public Property CustomerName As String 自動生成されたCustomerID列は非表示になります ltDisplay(AutoGenerateField=False)gt Public Property CustomerID As Integer 自動生成された「Frequency」列にはパーセンテージで書式設定された値が表示されます また編集を許可しません ltDisplayFormat(DataFormatString=0)gt ltEditable(False)gt Public Property Frequency As Double 自動生成された「Age」列は事前定義された範囲の値を許可します ltRequiredgt ltRange(10 90)gt Public Property Age As Integer

サンプルデータを作成します Public Shared Function GetSampleData(ByVal cnt As Integer) As BindingList(Of Data) Dim list = New BindingList(Of Data)() Dim rnd = New Random()

For i As Integer = 0 To cnt - 1 Dim item = New Data() itemCustomerName = _firstNames(rnd[Next](0 _firstNamesLength)) amp + _lastNames(rnd[Next](0 _lastNamesLength)) itemCustomerID = i itemFrequency = rndNextDouble() itemAge = rnd[Next](10 91) listAdd(item) Next

Return list End Function

VBNET

スパークライン

Sparklines are the miniature charts visually representing a series of values to show trends such as periodic fluctuationsor to highlight maximum or minimum values of the data series In grids sparklines are specially useful as they easily fitin a single cell and can help identify the data patterns at a glance

FlexGrid for WinForms

72 Copyright copy GrapeCity Inc All rights reserved

FlexGrid for WinForms lets you display sparklines in columns by setting ShowSparkline property of the Column classto true You can also set the type of sparkline using SparklineType property of the Sparkline class FlexGrid supportsthree types of sparklines which are

Line Similar to line chart line sparkline indicates change in values over a period of time with the help of a lineColumn Similar to column charts column sparkline uses vertical columns to demonstrate pattern acrossdifferent categoriesWinLoss Similar to column sparkline winloss sparkline uses vertical columns to represent values However itdoes not indicate the magnitude and is generally used to indicate the binary data

To display the data markers on sparkline you can set the ShowMarkers property to true The Sparkline class alsoprovides properties to highlight the first last highest lowest or negative data points by displaying them in differentformat You can even style the sparklines using the Styles property

Below code shows how to add sparkline to the WinForms FlexGrid columns

WinLossSparklineを表示するようにプロパティを設定します c1FlexGrid1Cols[2]ShowSparkline = true c1FlexGrid1Cols[2]SparklineSparklineType = SparklineTypeWinLoss c1FlexGrid1Cols[2]SparklineStylesSeriesColor = ColorGreen c1FlexGrid1Cols[2]SparklineShowNegative = true

C

WinLossSparklineを表示するようにプロパティを設定します c1FlexGrid1Cols(2)ShowSparkline = True c1FlexGrid1Cols(2)SparklineSparklineType = SparklineTypeWinLoss c1FlexGrid1Cols(2)SparklineStylesSeriesColor = ColorGreen c1FlexGrid1Cols(2)SparklineShowNegative = True

VBNET

ヘッダとフッタ

Column header refers to the fixed rows on the top of the grid which contains a caption string sort glyph etc

In FlexGrid by default the top row with zero index is allocated for the column header However you can span the header to other rows aswell by specifying them as fixed To set more than one rows as fixed you need to set the Fixed property of RowCollection class to an integergreater than 1

FlexGrid for WinForms

73 Copyright copy GrapeCity Inc All rights reserved

Set Header TextFlexGrid when in bound mode reads the field names from the data source and renders them as column header text However youcan explicitly set Caption property of the Row class to overwrite field name string from the data source In case of unbound grid as well theCaption property specifies the header text Note that this property sets the value of cells in the default header row at zero index To setvalue in the other fixed row cells you need to use the usual value allocation ways of FlexGrid For more information on how to set cellvalues see Set Value in Cell

Specify the header rows and set the header text in WinForms FlexGrid using the code below

Merge Column HeaderFlexGrid provides the AllowMerging property for Row object which specifies whether it is allowed to merge cells in a particular row (in thiscase the header row) or not Once you have allowed merging in the header row set either AllowMerging or AllowMergingFixed propertyof C1FlexGrid class to FixedOnly Availability of these two properties in the FlexGrid control offers you more flexibility to implement multiplelogics related to merging For more information on merging cells see Merge

Use the code below to merge column headers in the WinForms FlexGrid

Wrap Column Header Text

2つの行を列ヘッダ行として設定しますc1FlexGrid1RowsFixed = 2 最初の列のヘッダとサブヘッダを設定しますc1FlexGrid1Cols [1] Caption = Column Header 1c1FlexGrid1 [11] = Column Sub-header 1

C

2つの行を列ヘッダー行として設定します c1FlexGrid1RowsFixed = 2

最初の列のヘッダとサブヘッダを設定します c1FlexGrid1Cols(1)Caption = Column Header 1 c1FlexGrid1(1 1) = Column Sub-header 1

VBNET

ヘッダ行でのマージを許可しますc1FlexGrid1Rows[0]AllowMerging = true

グリッドのAllowMergingまたはAllowMergingFixedプロパティを設定して固定行のみを結合します c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

ヘッダ行でのマージを許可しますc1FlexGrid1Rows(0)AllowMerging = True

グリッドのAllowMergingまたはAllowMergingFixedプロパティを設定して固定行のみを結合します c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

FlexGrid for WinForms

74 Copyright copy GrapeCity Inc All rights reserved

To wrap the text in column header access the CellStyle item Fixed of the CellStyleCollection class and set its WordWrap property totrue Note that to view the wrapped text properly you need to adjust the row height or just call the AutoSizeRow() method to automaticallyresize the row according to the text length

Use the code below to wrap header text of the WinForms FlexGrid columns

Style Column HeaderTo style the column header you can access the CellStyle item Fixed of the CellStyleCollection class and set various styling relatedproperties for same such as Font ForeColor and TextEffect

Customize column header of the WinForms FlexGrid using the code below

Set Column FooterColumn Footer refers to the last row of the grid which displays additional information about the whole column Most common use ofcolumn footer is to show the summary of column data

In FlexGrid you can create the column footer by using Footers property of the C1FlexGrid class FlexGrid lets you choose whether toscroll the footer along with rows or keep it fixed at the bottom of the grid by using Fixed property of the Footers class This class alsoprovides the Descriptions property which accesses the FooterDescription collection to set the additional information such as Caption Todisplay aggregate result in the column footer through various aggregate functions you must access the AggregateDefinition collection

列のキャプションを設定しますc1FlexGrid1Cols[3]Caption = Large Text for Column Header Text Wrapping

行の高さを設定しますc1FlexGrid1Rows[0]Height = 50

固定の行と列のワードラップを設定しますc1FlexGrid1Styles[Fixed]WordWrap = true

C

列のキャプションを設定しますc1FlexGrid1Cols(3)Caption = Large Text for Column Header Text Wrapping

行の高さを設定しますc1FlexGrid1Rows(0)Height = 50

固定の行と列のワードラップを設定しますc1FlexGrid1Styles(Fixed)WordWrap = True

VBNET

ヘッダテキストのフォントを設定しますc1FlexGrid1Styles[Fixed]Font = new Font(Tahoma 10 FontStyleBold) ヘッダテキストの前色を設定しますc1FlexGrid1Styles[Fixed]ForeColor = ColorAqua ヘッダーテキストの背景色を設定しますc1FlexGrid1Styles[Fixed]BackColor = ColorBlue

ヘッダテキストにテキスト効果を適用しますc1FlexGrid1Styles[Fixed]TextEffect = C1WinC1FlexGridTextEffectEnumRaised

C

ヘッダテキストのフォントを設定します c1FlexGrid1Styles(Fixed)Font = New Font(Tahoma 10 FontStyleBold)

ヘッダテキストの前色を設定します c1FlexGrid1Styles(Fixed)ForeColor = ColorAqua

ヘッダーテキストの背景色を設定します c1FlexGrid1Styles(Fixed)BackColor = ColorBlue

ヘッダテキストにテキスト効果を適用します c1FlexGrid1Styles(Fixed)TextEffect = C1WinC1FlexGridTextEffectEnumRaised

VBNET

FlexGrid for WinForms

75 Copyright copy GrapeCity Inc All rights reserved

using Aggregates property of the FooterDescription class Aggregate functions can be specified using the Aggregate property whichaccepts values from AggregateEnum enumeration

Following code shows how to add a column footer in the WinForms FlexGrid

列にフッタを追加しますc1FlexGrid1FootersDescriptionsAdd(new C1WinC1FlexGridFooterDescription() Caption = Total ) フッタに集計を適用しますc1FlexGrid1FootersDescriptions[0]AggregatesAdd(new C1WinC1FlexGridAggregateDefinition() Column = 4 Aggregate = C1WinC1FlexGridAggregateEnumSum )

C

列にフッタを追加しますc1FlexGrid1FootersDescriptionsAdd(New C1WinC1FlexGridFooterDescription() With Caption = Total )

フッタに集計を適用しますc1FlexGrid1FootersDescriptions(0)AggregatesAdd(New C1WinC1FlexGridAggregateDefinition() With Column = 4 Aggregate = C1WinC1FlexGridAggregateEnumSum )

VBNET

サイズ変更

Set Column WidthFlexGrid provides the DefaultSize property of ColumnCollection class to set the column width across the grid You canalso specify the width of a particular column by setting the Width property of the Column class Default value ofWidth property is -1 which indicates that the column is taking width specified by the DefaultSize property The Widthproperty is also available at design time through the C1FlexGrid Column Editor For more information on columneditor see Editors

Use the code below to set the default width of a column of the WinForms FlexGrid

Auto-adjust Column WidthTo adjust the column width according to the text length FlexGrid provides the AutoSizeCol() and AutoSizeCols()methods While AutoSizeCol() method automatically adjusts width of the specified column the AutoSizeCols()method is used for cell ranges

Following code shows how you can auto adjust the column widths according to the text length in the WinFormsFlexGrid

すべての列のデフォルト幅を設定しますc1FlexGrid1ColsDefaultSize = 110最初の列の幅を設定しますc1FlexGrid1Cols [1] Width = 30

C

すべての列のデフォルト幅を設定します c1FlexGrid1ColsDefaultSize = 110最初の列の幅を設定します c1FlexGrid1Cols(1)Width = 30

VBNET

FlexGrid for WinForms

76 Copyright copy GrapeCity Inc All rights reserved

Set MinMax Column WidthFlexGrid allows you to set bounds to the column width by using the MinSize and MaxSize propertiesof ColumnCollection This feature is especially useful in scenarios such as when AllowResizing property is set to trueor while using the AutoSizeCol or AutoSizeCols method

Specify the bounds of column width in the WinForms FlexGrid using the code below

Star SizingStar sizing refers to proportional sizing of grid columns to occupy the available space so that layout of grid remainssame even on resizing For instance consider a grid with 5 columns whose star sizes are specified as 3 2 and In this case first fourth and fifth column always take the same width and grid allocates thrice the width of firstcolumn to the second and twice the width to third column

テキストの長さに応じて最初の列の幅を自動調整しますc1FlexGrid1AutoSizeCol(1) 列の幅を1番目から4番目まで自動調整しますc1FlexGrid1AutoSizeCols(1 4 2)

すべての列の幅を自動調整します c1FlexGrid1AutoSizeCols()

C

テキストの長さに応じて最初の列の幅を自動調整しますc1FlexGrid1AutoSizeCol(1)

列の幅を1番目から4番目まで自動調整しますc1FlexGrid1AutoSizeCols(1 4 2)

すべての列の幅を自動調整します c1FlexGrid1AutoSizeCols()

VBNET

列コレクションの最小幅を設定します c1FlexGrid1ColsMinSize = 20 列コレクションの最大幅を設定します c1FlexGrid1ColsMaxSize = 60

C

列コレクションの最小幅を設定します c1FlexGrid1ColsMinSize = 20

列コレクションの最大幅を設定します c1FlexGrid1ColsMaxSize = 60

VBNET

FlexGrid for WinForms

77 Copyright copy GrapeCity Inc All rights reserved

FlexGrid provides the StarWidth property of Column class to specify the star sizes of columns To restrict the widthsfrom getting too narrow or too wide you can set the MinWidth and MaxWidth properties These properties are alsoavailable through the C1FlexGrid Column Editor For more information on column editor see Editors

Set star sizing or proportional sizing in the WinForms FlexGrid columns using the code below

列のスターサイズを設定しますc1FlexGrid1Cols[1]StarWidth = c1FlexGrid1Cols[2]StarWidth = 3c1FlexGrid1Cols[3]StarWidth = 2c1FlexGrid1Cols[4]StarWidth = c1FlexGrid1Cols[5]StarWidth =

列が狭くなりすぎないようにMinWidthプロパティを設定しますc1FlexGrid1Cols[1]MinWidth = 50

C

列のスターサイズを設定しますc1FlexGrid1Cols(1)StarWidth = c1FlexGrid1Cols(2)StarWidth = 3c1FlexGrid1Cols(3)StarWidth = 2c1FlexGrid1Cols(4)StarWidth = c1FlexGrid1Cols(5)StarWidth =

列が狭くなりすぎないようにMinWidthプロパティを設定しますc1FlexGrid1Cols(1)MinWidth = 50

VBNET

FlexGrid for WinForms

78 Copyright copy GrapeCity Inc All rights reserved

A grid control is a collection of rows and columns Columns generally contain a particular type of information through out while rows are used to recorddifferent types of information about a particular item

In FlexGrid the collection of rows is represented by the RowCollection class which can be accessed through Rows property of the C1FlexGrid class Thissection discusses the various operations that can be performed on rows

Topic Snapshot Content

Basic Operations Discusses about how to perform basic row operations

Set Row CountAdd RowDelete RowInsert RowSet Data TypeSet Fixed RowSet Frozen Row

User Interaction Discusses about operations that can be performed by the end-user at run time

Allow AddingAllow DeletingAllow DraggingAllow FreezingAllow Resizing

Header Discusses about how to set row header and perform other related operations

Set Header TextMerge Row HeaderWrap Row Header TextStyle Row Header

Row Detail Discusses how to display additional information using row detail feature

In-form EditingHierarchical ViewCustom Row Details

Sizing Discusses about various aspects of row sizing

Set Row HeightAuto-adjust Row HeightSet MinMax Row Height

基本操作

This topic discusses various basic operations which can be performed on a row

Set Row CountWhen grid is bound to a data source the number of rows is determined by the number of records available in thedata source However in the case of unbound mode you can set any integer value in Count property ofthe RowCollection class to set the number of rows to be displayed in the grid

Use the code below to set row count in the WinForms FlexGrid

Set row count c1FlexGrid1RowsCount = 15

C

VBNET

FlexGrid for WinForms

79 Copyright copy GrapeCity Inc All rights reserved

Add RowFlexGrid provides various ways to add a new row at runtime You can either use Add method of the RowCollectionclass or AddItem method of the C1FlexGrid class to add a new record In the unbound mode you can also incrementthe value of Count property to add new rows Note that all these ways add rows towards the end of the grid To inserta row at a specific location see Insert Row Also note that an exception is thrown if a new row is added to a boundgrid using Count property

Add a row to WinForms FlexGrid using any of these approaches shown in the code below

Delete RowTo delete a particular row from the grid you can use Remove method of the RowCollection class and specify the rowyou want to delete as its parameter The RowCollection class also provides RemoveRange method which allows you

Set row countc1FlexGrid1RowsCount = 15

Approach1 Use the RowCollectionAdd method to add row C1WinC1FlexGridRow r r = c1FlexGrid1RowsAdd() Set data r[1] = New Row 2

Approach2 Use AddItem method to add row and set data c1FlexGrid1AddItem( + t + New Row 1) Approach3 Use the RowCollectionCount property to add row c1FlexGrid1RowsCount += 1 Set data c1FlexGrid1[c1FlexGrid1RowsCount - 1 1] = New Row 3

C

Approach1 Use the RowCollectionAdd method to add row Dim r As C1WinC1FlexGridRow r = c1FlexGrid1RowsAdd()

Set data r(1) = New Row 2

Approach2 Use AddItem method to add row and set data c1FlexGrid1AddItem( amp vbTab amp New Row 1)

Approach3 Use the RowCollectionCount property to add row c1FlexGrid1RowsCount += 1

Set data c1FlexGrid1(c1FlexGrid1RowsCount - 1 1) = New Row 3

VBNET

FlexGrid for WinForms

80 Copyright copy GrapeCity Inc All rights reserved

to remove a range of rows using a single call Similarly you can also use RemoveItem method of the C1FlexGridclass to remove a specific row In the unbound grid you can reduce the number of rows by changing the value ofCount property

Following code gives different approaches to delete row from the WinForms FlexGrid

Insert RowTo insert a row in FlexGrid at a specific location you can use Insert method of the RowCollection class which lets youspecify the position where rows are to be inserted You can also insert multiple rows in the grid by usingthe InsertRange method

Below code demonstrates how to insert a row at a particular position in the WinForms FlexGrid

Approach1 Remove second row using RowCollectionRemove methodc1FlexGrid1RowsRemove(2)

Approach1 Remove second row using the RemoveItem methodc1FlexGrid1RemoveItem(2)

Approach3 Remove 3 rows starting from second using the RemoveRange methodc1FlexGrid1RowsRemoveRange(2 3) Approach4 Remove last row using the RowCollectionCount property c1FlexGrid1RowsCount -= 1

C

Approach1 Remove second row using RowCollectionRemove method c1FlexGrid1RowsRemove(2)

Approach1 Remove second row using the RemoveItem method c1FlexGrid1RemoveItem(2)

Approach3 Remove 3 rows starting from second using the RemoveRange method c1FlexGrid1RowsRemoveRange(2 3)

Approach4 Remove last row using the RowCollectionCount property c1FlexGrid1RowsCount -= 1

VBNET

C1WinC1FlexGridRow r Approach1 Use the Insert method to insert row at second position r = c1FlexGrid1RowsInsert(2) r[1] = Inserted row Approach2

C

FlexGrid for WinForms

81 Copyright copy GrapeCity Inc All rights reserved

Set Data TypeIn case of a bound FlexGrid data type of each bound column is automatically picked from the data source dependingon the data However in the case of unbound mode you can set the data type of rows or columns by specifyingthe DataType property of Row or Column class respectively Note that when data type is set for both rows andcolumns column settings take preference over row settings

Use the code below to set data type of a WinForms FlexGrid row

Set Fixed RowFixed rows refer to the rows with non-editable cells which are always visible on top of the grid even when user scrollsdown the grid In FlexGrid fixed rows can be set using Fixed property of the RowCollection class This propertyaccepts an integer value that specifies the number of rows to be fixed

Set fixed rows in the WinForms FlexGrid using the code below

Set Frozen RowFrozen rows similar to fixed rows are non-scrollable but can be edited by the user In FlexGrid frozen rows can be set

Use the InsertRange method to add three rows at second position c1FlexGrid1RowsInsertRange(2 3)

Dim r As C1WinC1FlexGridRow Approach1 Use the Insert method to insert row at second position r = c1FlexGrid1RowsInsert(2) r(1) = Inserted row

Approach2 Use the InsertRange method to add three rows at second position c1FlexGrid1RowsInsertRange(2 3)

VBNET

C1WinC1FlexGridRow r r = c1FlexGrid1RowsAdd() rDataType = typeof(int)

C

Dim r As C1WinC1FlexGridRow r = c1FlexGrid1RowsAdd() rDataType = GetType(int)

VBNET

Set three rows as fixed c1FlexGrid1RowsFixed = 3

C

Set three rows as fixedc1FlexGrid1RowsFixed = 3

VBNET

FlexGrid for WinForms

82 Copyright copy GrapeCity Inc All rights reserved

by using Frozen property provided by the RowCollection class

Use the code below to set frozen rows in the WinForms FlexGrid

Set first two rows as frozen c1FlexGrid1RowsFrozen = 2

C

Set first two rows as frozen c1FlexGrid1RowsFrozen = 2

VBNET

ユーザー操作

This topic discusses how you can let end-users interact with the FlexGrid rows

Allow AddingBy default FlexGrid does not allow end-user to add new row to the grid To provide an option to add rows at runtimeyou can set AllowAddNew property of the C1FlexGrid class to true FlexGrid also provides a design-time optionEnable Adding Rows in C1FlexGrid Tasks menu to allow adding new row by the end-user For more information ontask menus see Tasks Menus Moreover you can also set watermark text to be displayed in the new row templatethrough NewRowWatermark property

Use the code below to allow users to add rows in WinForms FlexGrid at run-time

Allow user to add rows c1FlexGrid1AllowAddNew = true Set watermark in the template new row c1FlexGrid1NewRowWatermark = Add new row

C

Allow user to add rows c1FlexGrid1AllowAddNew = True

Set watermark in the template new row

VBNET

FlexGrid for WinForms

83 Copyright copy GrapeCity Inc All rights reserved

Allow DeletingFlexGrid by default does not allow end-user to delete rows from the grid However if your application requires youcan let the end-user delete the selected rows through Delete key by setting AllowDelete property to true You canalso enable row deletion by checking ON the Enable Deleting Rows checkbox on the C1FlexGrid Tasks menu

Following code shows how to allow users to delete rows from WinForms FlexGrid at run-time

Allow DraggingFlexGrid by default does not allow user to rearrange rows by dragging However you can change this behavior inunbound grid by using the FlexGridAllowDragging property and RowAllowDragging property To enable dragging ofgrid rows you can set the FlexGridAllowDragging property to either Rows or Both This property accepts the valuesfrom AllowDraggingEnum You can also disable dragging of a particular row by setting the RowAllowDraggingproperty to false

Note As moving a row is not allowed in bound mode the bound grid throws an exception on dragging arow To implement dragging in bound mode see the blog Drag and Drop Rows in C1Flexgrid

Let users drag the rows in an unbound WinForms FlexGrid at run-time by using the code below

Allow FreezingTo allow end user to freeze the rows at runtime you can use AllowFreezing property of the C1FlexGrid class whichaccepts values from AllowFreezingEnum When this property is set to Rows or Both a lock sign appears when mouseis hovered over the edge of header row End-user can click and drag the lock sign to freeze the rows

Use the code below to allow your users to freeze the WinForms FlexGrid rows at run-time

c1FlexGrid1NewRowWatermark = Add new row

Allow user to delete rowsc1FlexGrid1AllowDelete = true

C

Allow user to delete rowsc1FlexGrid1AllowDelete = True

VBNET

Allow dragging of all rows across the grid c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumRows Disable dragging of a particular row c1FlexGrid1Rows[3]AllowDragging = false

C

Allow dragging of all rows across the grid c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumRows

Disable dragging of a particular row c1FlexGrid1Rows(3)AllowDragging = False

VBNET

FlexGrid for WinForms

84 Copyright copy GrapeCity Inc All rights reserved

Allow ResizingBy default FlexGrid does not give option to resize the rows To change this behavior you can use AllowResizingproperty of the C1FlexGrid class This property accepts values from the AllowResizingEnum enumerationwhich enables end-user to change size of columns rows or both The enumeration also gives you options touniformly resize the rows columns or both that is if you resize one of the columns or rows the grid automaticallyresizes rest of the columns or rows as well FlexGrid also provides RowAllowResizing property which is Boolean typeand lets you enable or disable resizing of a particular row

Following code shows how to allow users to resize the WinForms FlexGrid rows at run-time

Allow freezing of rows at runtimec1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumRows

C

Allow freezing of rows at runtimec1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumRows

VBNET

Allow user to resize rows c1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumRows Stop user from resizing second row c1FlexGrid1Rows[2]AllowResizing = false

C

Allow user to resize rows c1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumRows

Stop user from resizing second row c1FlexGrid1Rows(2)AllowResizing = False

VBNET

ヘッダ

Row header refers to the fixed rows on the left hand side of the grid which may or may not contain the caption string

In FlexGrid by default the left most column with zero index is allocated for the row header However you can span theheader to other columns as well by specifying them as fixed To set more than one column as fixed you need toset the Fixed property of ColumnCollection class to an integer greater than 1

FlexGrid for WinForms

85 Copyright copy GrapeCity Inc All rights reserved

Set Header TextTo set the row header text you can set Caption property of the Row class Note that this property sets the value of cellsin the default header column at zero index To set value in the other fixed column cells you need to use the usual valueallocation ways of FlexGrid For more information on how to set cell values see Set Value in Cell

Specify the header column and set the header text in WinForms FlexGrid using the code below

Merge Row HeaderFlexGrid provides AllowMerging property of the Column class which specifies whether it is allowed to merge cells in aparticular column (in this case the header column) or not Once you have allowed merging in the header columnset either AllowMerging or AllowMergingFixed property of the C1FlexGrid class to FixedOnly Availability of these twoproperties in the FlexGrid control offers you more flexibility to implement multiple logics related to merging For moreinformation on merging cells see Merge

Set header for first rowc1FlexGrid1Rows[1]Caption = Row 1

Set header for all rowsfor (int i = c1FlexGrid1RowsFixed i lt c1FlexGrid1RowsCount i++) c1FlexGrid1[i 0] = Row + iToString()

Set column widthc1FlexGrid1Cols[0]Width = 85

C

Set header for first row c1FlexGrid1Rows(1)Caption = Row 1

Set header for all rows For i As Integer = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 c1FlexGrid1(i 0) = Row amp iToString() Next

Set column width c1FlexGrid1Cols(0)Width = 85

VBNET

FlexGrid for WinForms

86 Copyright copy GrapeCity Inc All rights reserved

Use the code below to merge row headers in the WinForms FlexGrid

Wrap Row Header TextTo wrap the text in row header access the CellStyle item Fixed of the CellStyleCollection class and set its WordWrapproperty to true Note that to view the wrapped text properly you need to adjust height of FlexGrid rows or just callthe AutoSizeRow() method to automatically resize the rows according to the length of text

Use the code below to wrap header text of the WinForms FlexGrid rows

Style Row HeaderTo style the row header you can access the CellStyle item Fixed of the CellStyleCollection class and set variousstyling related properties for same such as Font ForeColor and TextEffect

Allow merging on the header columnc1FlexGrid1Cols[0]AllowMerging = true

Set AllowMerging or AllowMergingFixed property of the grid to merge fixed rowcolumns only c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

Allow merging on the header columnc1FlexGrid1Cols(0)AllowMerging = True

Set AllowMerging or AllowMergingFixed property of the grid to merge fixed rowcolumns only c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

Set row captionc1FlexGrid1Rows[3]Caption = Large text to display text wrapping and mergingc1FlexGrid1Rows[4]Caption = Large text to display text wrapping and merging Set row heightc1FlexGrid1Rows[3]Height = 35c1FlexGrid1Rows[4]Height = 35

Set word wrapping for fixed rows and columnsc1FlexGrid1Styles[Fixed]WordWrap = true

C

Set row captionc1FlexGrid1Rows(3)Caption = Large text to display text wrapping and mergingc1FlexGrid1Rows(4)Caption = Large text to display text wrapping and merging

Set row heightc1FlexGrid1Rows(3)Height = 35c1FlexGrid1Rows(4)Height = 35

Set word wrapping for fixed rows and columnsc1FlexGrid1Styles(Fixed)WordWrap = True

VBNET

FlexGrid for WinForms

87 Copyright copy GrapeCity Inc All rights reserved

Customize row header of the WinForms FlexGrid using the code below

Set font of the header textc1FlexGrid1Styles[Fixed]Font = new Font(Tahoma 10 FontStyleBold) Set forecolor of the header textc1FlexGrid1Styles[Fixed]ForeColor = ColorPaleVioletRed Set backcolor of the header textc1FlexGrid1Styles[Fixed]BackColor = ColorLemonChiffon Apply text effect on the header textc1FlexGrid1Styles[Fixed]TextEffect = C1WinC1FlexGridTextEffectEnumInset

C

Set font of the header text c1FlexGrid1Styles(Fixed)Font = New Font(Tahoma 10 FontStyleBold)

Set forecolor of the header text c1FlexGrid1Styles(Fixed)ForeColor = ColorPaleVioletRed

Set backcolor of the header text c1FlexGrid1Styles(Fixed)BackColor = ColorLemonChiffon

Apply text effect on the header text c1FlexGrid1Styles(Fixed)TextEffect = C1WinC1FlexGridTextEffectEnumInset

VBNET

行の詳細

Row detail is a feature to provide additional information related to a row or record in the form of another expandablelayer In such case row which is the first layer contains the basic information while the second layer contains the detailedinformation This feature is specially useful when the additional information is too large to be displayed in the availablescreen space or it is not consistent for every record

FlexGrid for WinForms

88 Copyright copy GrapeCity Inc All rights reserved

FlexGrid provides the row detail feature using IC1FlexGridRowDetail interface which is implemented by the detail controls tobe hosted on detail row In addition FlexGrid also provides a separate assembly C1WinC1FlexGridRowDetails452dllto provide template user controls InputPanel and FlexGrid ready to be used in detail row You can add details section toany row in FlexGrid which enables you to group data in a template which is visible optionally This allows users to viewadditional data related to a row by simply selecting the row The grid also provides built-in expand or collapse buttons tocontrol the visibility of data within the expandable row

Some common use case scenarios of row detail feature are

1 In-form editing where an InputPanel control is hosted to get input from the user to fill information in a record2 Hierarchical grid which contains a master grid and a detail grid to show additional information about the record3 Custom row details where any control can be used to create row detail template

Detailed implementation of these scenarios is given in their respective sections below

In-form EditingFlexGrid supports in-form editing by hosting InputPanel control in detail row The InputPanel control contains data fieldswhere user can enter or edit the values like a form Once user finishes editing fields those values get reflected in theselected row

FlexGrid for WinForms

89 Copyright copy GrapeCity Inc All rights reserved

In FlexGrid you can implement in-form editing by adding reference to C1WinC1FlexGridRowDetails452dll and usingthe C1InputPanelRowDetail class which already implements the IC1FlexGridRowDetail interface The instance of this classis then assigned to RowDetailProvider property of the C1FlexGrid class which adds the InputPanel control to detail rowand enables the in-form editing

Hierarchical ViewHierarchical view refers to master-detail model where top level grid is the master grid and nested grid is the detail gridwhich displays additional information about expanded row of the master grid For instance example below demonstratesthe master-detail structure using Customer and Order tables respectively with CustomerID as common data element todefine a relation

flexGridRowDetailProvider = (g r) =gt new C1InputPanelRowDetail()flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected

C

flexGridRowDetailProvider = Function(g r) New C1InputPanelRowDetail()flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected

VBNET

FlexGrid for WinForms

90 Copyright copy GrapeCity Inc All rights reserved

In FlexGrid you can implement hierarchical grid by adding reference to C1WinC1FlexGridRowDetails452dll and usingthe C1FlexGridRowDetail class which already implements the IC1FlexGridRowDetail interface The instance of this class isthen assigned to RowDetailProvider property of the C1FlexGrid class to nest another grid in the detail row which enablesthe hierarchical grid interface

private void FlexGrid_Load(object sender EventArgs e) string conn = UtilGetConnectionString() var ds = new DataSet() string[] tables = Customers OrdersSplit() foreach (string tableName in tables) UtilFillTable(ds tableName conn) Defining relation between master and detail grid dsRelationsAdd(Customers_Orders dsTables[Customers]Columns[CustomerID] dsTables[Orders]Columns[CustomerID]) flexGridDataSource = ds flexGridDataMember = Customers flexGridRowDetailProvider = (g r) =gt new C1FlexGridRowDetail() flexGridAreRowDetailsFrozen = false

C

Private Sub FlexGrid_Load(ByVal sender As Object ByVal e As EventArgs) Dim conn As String = UtilGetConnectionString() Dim ds = New DataSet() Dim tables As String() = Customers OrdersSplit(c)

For Each tableName As String In tables UtilFillTable(ds tableName conn) Next Defining relation between master and detail grid dsRelationsAdd(Customers_Orders dsTables(Customers)Columns(CustomerID) dsTables(Orders)Columns(CustomerID))

VBNET

FlexGrid for WinForms

91 Copyright copy GrapeCity Inc All rights reserved

Custom Row DetailsIn addition to the InputPanel and FlexGrid control you can also host a custom control in the detail row of a grid Forinstance in the example below a text label control is attached to the row to enlist the additional information withoutaffecting the dimensions of the grid

To implement the custom row details in FlexGrid you need to create a user control which implementsthe IC1FlexGridRowDetail interface For instance here we have created a class named CustomRowDetail which representsthe text label control to be hosted in the detail row You then need to assign an object of this class to RowDetailProviderproperty of the C1FlexGrid class to enable the custom control to display additional information in the detail row

flexGridDataSource = ds flexGridDataMember = Customers flexGridRowDetailProvider = Function(g r) New C1FlexGridRowDetail() flexGridAreRowDetailsFrozen = False End Sub

private void CustomSample_Load(object sender EventArgs e) flexGridDataSource = DemoDataSource(Employees) flexGridRowDetailProvider = (g r) =gt new CustomRowDetail() flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected flexGridCols[Notes]Visible = false

Custom row detail class which shows label with notes about employee public class CustomRowDetail C1Label IC1FlexGridRowDetail Used to setup control before showing the FlexGrid detail control void IC1FlexGridRowDetailSetup(C1FlexGrid parentGrid int rowIndex) var bs = new BindingSource(parentGridDataSource parentGridDataMember) bsPosition = parentGridRows[rowIndex]DataIndex DataField = Notes DataSource = bs

C

FlexGrid for WinForms

92 Copyright copy GrapeCity Inc All rights reserved

Used to update size of the FlexGrid detail control void IC1FlexGridRowDetailUpdateSize(C1FlexGrid parentGrid int rowIndex Size proposedSize) var srSz = parentGridScrollableRectangleSize var sz = TextRendererMeasureText(Text Font srSz TextFormatFlagsWordBreak) szWidth = MathMax(szWidth srSzWidth) Size = sz

Private Sub CustomSample_Load(ByVal sender As Object ByVal e As EventArgs) flexGridDataSource = DemoDataSource(Employees) flexGridRowDetailProvider = Function(g r) New CustomRowDetail() flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected flexGridCols(Notes)Visible = False End Sub

Custom row detail class which shows label with notes about employee Public Class CustomRowDetail Inherits C1Label Implements IC1FlexGridRowDetail

Used to setup control before showing the FlexGrid detail control Private Sub Setup(ByVal parentGrid As C1FlexGrid ByVal rowIndex As Integer) Dim bs = New BindingSource(parentGridDataSource parentGridDataMember) bsPosition = parentGridRows(rowIndex)DataIndex DataField = Notes DataSource = bs End Sub

Used to update size of the FlexGrid detail control Private Sub UpdateSize(ByVal parentGrid As C1FlexGrid ByVal rowIndex As Integer ByVal proposedSize As Size) Dim srSz = parentGridScrollableRectangleSize Dim sz = TextRendererMeasureText(Text Font srSz TextFormatFlagsWordBreak) szWidth = MathMax(szWidth srSzWidth) Size = sz End Sub End Class

VBNET

サイズ変更

Set Row HeightFlexGrid provides DefaultSize property of the RowCollection class to set row height across the grid You can alsospecify the height of a particular row by setting Height property of the Row class Default value of the Heightproperty is -1 which indicates that the row is taking height specified by the DefaultSize property

Use the code below to set the default height of a row of the WinForms FlexGrid

Set the default size of all rowsc1FlexGrid1RowsDefaultSize = 50

C

FlexGrid for WinForms

93 Copyright copy GrapeCity Inc All rights reserved

Auto-adjust Row HeightTo adjust the row height according to text length and word wrapping options FlexGrid provides the AutoSizeRow()and AutoSizeRows() methods While AutoSizeRow() method automatically adjusts height of the specified row theAutoSizeRows() method is used for cell ranges

Following code shows how you can auto adjust the row height according to the text length in the WinForms FlexGrid

Set MinMax Row HeightFlexGrid allows you to set bounds to the row height by using the MinSize and MaxSize propertiesof the RowCollection class This feature is especially useful in scenarios such as when AllowResizing property is set totrue or while using the AutoSizeRow() or AutoSizeRows() method

Specify the bounds of row height in the WinForms FlexGrid using the code below

Set the height of a particular rowc1FlexGrid1Rows[1]Height = 55

Set the default size of all rowsc1FlexGrid1RowsDefaultSize = 50

Set the height of a particular rowc1FlexGrid1Rows(1)Height = 55

VBNET

Adjust the height of fourth row automaticallyc1FlexGrid1AutoSizeRow(4) Adjust the height of all rows automatically c1FlexGrid1AutoSizeRows() Adjust the height of cell range automaticallyc1FlexGrid1AutoSizeRows(2 4 5 6 10 C1WinC1FlexGridAutoSizeFlagsNone)

C

Adjust the height of fourth row automatically c1FlexGrid1AutoSizeRow(4)

Adjust the height of all rows automatically c1FlexGrid1AutoSizeRows()

Adjust the height of cell range automatically c1FlexGrid1AutoSizeRows(2 4 5 6 10 C1WinC1FlexGridAutoSizeFlagsNone)

VBNET

Set the maximum height of rowc1FlexGrid1RowsMaxSize = 50 Set the minimum height of rowc1FlexGrid1RowsMinSize = 20

C

FlexGrid for WinForms

94 Copyright copy GrapeCity Inc All rights reserved

Set the maximum height of rowc1FlexGrid1RowsMaxSize = 50

Set the minimum height of row c1FlexGrid1RowsMinSize = 20

VBNET

FlexGrid for WinForms

95 Copyright copy GrapeCity Inc All rights reserved

セル

Cell is the smallest unit of a grid Although in most common scenarios we prefer working on row or column levelthere are some operations which are required to be carried out on the cell level Getting setting or removing data arefew to name

Topic Snapshot Content

Basic Operations Discusses how to perform basic operations related to a cell

Set Value in CellSet Values in Cell RangeClear Value from Cell (Range)Set Image in CellDisplay Tooltip in CellRetrieve Cell Values

Cell Format Discusses how to format cell or cell data in various scenarios

Cell ContentCell AppearanceConditional FormattingOwner Drawn Cell

基本操作

Set Value in CellFlexGrid provides two ways to set values in cell You can either use Item property (indexer) or SetData method of the C1FlexGrid class

Use the code below to set a value in the WinForms FlexGrid cell

Set Values in Cell RangeTo set values in a cell range you can either use Data property of the CellRange class or SetData method of the C1FlexGrid class

Following code shows how to set values in a cell range in WinForms FlexGrid

インデックスを使用してデータを設定しますc1FlexGrid1[2 3] = 2nd col 3rd row SetDataメソッドを使用してデータを設定しますc1FlexGrid1SetData(2 4 2nd col 4th row)

C

インデックスを使用してデータを設定します c1FlexGrid1(2 3) = 2nd col 3rd row

SetDataメソッドを使用してデータを設定します c1FlexGrid1SetData(2 4 2nd col 4th row)

VBNET

セル範囲を取得しますC1WinC1FlexGridCellRange cr = c1FlexGrid1GetCellRange(2 3 5 6) 方法1dataプロパティを使用してセル範囲にデータを設定しますcrData = Cell Range

C

FlexGrid for WinForms

96 Copyright copy GrapeCity Inc All rights reserved

Clear Value from Cell (Range)There are two ways by which contents of cell or cell range can be cleared You can either chose to do it programmatically by setting thecontent of cell to an empty string using indexer or SetData method Or you can set the AutoClipboard property to true so that user candelete the values by pressing the Delete key

Below code demonstrates how to allow keyboard operations so that user can clear values from WinForms FlexGrid cells

Set Image in CellTo set image in a cell you can use SetCellImage method of the C1FlexGrid class You can also set an image in a cell range by using Imageproperty of the CellRange class By default text and image both are displayed in the cell However you can choose to display only image bysetting the ImageAndText property to false

Use the code below to set image in a WinForms FlexGrid cell

方法2SetDataメソッドを使用してセル範囲にデータを設定します c1FlexGrid1SetData(cr Cell Range)

セル範囲を取得します Dim cr As C1WinC1FlexGridCellRange = c1FlexGrid1GetCellRange(2 3 5 6)

方法1dataプロパティを使用してセル範囲にデータを設定します crData = Cell Range

方法2SetDataメソッドを使用してセル範囲にデータを設定します c1FlexGrid1SetData(cr Cell Range)

VBNET

ユーザーがDeleteキーを押してセルの内容をクリアするなどのキーボード操作を実行できるようにしますc1FlexGrid1AutoClipboard = true

コードを介して特定のセルのデータをクリアしますc1FlexGrid1SetData(3 4 )

C

ユーザーがDeleteキーを押してセルの内容をクリアするなどのキーボード操作を実行できるようにします c1FlexGrid1AutoClipboard = True

コードを介して特定のセルのデータをクリアします c1FlexGrid1SetData(3 4 )

VBNET

セル(36)に画像を設定しますc1FlexGrid1SetCellImage(3 6 ImageFromFile(masterpng))

C

FlexGrid for WinForms

97 Copyright copy GrapeCity Inc All rights reserved

Display Tooltip in CellTo display partially hidden content of cells as tooltip FlexGrid provides ShowCellLabels property of the C1FlexGrid class You can also showadditional information in the form of a tooltip by using the MouseEnterCell and MouseLeaveCell event

Below code shows how to display a tooltip on a WinForms FlexGrid cell

セル範囲(126)から(146)に画像を設定しますC1WinC1FlexGridCellRange crcr = c1FlexGrid1GetCellRange(12 6 14 6)crImage = ImageFromFile(amexjpg)

テキストなしで画像を表示しますc1FlexGrid1Rows[3]ImageAndText = false

セル(36)に画像を設定します c1FlexGrid1SetCellImage(3 6 ImageFromFile(masterpng))

セル範囲(126)から(146)に画像を設定します Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1GetCellRange(12 6 14 6) crImage = ImageFromFile(amexjpg)

テキストなしで画像を表示します c1FlexGrid1Rows(3)ImageAndText = False

VBNET

private void Form1_Load(object sender EventArgs e) このコードはデータを「c1NWindDataSetEmployees」テーブルにロードします 必要に応じて移動または削除できます thisemployeesTableAdapterFill(thisc1NWindDataSetEmployees) for (int i = c1FlexGrid1RowsFixed i lt c1FlexGrid1RowsCount i++) c1FlexGrid1Rows[i]UserData = Employee + c1FlexGrid1[i 2] + + c1FlexGrid1[i 3] private void C1FlexGrid1_MouseEnterCell(object sender C1WinC1FlexGridRowColEventArgs e) if (eRow gt= c1FlexGrid1RowsFixed) string tip tip = c1FlexGrid1Rows[eRow]UserDataToString() ツールチップを表示します toolTip1SetToolTip(c1FlexGrid1 tip)

private void C1FlexGrid1_MouseLeaveCell(object sender C1WinC1FlexGridRowColEventArgs e) ツールチップを非表示にします toolTip1SetToolTip(c1FlexGrid1 )

C

FlexGrid for WinForms

98 Copyright copy GrapeCity Inc All rights reserved

Retrieve Cell ValuesThere are numerous ways using which you can fetch the value of FlexGrid cells depending on your requirement Below tablediscusses several scenarios such as fetching the raw data or formatted data from a single cell or a cell range

Requirement MethodProperty Usage

Get the raw data Item property (indexer) ExampleCode

var data = c1FlexGrid1[1 1] SystemDiagnosticsDebugWriteLine($Cell data data)

GetData() method ExampleCode

var data1 = c1FlexGrid1GetData(1 1) SystemDiagnosticsDebugWriteLine($Cell data data1)

Get the formatted data GetDataDisplay() method ExampleCode

var data2 = c1FlexGrid1GetDataDisplay(1 1) SystemDiagnosticsDebugWriteLine($Display data data2)

Get values of a cell range Clip property ExampleCode

var data3 = c1FlexGrid1Clip SystemDiagnosticsDebugWriteLine($Clip data data3)

GetCellRange method ExampleCode

var data4 = c1FlexGrid1GetCellRange(1 1) SystemDiagnosticsDebugWriteLine($Cell Range data data4Clip)

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) このコードはデータを「c1NWindDataSetEmployees」テーブルにロードします 必要に応じて移動または削除できます MeemployeesTableAdapterFill(Mec1NWindDataSetEmployees)

For i As Integer = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 c1FlexGrid1Rows(i)UserData = Employee amp c1FlexGrid1(i 2) amp + c1FlexGrid1(i 3) Next End Sub

Private Sub C1FlexGrid1_MouseEnterCell(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) If eRow gt= c1FlexGrid1RowsFixed Then Dim tip As String tip = c1FlexGrid1Rows(eRow)UserDataToString() ツールチップを表示します toolTip1SetToolTip(c1FlexGrid1 tip) End If End Sub

Private Sub C1FlexGrid1_MouseLeaveCell(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) ツールチップを非表示にします toolTip1SetToolTip(c1FlexGrid1 ) End Sub

VBNET

FlexGrid for WinForms

99 Copyright copy GrapeCity Inc All rights reserved

セルの書式設定

Cell ContentTo control how content of the cells is formatted and displayed set the Format property of Row or Column object toformat string similar to the ones that are used with StringFormat property in the NET framework For instance thesample code below formats the third column as Date and fourth column as Currency

FlexGrid also provides design time option to set the Format property through the Format String dialog You canaccess the Format String dialog by clicking Ellipsis button against the Format String field in Column Tasks menu Oryou can also use the Format property in C1FlexGrid Column Editor

短い日付形式を設定しますc1FlexGrid1Cols[3]Format = D 通貨形式を設定しますc1FlexGrid1Cols[4]Format = c

C

短い日付形式を設定しますc1FlexGrid1Cols(3)Format = D

通貨形式を設定しますc1FlexGrid1Cols(4)Format = c

VBNET

FlexGrid for WinForms

100 Copyright copy GrapeCity Inc All rights reserved

Note that Format String dialog is specific to column and changes the Format property of the selected column only

Cell AppearanceFlexGrid provides CellStyle objects to handle the appearance aspects of cells such as alignment font colors bordersand so on The grid has Styles property that holds the collection of styles used to format the grid This collection hassome built-in members that define the appearance of grid elements such as fixed and scrollable cells selection focuscell and so on You can change these styles to modify the appearance of grid

Although changing the built-in styles is the simplest way to change appearance of the grid you can also create yourown custom styles and assign them to cells rows or columns

Use the code below to change appearance of the WinForms FlexGrid cells

組み込みのスタイルをカスタマイズしますCellStyle cs = c1FlexGrid1StylesFocus

C

FlexGrid for WinForms

101 Copyright copy GrapeCity Inc All rights reserved

Conditional FormattingTo format a cell according to its content you need to create a new style and apply it to the cells satisfying a particularcondition using SetCellStyle() method For instance to highlight the values greater than a specified value you canformat the cells containing them using different style

Following code shows how to apply conditional formatting on WinForms FlexGrid cells

csFont = new Font(c1FlexGrid1Font FontStyleBold)csForeColor = ColorGreencsBackColor = ColorRed

カスタムスタイルを作成します CellStyle cs1 = c1FlexGrid1StylesAdd(NewStyle)cs1BackColor = ColorAquacs1ForeColor = ColorBlue

カスタムスタイルを割り当てますc1FlexGrid1Cols[3]Style = cs1

Dim cs As CellStyle = c1FlexGrid1StylesFocus csFont = New Font(c1FlexGrid1Font FontStyleBold) csForeColor = ColorGreen csBackColor = ColorRed

Dim cs1 As CellStyle = c1FlexGrid1StylesAdd(NewStyle) cs1BackColor = ColorAqua cs1ForeColor = ColorBlue

c1FlexGrid1Cols(3)Style = cs1

VBNET

CellStyle cs 大きな値のカスタムスタイルを作成しますcs = c1FlexGrid1StylesAdd(LargeValue)csFont = new Font(Font FontStyleItalic)

C

FlexGrid for WinForms

102 Copyright copy GrapeCity Inc All rights reserved

Owner Drawn CellThe above sections explain how you can customize FlexGrid cells to change the appearance of grid using CellStyleobjects However for further customization of grid cells such as rendering gradient background custom graphics etcyou can use DrawMode property and OwnerDrawCell event of the C1FlexGrid class

The DrawMode property determines whether or not the OwnerDrawCell event is fired The event allows you tooverride every visual aspect of the cell You can change the text and image to be displayed in the cell by setting theeText and eImage parameters in the event handler You can also change the style that is used to display the cell bysetting the eStyle property

Note that you should not modify properties of the Style parameter as it might affect other cells Instead assign a newCellStyle object to the Style parameter For example instead of setting eStyleForeColor = ColorRed assign a wholenew style to the parameter using eStyle = c1FlexGrid1Styles[RedStyle]

You can also use your own drawing code to draw into the cell and even combine your custom code with calls to theeDrawCell method For example you can paint the cell background using GDI calls and then call eDrawCell todisplay the cell borders and content

In the example below WinForms FlexGrid uses a gradient brush to paint the background of the selected cell rangeFirst the sample code sets the DrawMode property to OwnerDraw and then declares a LinearGradientBrushobject

csBackColor = ColorGold

for (int row = 1 row lt c1FlexGrid1RowsCount row++)if (ConvertToDouble(c1FlexGrid1[row 4]) gt 80000)c1FlexGrid1SetCellStyle(row 4 cs)

Dim cs As CellStyle

cs = c1FlexGrid1StylesAdd(LargeValue) csFont = New Font(Font FontStyleItalic) csBackColor = ColorGold

For row As Integer = 1 To c1FlexGrid1RowsCount - 1

If ConvertToDouble(c1FlexGrid1(row 4)) gt 80000 Then c1FlexGrid1SetCellStyle(row 4 cs) End If Next

VBNET

SystemDrawingDrawing2DLinearGradientBrush m_GradientBrushprivate void Form1_Load(object sender EventArgs e)

C

FlexGrid for WinForms

103 Copyright copy GrapeCity Inc All rights reserved

所有者描画セルで使用するブラシ m_GradientBrush = new SystemDrawingDrawing2DLinearGradientBrush(ClientRectangle ColorSteelBlue ColorWhite 45)

グラデーションを追加するにはowner-drawを使用します c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw

private void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) グラデーションブラシを使用して選択したセルの背景を描画します if (c1FlexGrid1SelectionContains(eRow eCol)) 背景を描きますeGraphicsFillRectangle(m_GradientBrush eBounds)

グリッドにコンテンツを描画させますeDrawCell(C1WinC1FlexGridDrawCellFlagsContent)

このセルの描画は完了ですeHandled = true

Private m_GradientBrush As DrawingDrawing2DLinearGradientBrush

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) 所有者描画セルで使用するブラシ m_GradientBrush = New DrawingDrawing2DLinearGradientBrush(ClientRectangle ColorSteelBlue ColorWhite 45)

グラデーションを追加するにはowner-drawを使用します c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDrawEnd Sub

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) グラデーションブラシを使用して選択したセルの背景を描画します If c1FlexGrid1SelectionContains(eRow eCol) Then 背景を描きます eGraphicsFillRectangle(m_GradientBrush eBounds)

グリッドにコンテンツを描画させます eDrawCell(C1WinC1FlexGridDrawCellFlagsContent)

このセルの描画は完了です eHandled = True End IfEnd SubEnd IfEnd Sub

VBNET

FlexGrid for WinForms

104 Copyright copy GrapeCity Inc All rights reserved

グリッド

This section discusses about various operations that can be performed on the grid

Topic Snapshot Content

Basic Operations Discusses about basic operations that can be performed on the grid

Transpose Data in GridDisplay Context Menu

Keyboard Navigation Discusses about supperted keys and their operations in

Non-edit ModeEdit Mode

Improve Performance Provides tips and tricks to get best out of your grid by improving its performance

Use Data VirtualizationUse BeginUpdate and EndUpdate MethodsKeep AutoResize Property to False (default)Assign Styles DynamicallyAvoid Modifying Styles in the OwnerDrawCell EventShow Ellipses in a Single ColumnShow Multi-line Text in a CellRetrieve Data Sorting When Bound to a Data TableSpecify Character Limit for Column

基本操作

This topic discusses about various operations that require handling at the grid level

Transpose Data in GridTransposing data refers to swapping column data and row data In WinForms FlexGrid this can be achieved usingTranspose() method of the C1FlexGrid class as shown in the code below

Note that data can be transposed only in the case of unbound grid Also if grid has sorting applied on a column theTranspose() method removes sorting before transposing the data

Display Context MenuContext menus can be helpful to user as they provide shortcuts for actions that are frequently used In FlexGrid therecan be two scenarios to display a context menu

Display context menu in non-edit modeDisplay context menu in edit mode

Display Context Menu in Non-edit Mode

To display context menu when grid is in non-edit mode you need to create an instance of ContextMenuStrip controladd the menu items and assign the instance to ContextMenuStrip property of the Control class

c1FlexGrid1Transpose()

C

C1FlexGrid1Transpose()

VBNET

FlexGrid for WinForms

105 Copyright copy GrapeCity Inc All rights reserved

Refer to the code below to see how to display a context menu in WinForms FlexGrid in non-edit mode

Display Context Menu in Edit Mode

To display context menu in edit mode you need to display the context menu on editor by using StartEdit event ofthe C1FlexGrid class In the StartEdit event instantiate the editor and the ContextMenuStrip add menu items andthen assign it to ContextMenuStrip property of the editor

Create an instance of ContextMenuStrip controlContextMenuStrip cm = new ContextMenuStrip()

Add menu items to the context menucmItemsAdd(Add Above)cmItemsAdd(Add Below)cmItemsAdd(Add Left)cmItemsAdd(Add Right)

Assign the instance to ContextMenuStrip property c1FlexGrid1ContextMenuStrip = cm

C

Create an instance of ContextMenuStrip controlDim cm As ContextMenuStrip = New ContextMenuStrip()

Add menu items to the context menucmItemsAdd(Add Above)cmItemsAdd(Add Below)cmItemsAdd(Add Left)cmItemsAdd(Add Right)

Assign the instance to ContextMenuStrip property c1FlexGrid1ContextMenuStrip = cm

VBNET

FlexGrid for WinForms

106 Copyright copy GrapeCity Inc All rights reserved

Use the code below to display context menu in WinForms FlexGrid in edit mode

private void C1FlexGrid1_StartEdit(object sender C1WinC1FlexGridRowColEventArgs e) TextBox tb = (TextBox)c1FlexGrid1Editor

Create context menu ContextMenuStrip cm2 = new ContextMenuStrip() cm2ItemsAdd(Cut) cm2ItemsAdd(Copy) cm2ItemsAdd(Paste) Set context menu tbContextMenuStrip = cm2

C

Private Sub C1FlexGrid1_StartEdit(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) Dim tb As TextBox = CType(c1FlexGrid1Editor TextBox)

Create context menu Dim cm2 As ContextMenuStrip = New ContextMenuStrip() cm2ItemsAdd(Cut) cm2ItemsAdd(Copy) cm2ItemsAdd(Paste)

Set context menu tbContextMenuStrip = cm2End Sub

VBNET

キーボードによる移動

With built-in keyboard support FlexGrid lets you perform the basic navigation operations such as moving the focusentering or exiting the edit mode etc with a perfect ease just by using keys Below tables list the supported keys andtheir corresponding operations in non-edit as well as in edit mode of the cell

Non-edit Mode

Key Sequence Key Action

FlexGrid for WinForms

107 Copyright copy GrapeCity Inc All rights reserved

uarr

larr rarr

darr

Moves focus to the adjacent cell in direction indicated by the arrow key

Shift + ArrowSelects adjacent cells in direction indicated by the arrow key

F2Grid is editable Toggles the cell to edit mode If a value exists in the cell it getsselected Else the grid simply displays a cursor in the cell

Grid is not editable No action

EnterGrid is editable Toggles the cell to edit mode If a value exists in the cell it getsselected Else the grid simply displays a cursor in the cell

Grid is not editable Moves the selection down to the next visible row

You can also change default behavior of Enter key press by using the KeyActionEnterproperty

HomeMoves focus to the first cell of row

EndMoves focus to the last cell of row

Ctrl + HomeMoves focus to the first cell of column

Ctrl + EndMoves focus to the last cell of column

TabBy default grid ignores the Tab key press and lets it cycle through the controls on theform However you can define the action to be performed on Tab key press by usingthe KeyActionTab property

Ctrl + C

Ctrl + X

Ctrl + V

Performs usual clipboard operations that is copy(Ctrl+C) cut(Ctrl+X) and paste(Ctrl+V)when AutoClipboard property is set to true (Default value is false)

Edit Mode

Key Sequence Key Action

uarr

darr

Moves focus to the adjacent cell in the direction indicated by arrow key

FlexGrid for WinForms

108 Copyright copy GrapeCity Inc All rights reserved

larr rarrMoves cursor by one character in the direction indicated by arrow key When cursor is onthe first or last character moves focus to the adjacent cell in the direction of arrow key

EnterToggles the cell to non-edit mode and moves focus to the cell below You can also changedefault behavior of Enter key press by using the KeyActionEnter property

EscCancels editing and exits the edit mode

TabBy default grid ignores the Tab key press and lets it cycle through the controls on theform However you can define the action to be performed on Tab key press by usingthe KeyActionTab property

パフォーマンスの向上

Use Data VirtualizationTo efficiently render large data sets FlexGrid supports data vitualization in which data is fetched in pages as the user scrolls down The gridknows the total number of rows but only loads and displays those that are visible to the user For instance you can use C1DataCollectionpackage to implement virtualizable data source Create a class inherited from the C1VirtualDataCollection and implement GetPageAsyncmethod which returns one page of data from data source you have assigned The following GIF shows how FlexGrid appears in the virtualscrolling mode

public class VirtualModeCollectionView C1VirtualDataCollectionltCustomergt public int TotalCount get set = 1_000 protected override async TaskltTupleltint IReadOnlyListltCustomergtgtgt GetPageAsync(int pageIndex int startingIndex int count IReadOnlyListltSortDescriptiongt sortDescriptions = null FilterExpression filterExpression = null CancellationToken cancellationToken = default(CancellationToken)) await TaskDelay(500 cancellationToken)Simulates network traffic return new Tupleltint IReadOnlyListltCustomergtgt(TotalCount EnumerableRange(startingIndex count)Select(i =gt new Customer(i))ToList())

C

Public Class VirtualModeCollectionView

VBNET

FlexGrid for WinForms

109 Copyright copy GrapeCity Inc All rights reserved

Use BeginUpdate and EndUpdate MethodsThe BeginUpdate and EndUpdate methods are used to optimize the performance of the grid Call BeginUpdate before making extensivechanges and call EndUpdate when done to suspend repainting This reduces flicker and increases performance This optimization is especiallyeffective when adding large number of rows to the grid because it needs to recalculate ranges and update scrollbars each time a row is added

The code below shows how to add a large number of rows to the WinForms FlexGrid efficiently Note how the EndUpdate method is calledinside a finally block to ensure repainting is properly restored

Keep AutoResize Property to False (default)In case of bound grid if AutoResize property is set to true the control automatically resizes its columns to fit the widest entry every time newdata is read from the data source If the data source contains a large number of rows and columns the automatic resizing may take a relativelylong time In such cases you should consider setting AutoResize to false and setting the column widths directly in code

Assign Styles DynamicallyFlexGrid allows you to create cell styles and assign them to rows columns and arbitrary cell ranges You can use this feature to format the gridcells conditionally Usually you do this by using the SetCellStyle() method However in that case you have to update the style whenever the cellvalue changes Also if the grid is bound to a data source styles are lost whenever data source is reset after operations such as sorting andfiltering A better alternative in these cases is to use the OwnerDraw feature and select styles dynamically based on the cell values For example

Inherits C1VirtualDataCollection(Of Customer)

Public Property TotalCount As Integer = 1_000

Protected Overrides Async Function GetPageAsync(ByVal pageIndex As Integer ByVal startingIndex As Integer ByVal count As Integer ByVal Optional sortDescriptions As IReadOnlyList(Of SortDescription) = Nothing ByVal Optional filterExpression As FilterExpression = Nothing ByVal Optional cancellationToken As CancellationToken = DirectCast(Nothing CancellationToken)) As Task(Of Tuple(Of Integer IReadOnlyList(Of Customer))) Await TaskDelay(500 cancellationToken) Simulates network traffic Return New Tuple(Of Integer IReadOnlyList(Of Customer))(TotalCount EnumerableRange(CInt(startingIndex) CInt(count))[Select](Function(i) New Customer(i))ToList()) End FunctionEnd Class

void UpdateGrid(C1FlexGrid c1FlexGrid1) try c1FlexGrid1BeginUpdate() suspend painting to avoid flicker c1FlexGrid1RowsCount = 1 for (int i = 1 i lt 10000 i++) c1FlexGrid1AddItem(Row + iToString()) finally c1FlexGrid1EndUpdate() always restore painting

C

Private Sub UpdateGrid(ByVal c1FlexGrid1 As C1FlexGrid) Try c1FlexGrid1BeginUpdate() suspend painting to avoid flicker c1FlexGrid1RowsCount = 1

For i As Integer = 1 To 10000 - 1 c1FlexGrid1AddItem(Row amp iToString()) Next

Finally c1FlexGrid1EndUpdate() always restore painting End TryEnd Sub

VBNET

FlexGrid for WinForms

110 Copyright copy GrapeCity Inc All rights reserved

the sample code shows how to display negative values in red color and values above 1000 in green color in the WinForms FlexGrid

Avoid Modifying Styles in the OwnerDrawCell EventAnother way to improve performance is not to modify the CellStyle object passed as a parameter in the OwnerDrawCell event Instead assign anew value to the eStyle parameter This is important because the CellStyle passed to the event handler is often used by other cells Forexample you could unintentionally change a normal style of the WinForms FlexGrid which would affect other similar cells as well in the grid

private void Form1_Load(object sender EventArgs e) Fill a column with random values c1FlexGrid1Cols[1]DataType = typeof(int) Random rnd = new Random() for (int r = 1 r lt c1FlexGrid1RowsCount r++) c1FlexGrid1[r 1] = rndNext(-10000 10000) Create style used to show negative values c1FlexGrid1StylesAdd(Red)ForeColor = ColorRed Enable OwnerDraw by setting the DrawMode property c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw c1FlexGrid1OwnerDrawCell += new C1WinC1FlexGridOwnerDrawCellEventHandler(C1FlexGrid1_OwnerDrawCell)

private void C1FlexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if(eMeasuring) Check that the row and column contain integer data if (eRow gt 0 ampamp c1FlexGrid1Cols[eCol]DataType == typeof(int)) Apply the style Red eStyle = c1FlexGrid1Styles[Red]

C

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) Fill a column with random values c1FlexGrid1Cols(1)DataType = GetType(Integer) Dim rnd As Random = New Random()

For r As Integer = 1 To c1FlexGrid1RowsCount - 1 c1FlexGrid1(r 1) = rnd[Next](-10000 10000) Next

Create style used to show negative values c1FlexGrid1StylesAdd(Red)ForeColor = ColorRed

Enable OwnerDraw by setting the DrawMode property c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw c1FlexGrid1OwnerDrawCell += New C1WinC1FlexGridOwnerDrawCellEventHandler(AddressOf C1FlexGrid1_OwnerDrawCell) End Sub

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If Not eMeasuring Then

Check that the row and column contain integer data If eRow gt 0 AndAlso c1FlexGrid1Cols(eCol)DataType Is GetType(Integer) Then Apply the style Red eStyle = c1FlexGrid1Styles(Red) End If End If End Sub

VBNET

FlexGrid for WinForms

111 Copyright copy GrapeCity Inc All rights reserved

Show Ellipses in a Single ColumnThe Trimming property should be used to show ellipses in a single column of the grid To determine how long strings are trimmed to fit the cellthe Trimming property can be set to either None Character Word EllipsisCharacter EllipsisWord or EllipsisPath For more information ontrimming see Display Trimmed Text

The following code sets the Trimming property to show ellipses at the end of the second WinForms Flexgrid column with the text trimmed tothe nearest character

Show Multi-line Text in a CellWhen showing multiple lines of text in a cell use the WordWrap and Height properties The WordWrap property determines whether the gridshould automatically break long strings that contain spaces and display them in multiple lines Strings that contain hard line breaks (vbCrLf ornr) are always displayed in multiple lines Multiple line text can be displayed in both fixed and scrollable cells For more information on wordwrapping see Wrap Text

Refer to code below to see how a multi-line text should be effectively displayed in the WinForms FlexGrid

CORRECT APPROACHprivate void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) Select style to use when painting this cell eStyle = MyStyleSelector(eRow eCol) WRONG APPROACHprivate void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) Select style to use when painting this cell This is wrong because changing any CellStyle objects invalidates the grid which would cause this event handler to be called over and over again eStyleColor = MyColorSelector(eRow eCol)

C

CORRECT APPROACHPrivate Sub C1FlexGrid1_OwnerDrawCellMethod(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) Select style to use when painting this celleStyle = MyStyleSelector(eRow eCol)End Sub

WRONG APPROACHPrivate Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) Select style to use when painting this cell This is wrong because changing any CellStyle objects invalidates the grid which would cause this event handler to be called over and over againeStyleColor = MyColorSelector(eRow eCol)End Sub

VBNET

c1FlexGrid1Cols[1]StyleNewTrimming =StringTrimmingEllipsisCharacter

C

c1FlexGrid1Cols(1)StyleNewTrimming = StringTrimmingEllipsisCharacter

VBNET

Set the WordWrap property

C

FlexGrid for WinForms

112 Copyright copy GrapeCity Inc All rights reserved

Retrieve Data Sorting When Bound to a Data TableTo maintain the way the grid is sorted when data is refreshed you can use the default views Sort property and a sort expression The Sortproperty uses a string containing the column name followed by ASC(default) or DESC to sort the column in ascending or descending orderrespectively Multiple columns can be sorted by specifying each column name separated by a comma A sort expression can include names ofgrid columns or a calculation Setting the sort expression at run time immediately reflects the changes in the data view

Below code shows how to use the sort expression with Sort property in the WinForms FlexGrid

Specify Character Limit for ColumnTo set the maximum number of characters a user can enter for any given column use the SetupEditor event You must declare an externaleditor such as C1TextBox in the StartEdit event of the C1FlexGrid class Then in the SetupEditor event you can set the maximum number ofcharacters that are allowed in a column cell

Use the code below to set the character limit for a WinForms FlexGrid column

c1FlexGrid1Styles[Normal]WordWrap = true Set the row heightc1FlexGrid1Rows[1]Height = 2 fgRowsDefaultSize Add text to the cellc1FlexGrid1[1 2] = This is the first line rn This is the second line

Set the WordWrap property c1FlexGrid1Styles(Normal)WordWrap = True

Set the row height c1FlexGrid1Rows(1)Height = 2 fgRowsDefaultSize

Add text to the cell c1FlexGrid1(1 2) = This is the first line amp vbCrLf amp This is the second line

VBNET

Sort the data by the UnitsInStock column then by the ProductID column thisproductsBindingSourceSort = UnitsInStock ASC ProductID ASC

C

Sort the data by the UnitsInStock column then by the ProductID columnMeproductsBindingSourceSort = UnitsInStock ASC ProductID ASC

VBNET

private void C1FlexGrid1_StartEdit(object sender C1WinC1FlexGridRowColEventArgs e) c1FlexGrid1Editor = c1TextBox private void C1FlexGrid1_SetupEditor(object sender RowColEventArgs e) Set the 3rd column to allow 20 characters and the rest only 10 if (eCol == 2) c1TextBoxMaxLength = 20 else c1TextBoxMaxLength = 10

C

Private Sub C1FlexGrid1_StartEdit(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs)

VBNET

FlexGrid for WinForms

113 Copyright copy GrapeCity Inc All rights reserved

c1FlexGrid1Editor = c1TextBox End Sub

Private Sub C1FlexGrid1_SetupEditor(ByVal sender As Object ByVal e As RowColEventArgs)

Set the 3rd column to allow 20 characters and the rest only 10 If eCol = 2 Then c1TextBoxMaxLength = 20 Else c1TextBoxMaxLength = 10 End If End Sub

FlexGrid for WinForms

114 Copyright copy GrapeCity Inc All rights reserved

スクロールバー

Display or Hide the Scroll BarIn FlexGrid you can manage the display of scroll bars using the ScrollBars property which lets you choose whether todisplay horizontal vertical both or no scroll bar through the ScrollBars enumeration

Below code shows how to always display both the scrollbars in the WinForms FlexGrid

Set Scroll PositionTo scroll FlexGrid to a specified location you can set TopRow and LeftCol property of the C1FlexGrid class TopRowproperty scrolls the grid vertically while LeftCol sets the horizontal scroll position of the grid The maximum value ofthese properties depends on the total number of rows or columns and the count that can be displayed in the gridThis feature is really useful in scenarios like synchronized scrolling of multiple grids

Use the code below to set scroll position of the WinForms FlexGrid

水平および垂直スクロールバーを表示しますc1FlexGrid1ScrollBars = ScrollBarsBoth 常にスクロールバーを表示しますc1FlexGrid1ScrollOptions = ScrollFlagsAlwaysVisible

C

水平および垂直スクロールバーを表示しますc1FlexGrid1ScrollBars = ScrollBarsBoth

常にスクロールバーを表示しますc1FlexGrid1ScrollOptions = ScrollFlagsAlwaysVisible

VBNET

スクロール位置を設定しますc1FlexGrid1TopRow = 3c1FlexGrid1LeftCol = 2

C

スクロール位置を設定しますc1FlexGrid1TopRow = 3

VBNET

FlexGrid for WinForms

115 Copyright copy GrapeCity Inc All rights reserved

Other Scroll OptionsFlexGrid also provides more options to handle various aspects of displaying a scroll bar through ScrollOptionsproperty This property accepts the values from ScrollFlags enumeration which lets you customize the scroll baroptions as described in the table below

Value Scroll Operation

AlwaysVisible Displays the scroll bar even when they are disable or there is no scrollable area

DelayedScroll Scrolls the content only after user has released the scrollbar thumb

KeepMergedRangePosition Can not set scroll position to the first cell of a merged range

None Uses the default scrolling behavior

ScrollByRowColumn Scrolls the content in units of rows or columns instead of scrolling by pixels

ShowScrollTips Fires the ShowScrollTip event and displays a tooltip next to the vertical scrollbarwhile scrolling vertically

Following code shows how to scroll the WinForms FlexGrid by rows or columns only

c1FlexGrid1LeftCol = 2

行や列単位でスクロールします c1FlexGrid1ScrollOptions = ScrollFlagsScrollByRowColumn

C

行や列単位でスクロールしますc1FlexGrid1ScrollOptions = ScrollFlagsScrollByRowColumn

VBNET

FlexGrid for WinForms

116 Copyright copy GrapeCity Inc All rights reserved

選択

Selection ModesFlexGrid by default allows to select a continuous batch of cells using mouse or keyboard and entire row or column by clicking thecorresponding header However the default behavior can be changed to allow selection in units of cell row column etc byusing SelectionMode property of the C1FlexGrid class The property accepts values from the SelectionModeEnumenumeration Below table gives a quick snapshot of how selection looks like in each of these modes

Value Description Snapshot

Default Allows selection of continuous batch of cells using mouse orkeyboard Also lets the user select entire row or column onclicking the respective header

Cell Allows selection of single cell at a time

CellRange Allows selection of continuous batch of cells using mouse orkeyboard

Column Allows selection of single column at a time

ColumnRange Allows selection of multiple contiguous columns at a time

ListBox Allows selection of multiple non-contiguous rows using the Ctrlkey

FlexGrid for WinForms

117 Copyright copy GrapeCity Inc All rights reserved

Row Allows selection of single row at a time

RowRange Allows selection of multiple contiguous rows at a time

Set SelectionFlexGrid provides various ways to set the selection through code You can use any of these methods depending on the requirementsuch as selecting the single cell cell range or rows

Selection MethodProperty Sample code

Single cell Set the Row and Col property Default value of both of theseproperties is 1 Hence by default selection is set to the firstscrollable cell on top left of the grid

Example Title

c1FlexGrid1Row = 2c1FlexGrid1Col = 1

Call the Select(rowIndex colIndex) method to select a singlecell

Example Title

c1FlexGrid1Select(2 1)

Cell range Set the RowSel and ColSel property These properties set theselection starting from value set in Row and Col property tothe specified row and column Note that to specify a blockselection you must set Row and before setting RowSel andColSel

Example Title

c1FlexGrid1Row = 2c1FlexGrid1Col = 1c1FlexGrid1RowSel = 4c1FlexGrid1ColSel = 3

Call the Select(CellRange Boolean) method to select a cellrange in a single call

Example Title

CellRange cellRange = new CellRange()cellRanger1 = 2cellRanger2 = 4cellRangec1 = 1cellRangec2 = 3c1FlexGrid1Select(cellRange)

Rows

(If SelectionModes =

SelectionModesEnum

ListBox)

Set the RowSelected property to true for individual rowobjects to select the non-continuous rows

Example Title

c1FlexGrid1SelectionMode = SelectionModeEnumListBoxc1FlexGrid1Rows[1]Selected = truec1FlexGrid1Rows[4]Selected =

Value Description Snapshot

FlexGrid for WinForms

118 Copyright copy GrapeCity Inc All rights reserved

true

Get Selection To get selected range of the WinForms FlexGrid you can use Selection property of the C1FlexGrid class

Select Text on Double ClickBy default double click on a grid cell changes the cell state to edit mode and shows the cursor at position of the mouse pointerHowever you can change this behavior and select the cell value on double click of a cell This can be done by detecting anddisabling the double click in BeforeDoubleClick event Then call the StartEditing method to enter the edit mode change theeditor to a TextBox and call the SelectAll method to select the cell value

Following code shows how you can select text of the WinForms FlexGrid cell on a double click

private void Button1_Click(object sender EventArgs e) C1WinC1FlexGridCellRange cr cr = c1FlexGrid1Selection MessageBoxShow(Selected rangen + crr1 + + crc1 + to + crr2 + + crc2)

C

Private Sub Button1_Click(ByVal sender As Object ByVal e As EventArgs) Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1Selection MessageBoxShow(Selected range amp vbLf amp crr1 amp + crc1 amp to + crr2 amp + crc2)End Sub

VBNET

private void C1FlexGrid1_BeforeDoubleClick(object sender BeforeMouseDownEventArgs e) デフォルトのダブルクリックを無効にします eCancel = true 編集モードに入ります c1FlexGrid1StartEditing() TextBoxクラスに変換しSelectAllメソッドを使用して選択します TextBox tb = (TextBox)c1FlexGrid1Editor tbSelectAll()

C

Private Sub C1FlexGrid1_BeforeDoubleClick(ByVal sender As Object ByVal e As BeforeMouseDownEventArgs) デフォルトのダブルクリックを無効にします eCancel = True 編集モードに入ります c1FlexGrid1StartEditing() TextBoxクラスに変換しSelectAllメソッドを使用して選択します Dim tb As TextBox = CType(c1FlexGrid1Editor TextBox) tbSelectAll()End Sub

VBNET

Selection MethodProperty Sample code

FlexGrid for WinForms

119 Copyright copy GrapeCity Inc All rights reserved

編集

This topic discusses about various events and methods which are related to editing and also about how to disableediting

Topic Content

Edit Mode Discusses various events and methods related to editing

Disable Editing Discusses how to disable editing in grid at various levels

Disable Grid EditingDisable Row or Column EditingDisable Cell Editing

編集モード

In FlexGrid edit mode can be invoked at runtime using mouse click or even keyboard To determineprogrammatically whether the grid is in edit mode you can read the value of Editor property If the grid is in editmode the property returns a reference to the control that is being used as editor such as TextBox or ComboBoxHowever if the grid is not in edit mode the property returns null

To put the grid in edit mode programmatically you can use the StartEditing method and to finish editing you can callthe FinishEditing method You can also retain the state of edit mode in grid while navigating through the cells byusing the PreserveEditMode property

In addition FlexGrid fires various events to facilitate better control on the editing process Below table lists thesequence of events which are fired by the grid during the editing process

Event Name Description

BeforeEdit The event fires whenever an editable cell is selected It allows you to prevent the cell from beingedited by setting the events Cancel parameter to true You can also modify the ComboList propertyso the appropriate drop-down button gets painted in the cell Note that the user might not actuallystart editing after this he could simply move the selection to a different cell or control

StartEdit The event is similar to BeforeEdit except the user has actually typed a key or clicked the dropdownbutton in the cell and really is about to start editing You can still cancel the editing at this point Notethat the Editor property is still null at this point because the control hasnt yet determined the typeof editor that should be used You can assign custom editors to the Editor property at this point

ChangeEdit The event is a wrapper of editorTextChanged event The event fires when the contents of the editorchange You can use this event to keep track of the current content in editor

SetupEditor The event fires after the editor control has been created and configured to edit the cell but before itis displayed You can change the editor properties at this point (for example set the maximum lengthor password character to be used in a TextBox editor) You can also attach your own event handlers tothe editor

ValidateEdit The event fires when the user is done editing before the editor value gets copied back into the gridYou can examine the original value by retrieving it from the grid (the event provides the coordinatesof the cell) You can examine the new value about to be assigned to the grid through the Editorproperties (for example EditorText) If the new value is not valid for the cell set the Cancel parameterto true and the grid remains in edit mode If instead of keeping the cell in edit mode you wouldrather restore the original value and leave edit mode set Cancel parameter to true and then call theFinishEditing method

LeaveEdit This event fires after the grid control leaves edit mode You can use this event to approve or deny the

FlexGrid for WinForms

120 Copyright copy GrapeCity Inc All rights reserved

new cell content or to change the editor content about to be committed

AfterEdit This event fires after the new value has been applied to the cell and the editor has been deactivatedYou can use this event to update anything that depends on the cell value (for example subtotals orsorting)

Also there are few events which are related to keyboard operations and are fired when a key is pressed They aresimilar to their counterparts from SystemWindowsFormsControl class apart from the fact that they occur when thegrid is in edit mode

Event Description

KeyDownEdit This event fires when grid is in edit mode and a key is pressed You can use this event toperform an action once or even multiple times while the key is held down such as movinga cursor

KeyPressEdit This event fires when grid is in edit mode and a character key is pressed You can use thisevent to perform any operation related to typing such as handling input in the cell editor

KeyUpEdit This event fires when grid is in edit mode and key is released You can use this event toplace a logic that executes after KeypressEdit logic has taken effect

Event Name Description

編集の無効化

FlexGrid by default allows end-user to edit the cell values at runtime However with FlexGrid you can easily managehow much control you want to give to the end-users using various properties provided by the FlexGrid

Disable Grid EditingTo disable editing of the whole WinForms FlexGrid you need to set AllowEditing property of the C1FlexGrid class tofalse as shown in the code below

Disable Row or Column EditingTo disable the editing of a particular row or column of the WinForms FlexGrid you can set the AllowEditing propertyof Row or Column object to false as shown in the code below

グリッドで編集を無効にします c1FlexGrid1AllowEditing = false

C

グリッドで編集を無効にしますc1FlexGrid1AllowEditing = False

VBNET

3行目の編集を無効にしますc1FlexGrid1Rows[3]AllowEditing = false 3列目の編集を無効にしますc1FlexGrid1Cols[3]AllowEditing = false

C

FlexGrid for WinForms

121 Copyright copy GrapeCity Inc All rights reserved

Disable Cell EditingTo disable editing of a particular cell you can use the BeforeEdit event and set the Cancel parameter for thatparticular cell to true

3行目の編集を無効にしますc1FlexGrid1Rows(3)AllowEditing = False

3列目の編集を無効にしますc1FlexGrid1Cols(3)AllowEditing = False

VBNET

セル編集を無効にしますprivate void C1FlexGrid1_BeforeEdit(object sender RowColEventArgs e) if ((eCol == 4) ampamp (eRow == 2)) eCancel = true

C

セル編集を無効にしますPrivate Sub C1FlexGrid1_BeforeEdit(ByVal sender As Object ByVal e As RowColEventArgs) If eCol = 4 AndAlso eRow = 2 Then eCancel = True End IfEnd Sub

VBNET

FlexGrid for WinForms

122 Copyright copy GrapeCity Inc All rights reserved

並べ替え

Sorting is one of the basic features a grid must have and FlexGrid provides you complete control on how data can besorted in ascending or descending order for easier data analysis This topic discusses about sorting in FlexGrid andother related operations

Topic Snapshot Content

Sort Operations Discusses various operations related to sorting

Sorting through CodeSort Multiple ColumnsRevertUndo SortingDisable Sort on a Particular ColumnSort OrderCustom Sorting

Sort Indicator Discusses how to hide position and customize sort indicator

HideDisplay Sort IndicatorPosition Sort IndicatorCustomize Sort Indicator

並べ替えの操作

FlexGrid by default allows end-users to apply sorting on a single column by clicking the column header in ascending ordescending order However the grid also provides you flexibility so that you can sort your data according to yourrequirement Below sections take you through the ways to perform various operations related to sorting

Sorting through CodeYou can apply sorting through code by calling Sort method of the C1FlexGrid class The method takes SortFlagsenumeration as its parameter which lets you provide the various sort options such as setting the sort order and ignorecasing The method has various overloads which gives you flexibility to apply sorting either on a column or a range ofcells rows or columns

Use the code below to sort columns and apply sorting options through code in the WinForms FlexGrid

FlexGrid for WinForms

123 Copyright copy GrapeCity Inc All rights reserved

Sort Multiple ColumnsTo apply sorting on multiple columns through code you can use the Sort property of Column class and then call theSort() method with SortFlags set to UseColSort The Sort property accepts values from SortFlags enumeration

Following code shows how to sort multiple columns of the WinForms FlexGrid through code

To allow user to sort multiple columns at runtime set AllowSorting property of the C1FlexGrid class to MultiColumn Theproperty accepts values from the AllowSortingEnum enumeration

Following code shows how to let user sort multiple columns of the WinForms FlexGrid at run-time

方法1 2番目の列を降順で並べ替えますc1FlexGrid1Sort(C1WinC1FlexGridSortFlagsDescending 2) 方法 2SortFlagを使用して複数の並べ替えオプションを指定しますC1WinC1FlexGridSortFlags order = C1WinC1FlexGridSortFlagsAscending | C1WinC1FlexGridSortFlagsIgnoreCase Sortメソッドを呼び出しますc1FlexGrid1Sort(order 2)

C

方法1 2番目の列を降順で並べ替えますc1FlexGrid1Sort(C1WinC1FlexGridSortFlagsDescending 2)

方法2 SortFlagを使用して複数の並べ替えオプションを指定しますDim order As C1WinC1FlexGridSortFlags = C1WinC1FlexGridSortFlagsAscending Or C1WinC1FlexGridSortFlagsIgnoreCase

Sortメソッドを呼び出しますc1FlexGrid1Sort(order 2)

VBNET

複数列を並べ替えますc1FlexGrid1Cols[2]Sort = SortFlagsAscendingc1FlexGrid1Cols[3]Sort = SortFlagsDescending Sortメソッドを呼び出しますc1FlexGrid1Sort(SortFlagsUseColSort 2 3)

C

複数列を並べ替えますc1FlexGrid1Cols(2)Sort = SortFlagsAscendingc1FlexGrid1Cols(3)Sort = SortFlagsDescending

Sortメソッドを呼び出しますc1FlexGrid1Sort(SortFlagsUseColSort 2 3)

VBNET

グリッドの複数の列での並べ替えを許可します c1FlexGrid1AllowSorting = AllowSortingEnumMultiColumn

C

FlexGrid for WinForms

124 Copyright copy GrapeCity Inc All rights reserved

RevertUndo SortingTo remove sorting from the grid you can set SortDefinition property of the C1FlexGrid class to an empty string

Below code how to remove sorting from the WinForms FlexGrid

Disable Sort on a Particular ColumnTo disable sorting on a particular column you need to set the AllowSorting property of that Column object to false

Use the code below to disable sorting on a particular column of the WinForms FlexGrid

Sort OrderOrder of sorting usually varies in case of bound and unbound mode When a column header is clicked in case of boundmode sorting is done same as DefaultViewSort property of the data table However in case of unbound mode columnis sorted either according to StringCompare method or by differentiating the lower and upper case according to theculture

Refer to the code below to specify sorting order of a WinForms FlexGrid column

グリッドの複数の列での並べ替えを許可しますc1FlexGrid1AllowSorting = AllowSortingEnumMultiColumn

VBNET

並べ替えを削除します c1FlexGrid1SortDefinition = stringEmpty

C

並べ替えを削除しますc1FlexGrid1SortDefinition = StringEmpty

VBNET

グリッドの特定の列での並べ替えを無効にしますc1FlexGrid1Cols[2]AllowSorting = false

C

グリッドの特定の列での並べ替えを無効にしますc1FlexGrid1Cols(2)AllowSorting = False

VBNET

C1WinC1FlexGridSortFlags order = C1WinC1FlexGridSortFlagsAscending | C1WinC1FlexGridSortFlagsIgnoreCase c1FlexGrid1Sort(order 2)

C

Dim order As C1WinC1FlexGridSortFlags = C1WinC1FlexGridSortFlagsAscending Or C1WinC1FlexGridSortFlagsIgnoreCasec1FlexGrid1Sort(order 2)

VBNET

FlexGrid for WinForms

125 Copyright copy GrapeCity Inc All rights reserved

Custom SortingFlexGrid provides several sorting options which are required for most commonly used scenarios such as ignore case usethe display value etc However if you need to have more flexibility and control over sort operation you can even writeyour own custom logic using the IComparer class For instance the example below sorts the Name column by fileextensions In the sample code custom logic to sort by file extension is implemented in the FileNameComparer class whichis then passed as parameter to Sort() method of the C1FlexGrid class

The code below demonstrates how to apply custom sorting on the WinForms FlexGrid columns

c1FlexGrid1Sort(new FileNameComparer(c1FlexGrid1 eOrder)) class FileNameComparer IComparer C1FlexGrid c1FlexGrid1 bool _desc

ctor public FileNameComparer(C1FlexGrid flex SortFlags order) c1FlexGrid1 = flex _desc = ((order amp SortFlagsDescending) = 0) IComparer public int Compare(object r1 object r2) ファイル名を取得します string s1 = (string)c1FlexGrid1[((Row)r1)Index Name] string s2 = (string)c1FlexGrid1[((Row)r2)Index Name]

拡張機能を比較します int icmp = stringCompare(PathGetExtension(s1) PathGetExtension(s2) true)

並べ替え順(昇順または降順)を返します return (_desc) -icmp icmp

C

C1FlexGrid1Sort(New FileNameComparer(C1FlexGrid1 SortFlagsAscending))

Public Class FileNameComparer Implements IComparer

Private c1FlexGrid1 As C1FlexGrid Private _desc As Boolean

Public Sub New(ByVal flex As C1FlexGrid ByVal order As SortFlags) c1FlexGrid1 = flex _desc = ((order And SortFlagsDescending) ltgt 0) End Sub

Public Function Compare(r1 As Object r2 As Object) As Integer Implements IComparerCompare Dim s1 As String = CStr(c1FlexGrid1((CType(r1 Row))Index Name)) Dim s2 As String = CStr(c1FlexGrid1((CType(r2 Row))Index Name)) Dim icmp As Integer = StringCompare(PathGetExtension(s1) PathGetExtension(s2) True) Return If((_desc) -icmp icmp) End Function

VBNET

FlexGrid for WinForms

126 Copyright copy GrapeCity Inc All rights reserved

For detailed implementation of custom sorting see the product sample named Custom Sort

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing WinFormsEdition using ComponentOneControlPanelexe

並べ替えのインジケータ

FlexGrid displays sort indicator a small triangular arrow sign to indicate the direction of sorting The grid alsoprovides flexibility to hide display position or customize the indicator

Hide or Display Sort IndicatorFlexGrid by default displays the sort indicator when a column header is clicked to sort the columns However you canhide the indicator by setting the ShowSortPosition property to None The property accepts valuesfrom ShowSortPositionEnum enumeration

Use the code below to hide the sort indicator displayed on the sorted WinForms FlexGrid column

Position Sort IndicatorSort indicator by default gets displayed towards the right side of the header cell However when the filtering isapplied on a column the sort indicator displays on top of the header cell to give place to the filtering icon You can fixthe position of sort indicator by setting value of ShowSortPosition property to Top or Right

Customize the position of column sort indicator in WinForms FlexGrid using the code below

Customize Sort IndicatorFlexGrid provides the GlyphEnum enumeration which lets you specify the image to be used for sort indicator Formore information on the GlyphEnum and glyph customization see Custom Glyphs

並べ替えインジケータを非表示にしますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumNone

C

並べ替えインジケータを非表示にしますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumNone

VBNET

並べ替えインジケータの位置を上に変更しますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumTop

C

並べ替えインジケータの位置を上に変更しますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumTop

VBNET

FlexGrid for WinForms

127 Copyright copy GrapeCity Inc All rights reserved

フィルタ

Grid filtering lets you narrow down display records according to a specified condition applied on a column It is especially useful in case of large data sets asit lets you easily analyze data by displaying a specific type of records only

This section discusses about the process types and customization of filters

Topic Snapshot Content

Filter Operations Discusses about how to enable or apply filtering and other related operations

Allow FilteringFiltering through CodeCustom FilteringRemove FilteringTypes of Filters

Filter UI Discusses about filtering icon its customization and how to set the filter language

Show Filter IconUse Custom IconsChange Filter Language

フィルタの操作

Data filtering in a grid can be performed in two ways

Header-based Filter

In header-based filtering an icon is displayed in the header cell of column which gives you options to specify the filter in a drop-down and alsoindicates if the filter is applied on a particular column In FlexGrid this behavior can be achieved by simply using AllowFiltering property of the gridIn this case filter does not require any extra real estate on the screen This approach also gives you flexibility to customize and create better filtereditors More details about same is given in the sections below

Filter Row

Filter row is a row dedicated for displaying the filtering criteria and appears just below the column header So in this case user can always see thefiltered columns and their current filtering criteria But this added advantage comes at the cost of extra screen real estate that a filter row needs InFlexGrid you can easily achieve filter row using the custom implementation For implementation see the product sample named Filter Row

Note The Filter Row sample is located at DocumentsComponentOne SamplesWinFormsv452C1FlexGridCS on your system if you haveinstalled the samples while installing WinForms Edition using ComponentOneControlPanelexe

Allow FilteringIn FlexGrid filtering can be enabled by setting the C1FlexGridAllowFiltering property to true This enables the default ColumnFilter on allcolumns of the grid The ColumnFilter lets the users choose from ValueFilter and ConditionFilter at runtime

FlexGrid for WinForms

128 Copyright copy GrapeCity Inc All rights reserved

You can also specify the filter types for each column by setting the AllowFiltering property of each Column object AllowFiltering property ofcolumn lets you choose from any of the following values

Value Description

Default Enables the ColumnFilter which is a combination of ValueFilter and ConditionFilter and gives user a runtime option to choose eitherof them

ByValue Enables ValueFilter which contains a checkbox list of values present in that column User can check off the values that should not bedisplayed in the filtered output

ByCondition Enables ConditionFilter which lets you specify combination of two conditions such as equals greater than contains etc Youcan combine the specified conditions using And and Or operator

Custom Lets you instantiate a custom filter and explicitly assign it to Filter property of the column

None Disables filtering for that column

Use the following code snippet to enable a condition filter on first column of the WinForms FlexGrid

For more details regarding abovementioned filter types see Types of Filters

Filtering through CodeAlthough AllowFiltering property of grid enables grid filtering and can be used in most common scenarios there may be cases where you need tofurther fine tune the filter options This can be achieved by modifying AllowFiltering and Filter properties of individual columns For example thecode below enables filtering in the WinForms FlexGrid but restricts the filtering to columns of type string

You can also customize the filtering process further by creating filters and assigning them to columns or by retrieving existing filters and modifyingtheir properties For example the code below creates a ConditionFilter in the WinForms FlexGrid configures it to select all items that are equal toGermany and then assigns the new filter to the ShipCountry column

グリッドでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = true 列1に対してフィルタを指定しますc1FlexGrid1Cols[1]AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

C

グリッドでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = True

列1に対してフィルタを指定しますc1FlexGrid1Cols(1)AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

VBNET

文字列型の列にフィルタリングを制限します foreach (Column c in c1FlexGrid1Cols) cAllowFiltering = cDataType == typeof(string) AllowFilteringDefault AllowFilteringNone

C

文字列型の列にフィルタリングを制限しますFor Each c As Column In c1FlexGrid1Cols cAllowFiltering = If(cDataType Is GetType(String) AllowFilteringDefault AllowFilteringNone)Next

VBNET

グリッドでフィルタリングを有効にします c1FlexGrid1AllowFiltering = true 新しいConditionFilterを作成します C1WinC1FlexGridConditionFilter Filter Filter = new C1WinC1FlexGridConditionFilter()

C

FlexGrid for WinForms

129 Copyright copy GrapeCity Inc All rights reserved

Custom FilteringWhen filtering is applied to FlexGrid it hides the rows that do not qualify the filtering criteria by setting their Visible property to false However insome cases you may want to customize this behavior For such scenarios you can use the BeforeFilter and AfterFilter events fired by FlexGridThe below example customizes the filtering behavior of WinForms FlexGrid by applying a different style to non-qualifying rows instead of hidingthem

Germanyのアイテムを絞り込むためのフィルタを作成します FilterCondition1Operator = C1WinC1FlexGridConditionOperatorEquals FilterCondition1Parameter = Germany 「ShipCountry」列に新しいフィルタを割り当てます c1FlexGrid1Cols[ShipCountry]Filter = Filter フィルタを適用します c1FlexGrid1ApplyFilters()

グリッドでフィルタリングを有効にしますc1FlexGrid1AllowFiltering = True

新しいConditionFilterを作成しますDim Filter As C1WinC1FlexGridConditionFilterFilter = New C1WinC1FlexGridConditionFilter()

Germanyのアイテムを絞り込むためのフィルタを作成しますFilterCondition1[Operator] = C1WinC1FlexGridConditionOperatorEqualsFilterCondition1Parameter = Germany

「ShipCountry」列に新しいフィルタを割り当てますc1FlexGrid1Cols(ShipCountry)Filter = Filter

フィルタを適用しますc1FlexGrid1ApplyFilters()

VBNET

private void c1FlexGrid1_BeforeFilter(object sender CancelEventArgs e) c1FlexGrid1BeginUpdate()

private void c1FlexGrid1_AfterFilter(object sender EventArgs e) フィルタリングされた行を表示するために使用されるスタイルを取得します var cs = c1FlexGrid1Styles[filteredOut]

すべての行にスタイルを適用します

C

FlexGrid for WinForms

130 Copyright copy GrapeCity Inc All rights reserved

The above code uses a custom style named filteredout which can be defined as shown in the code below

Remove FilteringUser can remove column filtering at runtime by using Clear option given in the filter UI of each column You can also remove filtering of the wholegrid programmatically by passing the empty string in FilterDefinition property of FlexGrid

Below code demonstrates how to clear all the filters from the WinForms FlexGrid

for (int r = c1FlexGrid1RowsFixed r lt c1FlexGrid1RowsCount r++) var row = c1FlexGrid1Rows[r] if (rowVisible) 通常の行スタイルをリセットします rowStyle = null else フィルタリングされた行 見えるようにしスタイルを適用します rowVisible = true rowStyle = cs

更新を再開します c1FlexGrid1EndUpdate()

Private Sub c1FlexGrid1_BeforeFilter(ByVal sender As Object ByVal e As CancelEventArgs) c1FlexGrid1BeginUpdate()End Sub

Private Sub c1FlexGrid1_AfterFilter(ByVal sender As Object ByVal e As EventArgs) フィルタリングされた行を表示するために使用されるスタイルを取得します Dim cs = c1FlexGrid1Styles(filteredOut)

すべての行にスタイルを適用します For r = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 Dim row = c1FlexGrid1Rows(r)

If rowVisible Then 通常の行スタイルをリセットします rowStyle = Nothing Else フィルタリングされた行 見えるようにしスタイルを適用します rowVisible = True rowStyle = cs End If Next

更新を再開します c1FlexGrid1EndUpdate()End Sub

VBNET

フィルタによって除外された行のスタイルを作成しますvar cs = c1FlexGrid1StylesAdd(filteredOut)csBackColor = ColorLightGraycsForeColor = ColorDarkGray

C

フィルタによって除外された行のスタイルを作成しますDim cs = c1FlexGrid1StylesAdd(filteredOut)csBackColor = ColorLightGraycsForeColor = ColorDarkGray

VBNET

フィルタ定義を空の文字列に設定してフィルタリングを削除しますc1FlexGrid1FilterDefinition = stringEmpty

C

FlexGrid for WinForms

131 Copyright copy GrapeCity Inc All rights reserved

フィルタ定義を空の文字列に設定してフィルタリングを削除しますc1FlexGrid1FilterDefinition = StringEmpty

VBNET

フィルタの種類

FlexGrid not only provides built-in filters such as Column filter Value filter and Condition Filter but also lets youcreate your own custom filter The built-in filters are provided through AllowFiltering property of Column class whichlets you set the type of filter to be applied on a particular column On the other hand the custom filters make use ofthe IC1ColumnFilter interface and the IC1ColumnFilterEditor interface This topic discusses the implementation ofbuilt-in and custom filters in detail

Column FilterColumn filter is the default filter that is applied to all the columns automatically when AllowFiltering property of thegrid is set to true The ColumnFilter is a combination of ValueFilter and ConditionFilter (discussed below) and givesuser an option to choose either of them at runtime While working with code you can use its ValueFilterand ConditionFilter properties to access the two types of filters The filter also provides Apply method to apply filterto a value and Reset method to reset the filter and hence making it inactive

Use the below code to apply column filter on ProductName column of the WinForms FlexGrid

列フィルタ(ProductNameが「C」で始まる製品をフィルター処理します)ColumnFilter colFilter = new ColumnFilter()colFilterConditionFilterCondition1Parameter = CcolFilterConditionFilterCondition1Operator = ConditionOperatorBeginsWithc1FlexGrid1Cols[ProductName]Filter = colFilter

C

列フィルタ(ProductNameが「C」で始まる製品をフィルター処理します) Dim colFilter As ColumnFilter = New ColumnFilter()

VBNET

FlexGrid for WinForms

132 Copyright copy GrapeCity Inc All rights reserved

Value FilterValue filter refers to the value based filter which gets enabled on setting the AllowFiltering property of column toByValue The ValueFilter provides the dropdown list of all values with checkbox which lets the user select the valueswhich are to be displayed in the output These values can be get or set through the ShowValues property You canalso set a limit on number of values to be displayed in the dropdown list by setting the ValuesLimit property Just likecolumn filter value filter also provides Apply method to apply filter to a value and Reset method to reset the filter

Below code shows how to apply ValueFilter on a column of the WinForms FlexGrid

Condition FilterCondition filter refers to a filter based on one or two logical conditions which can be enabled by setting theAllowFiltering property to ByCondition The ConditionFilter gives user an option to set the conditionsthrough Condition1 and Condition2 properties which can be combined using ANDOR operator by settingthe AndConditions property to filter the records Similar to other filters this class also provides Apply and Resetmethod

colFilterConditionFilterCondition1Parameter = C colFilterConditionFilterCondition1[Operator] = ConditionOperatorBeginsWith c1FlexGrid1Cols(ProductName)Filter = colFilter

値フィルタ(CategoryIdが12358である製品をフィルタ処理します)ValueFilter valueFilter = new ValueFilter()valueFilterShowValues = new object[] 1 2 3 5 8 c1FlexGrid1Cols[CategoryId]Filter = valueFilter

C

値フィルタ(CategoryIdが12358である製品をフィルタ処理します) Dim valueFilter As ValueFilter = New ValueFilter() valueFilterShowValues = New Object() 1 2 3 5 8 c1FlexGrid1Cols(CategoryId)Filter = valueFilter

VBNET

FlexGrid for WinForms

133 Copyright copy GrapeCity Inc All rights reserved

Below code demonstrates how to apply a ConditionFilter on a WinForms FlexGrid column

Custom FilterThe abovementioned filters provide you enough flexibility to implement most common filtering scenarios efficientlyIn addition custom filter option also lets you create your own filter to meet any other specialized requirements ofyour application To create a custom filter you need to create a filter class that implements the IC1ColumnFilterinterface and an editor class that implements the IC1ColumnFilterEditor interface Below example shows theimplementation of a custom string filter which lets you filter based on ranges

条件フィルタ(UnitPricegt = 50およびlt= 100の製品をフィルタ処理します)ConditionFilter conditionFilter = new ConditionFilter()conditionFilterCondition1Parameter = 50conditionFilterCondition1Operator = ConditionOperatorGreaterThanOrEqualToconditionFilterCondition2Parameter = 100conditionFilterCondition2Operator = ConditionOperatorLessThanOrEqualToconditionFilterAndConditions = truec1FlexGrid1Cols[UnitPrice]Filter = conditionFilter

C

条件フィルタ(UnitPricegt = 50およびlt= 100の製品をフィルタ処理します) Dim conditionFilter As ConditionFilter = New ConditionFilter() conditionFilterCondition1Parameter = 50 conditionFilterCondition1[Operator] = ConditionOperatorGreaterThanOrEqualTo conditionFilterCondition2Parameter = 100 conditionFilterCondition2[Operator] = ConditionOperatorLessThanOrEqualTo conditionFilterAndConditions = True c1FlexGrid1Cols(UnitPrice)Filter = conditionFilter

VBNET

FlexGrid for WinForms

134 Copyright copy GrapeCity Inc All rights reserved

Following is the code of a custom filter created for the WinForms FlexGrid Note that the class implementsIC1CustomFilter interface

StringFiltercs

class StringFilter C1WinC1FlexGridIC1ColumnFilter

ListltPointgt _ranges = new ListltPointgt()

ltsummarygt このフィッタが受け入れる文字列を定義するポイントのリストを取得します ltsummarygt public ListltPointgt Ranges get return _ranges

範囲リストが空でない場合フィルタはアクティブです public bool IsActive get return _rangesCount gt 0

フィルタをリセットします public void Reset() _rangesClear()

指定された日付にフィルタを適用します public bool Apply(object value) if (value = null)

C

FlexGrid for WinForms

135 Copyright copy GrapeCity Inc All rights reserved

var s = valueToString() if (sLength gt 0) int c = charToUpperInvariant(s[0]) foreach (var cr in _ranges) if (c gt= charToUpperInvariant((char)crX) ampamp c lt= charToUpperInvariant((char)crY)) return true return false

このフィルタのエディタコントロールを返します public C1WinC1FlexGridIC1ColumnFilterEditor GetEditor() return new StringFilterEditor()

Friend Class StringFilter Implements C1WinC1FlexGridIC1ColumnFilter Private _ranges As List(Of Point) = New List(Of Point)()

ltsummarygt このフィッタが受け入れる文字列を定義するポイントのリストを取得します ltsummarygt Public ReadOnly Property Ranges As List(Of Point) Get Return _ranges End Get End Property

範囲リストが空でない場合フィルタはアクティブです Public ReadOnly Property IsActive As Boolean Implements C1WinC1FlexGridIC1ColumnFilterIsActive Get Return _rangesCount gt 0 End Get End Property

フィルタをリセットします Public Sub Reset() Implements C1WinC1FlexGridIC1ColumnFilterReset _rangesClear() End Sub

指定された日付にフィルタを適用します Public Function Apply(ByVal value As Object) As Boolean Implements C1WinC1FlexGridIC1ColumnFilterApply If value IsNot Nothing Then Dim s = valueToString()

If sLength gt 0 Then Dim c As Integer = AscW(CharToUpperInvariant(s(0)))

VBNET

FlexGrid for WinForms

136 Copyright copy GrapeCity Inc All rights reserved

Following is the code of a custom class that implements IC1CustomFilterEditor interface

StringFilterEditorcs

For Each cr In _ranges

If c gt= AscW(CharToUpperInvariant(MicrosoftVisualBasicChrW(crX))) AndAlso c lt= AscW(CharToUpperInvariant(MicrosoftVisualBasicChrW(crY))) Then Return True End If Next End If End If

Return False End Function

このフィルタのエディタコントロールを返します Public Function GetEditor() As C1WinC1FlexGridIC1ColumnFilterEditor Implements C1WinC1FlexGridIC1ColumnFilterGetEditor Return New StringFilterEditor() End Function

End Class

public partial class StringFilterEditor UserControl C1WinC1FlexGridIC1ColumnFilterEditor StringFilter _filter

public StringFilterEditor() InitializeComponent()

public void Initialize(C1WinC1FlexGridC1FlexGridBase grid int columnIndex C1WinC1FlexGridIC1ColumnFilter filter) _filter = (StringFilter)filter

チェックボックスの値を初期化します foreach (var pt in _filterRanges) switch ((char)ptX) case A _chkAEChecked = true break case F _chkFJChecked = true break case K _chkKOChecked = true break case P _chkPTChecked = true

C

FlexGrid for WinForms

137 Copyright copy GrapeCity Inc All rights reserved

break case U _chkUZChecked = true break public void ApplyChanges() フィルタをリセットします _filterRangesClear()

選択した範囲を追加します foreach (Control ctl in thisControls) var cb = ctl as CheckBox if (cb = null ampamp cbChecked) var pt = new Point((int)cbText[0] (int)cbText[cbTextLength - 1]) _filterRangesAdd(pt) public bool KeepFormOpen get return false void _chkAE_CheckedChanged(object sender EventArgs e) var cb = sender as CheckBox cbFont = new Font(Font cbChecked FontStyleBold FontStyleRegular)

Public Partial Class StringFilterEditor Inherits UserControl Implements C1WinC1FlexGridIC1ColumnFilterEditor

Private _filter As StringFilter Public Sub New() InitializeComponent() End Sub

Public Sub Initialize(ByVal grid As C1WinC1FlexGridC1FlexGridBase ByVal columnIndex As Integer ByVal filter As C1WinC1FlexGridIC1ColumnFilter) Implements C1WinC1FlexGridIC1ColumnFilterEditorInitialize _filter = CType(filter StringFilter)

チェックボックスの値を初期化します For Each pt In _filterRanges

Select Case MicrosoftVisualBasicChrW(ptX) Case Ac _chkAEChecked = True Case Fc _chkFJChecked = True Case Kc _chkKOChecked = True Case Pc

VBNET

FlexGrid for WinForms

138 Copyright copy GrapeCity Inc All rights reserved

_chkPTChecked = True Case Uc _chkUZChecked = True End Select Next End Sub

Public Sub ApplyChanges() Implements C1WinC1FlexGridIC1ColumnFilterEditorApplyChanges フィルタをリセットします _filterRangesClear()

選択した範囲を追加します For Each ctl As Control In Controls Dim cb = TryCast(ctl CheckBox)

If cb IsNot Nothing AndAlso cbChecked Then Dim pt = New Point(MicrosoftVisualBasicAscW(cbText(0)) MicrosoftVisualBasicAscW(cbText(cbTextLength - 1))) _filterRangesAdd(pt) End If Next End Sub

Public ReadOnly Property KeepFormOpen As Boolean Implements C1WinC1FlexGridIC1ColumnFilterEditorKeepFormOpen Get Return False End Get End Property

Private Sub _chkAE_CheckedChanged(ByVal sender As Object ByVal e As EventArgs) Dim cb = TryCast(sender CheckBox) cbFont = New Font(MyBaseFont If(cbChecked FontStyleBold FontStyleRegular)) End Sub

End Class

フィルタUI

FlexGrid provides several options to flexibly customize the filtering UI and lets you create your own unique filter for yourapplication The control allows you to show hide and customize the filtering icon You can even change the language displaying infilter to meet your localization requirements

Show Filter Icon

FlexGrid by default shows the filtering icon( ) when mouse hovers over the filterable column header However you can chooseto display the filtering icon always by setting ShowFilterIcon property of the C1FlexGrid class to Always The property accepts thevalues from FilterIconVisibility enumeration

FlexGrid for WinForms

139 Copyright copy GrapeCity Inc All rights reserved

Use the code below to always display the filter icon on filtered columns of the WinForms FlexGrid

Use Custom IconsFlexGrid also lets you customize the filtering icon by using Glyphs property of the C1FlexGrid class which accepts an imagethrough GlyphEnum enumeration You can also change icon displayed on the current filtered column using the same enumerationFor more information about custom glyphs see Custom Glyphs

常にフィルタのアイコンを表示しますc1FlexGrid1ShowFilterIcon = C1WinC1FlexGridFilterIconVisibilityAlways

C

常にフィルタのアイコンを表示しますc1FlexGrid1ShowFilterIcon = C1WinC1FlexGridFilterIconVisibilityAlways

VBNET

FlexGrid for WinForms

140 Copyright copy GrapeCity Inc All rights reserved

Following code displays how to apply custom icons on filtered columns of the WinForms FlexGrid

Change Filter LanguageBy default FlexGrid localizes the column filter editor to use language specified by the CurrentUICulture setting However you canuse the Language property to override the default and specify the language to be used when grid displays the column filter editor

Use the below code to change the display language of filter in the WinForms FlexGrid

フィルタのアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilterEditor] = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilteredColumn] = ImageFromFile(filterico)

C

フィルタのアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilterEditor) = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilteredColumn) = ImageFromFile(filterico)

VBNET

フィルタ言語を日本語に設定しますc1FlexGrid1Language = C1UtilLocalizationLanguageJapanese

C

フィルタ言語を日本語に設定しますc1FlexGrid1Language = C1UtilLocalizationLanguageJapanese

VBNET

FlexGrid for WinForms

141 Copyright copy GrapeCity Inc All rights reserved

検索

With FlexGrid you can easily perform search either on the entire grid or just a specific column This topic discusseshow you can enable search in FlexGrid

Search in Entire GridTo search the entire FlexGrid you need to add the C1FlexGridSearchPanel control to the form and associate it with thegrid to be searched using SetC1FlexGridSearchPanel method The C1FlexGridSearchPanel control highlights thesearch results and filters the records having search results automatically However you can choose not to highlight theresults by setting the HighlightSearchResults to false It also provides a SearchMode property to set whether tostart the search automatically or on hitting the Search button or Enter key You can also set the watermark in searchbox as well as a time delay in search

Use the code below to search the entire WinForms FlexGrid using SearchPanel

検索パネルを検索対象のFlexGridに関連付けますc1FlexGridSearchPanel1SetC1FlexGridSearchPanel(c1FlexGrid1 c1FlexGridSearchPanel1)

検索を構成しますc1FlexGridSearchPanel1HighlightSearchResults = truec1FlexGridSearchPanel1SearchMode = C1WinC1FlexGridSearchModeAlways c1FlexGridSearchPanel1Watermark = Search productsc1FlexGridSearchPanel1SearchDelay = 2

C

検索パネルを検索対象のFlexGridに関連付けます

VBNET

FlexGrid for WinForms

142 Copyright copy GrapeCity Inc All rights reserved

Search in ColumnTo enable column-wise search FlexGrid provides AutoSearch property of the C1FlexGrid class which accepts valuesfrom AutoSearchEnum enumeration The enumeration lets you start downward column search from the first scrollablerow or from the current cursor position To search a value in a particular column you need to keep the cursor in thatcolumn and type the value to be searched and grid automatically jumps to the search result in that column You canalso set delay in search by setting the AutoSearchDelay property

Following code enables column-wise search in the WinForms FlexGrid

c1FlexGridSearchPanel1SetC1FlexGridSearchPanel(c1FlexGrid1 c1FlexGridSearchPanel1)

検索を構成しますc1FlexGridSearchPanel1HighlightSearchResults = Truec1FlexGridSearchPanel1SearchMode = C1WinC1FlexGridSearchModeAlwaysc1FlexGridSearchPanel1Watermark = Search productsc1FlexGridSearchPanel1SearchDelay = 2

一番上の行からの列単位の検索を有効にしますc1FlexGrid1AutoSearch = C1WinC1FlexGridAutoSearchEnumFromTopc1FlexGrid1AutoSearchDelay = 2

C

一番上の行からの列単位の検索を有効にしますc1FlexGrid1AutoSearch = C1WinC1FlexGridAutoSearchEnumFromTopc1FlexGrid1AutoSearchDelay = 2

VBNET

FlexGrid for WinForms

143 Copyright copy GrapeCity Inc All rights reserved

マージ

FlexGrid allows you to merge cells with same values making them span multiple rows or columns This capability is useful for enhancing appearance andclarity of data displayed in the grid The effect of these settings is similar to the HTML ltROWSPANgt and ltCOLSPANgt tags

Cell merging has several possible uses For example you can use it to create merged table headers merged data views or grids where the text spills intoadjacent columns This section discusses these scenarios in the topics below

Topic Snapshot Content

Auto-merge Discusses about how to enable automatic merging in grid

Free auto-mergeRestricted auto-mergeMerge table headers

Handle Spilling Text Discusses how to display long texts in normal and node rows

Handle Spill in Normal CellsHandle Text in Node Rows

Custom Merge Discusses about ways to customize the default merging behavior

Method 1 Use IComparer interfaceMethod 2 Override the GetMergedRange method

自動マージ

FlexGrid lets you enable automatic cell merging in the grid by setting the AllowMerging property to a value other than None Inaddition you need to set the AllowMerging property of each target row or column to true Merging occurs only if adjacent cellscontain the same non-empty string There is no method to force a pair of cells to merge The merging is done automaticallybased on the cell contents This feature makes it easy to provide merged views of sorted data where values in adjacent rowspresent repeated data

Free Auto-mergeFree auto-merge refers to merging of cells with just one pre-condition of having same values in adjacent cells To automaticallymerge the cells in a row or a column you simply need to set AllowMerging property of the C1FlexGrid class to Free and setAllowMerging property of the target row or column object to true

FlexGrid for WinForms

144 Copyright copy GrapeCity Inc All rights reserved

Below code shows how to apply free merging on a WinForms FlexGrid column

Restricted Auto-mergeIn most of the scenarios you would want the grid to merge the grid cells with same values only if cells above or in left directionare also merged This behavior is called restricted auto-merge and can be achieved by setting the C1FlexGridAllowMergingproperty to RestrictAll RestrictRows or RestrictCols This is required in addition to setting the AllowMerging property oftarget row or column to true

Use the code below to allow restricted auto-merging on a WinForms FlexGrid column

Merge Table HeadersMerging the header cells specially in case of multi-row header is another very common scenario used in grids and tables Tomerge the header cells you must set the C1FlexGridAllowMerging property to FixedOnly You must also set theAllowMerging property of designated row and columns to true In this case headers cells with same value merge together togive a simplified appearance

許可される結合の種類を指定しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFree 結合を許可する列を指定しますc1FlexGrid1Cols[2]AllowMerging = true

C

許可される結合の種類を指定しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFree

結合を許可する列を指定しますc1FlexGrid1Cols(2)AllowMerging = True

VBNET

結合を許可する列を指定しますc1FlexGrid1Cols[3]AllowMerging = true 左側のセルが結合されている場合にのみ列を結合しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumRestrictCols

C

結合を許可する列を指定しますc1FlexGrid1Cols(3)AllowMerging = True

左側のセルが結合されている場合にのみ列を結合しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumRestrictCols

VBNET

FlexGrid for WinForms

145 Copyright copy GrapeCity Inc All rights reserved

Following code demonstrates how to apply merging only on table headers of the WinForms FlexGrid

Custom Auto-mergeFlexGrid also provides a Custom option through AllowMerging enumeration In this case auto-merge is performed on cellrange collection provided using MergedRanges property of the C1FlexGrid class The custom auto-merge is performedindependent of cell content For instance below image shows the merging of two specified cell ranges despite of the differentcell values

固定の行と列の結合を許可しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

固定の行と列の結合を許可しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

FlexGrid for WinForms

146 Copyright copy GrapeCity Inc All rights reserved

Use the following code snippet to apply custom merge on the WinForms FlexGrid

結合のモードをアクティブにしますthisc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumCustom

いくつかのマージされた範囲を定義します 2つのセルは幅が広く1つのセルは高いですthisc1FlexGrid1MergedRangesAdd(2 2 2 3)

3つのセルは幅が広く3つのセルは高さですthisc1FlexGrid1MergedRangesAdd(5 2 7 4)

C

結合のモードをアクティブにしますMec1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumCustom

いくつかのマージされた範囲を定義します 2つのセルは幅が広く1つのセルは高いですMec1FlexGrid1MergedRangesAdd(2 2 2 3)

3つのセルは幅が広く3つのセルは高さですMec1FlexGrid1MergedRangesAdd(5 2 7 4)

VBNET

はみ出して表示されるセルの処理

In FlexGrid you can create the same behavior as excel for handling long text entries by spilling them into emptyadjacent cells This behavior not only helps you in handling long text entries of usual cells but also in displayingoutline nodes which are different from data rows This topic discusses these two scenarios in the following sectionsThese settings work on the grid level and does not need you to set AllowMerging property of specific row or column

Handle Spill in Normal CellsThis FlexGrid setting causes text that is too long to fit in a cell to spill into empty adjacent cells If you have a longentry in a cell and the adjacent cell is empty the entry spills onto the adjacent cells to occupy as much room as

FlexGrid for WinForms

147 Copyright copy GrapeCity Inc All rights reserved

needed This behavior can be achieved by setting the AllowMerging property to Spill For instance in the imagebelow long data strings from TestGroup column cells spill to the empty Flag column cells giving a better visibility ofdata while using the available space on the grid

Following code enables spilling of long text to adjacent empty cell in the WinForms FlexGrid

Handle Text in Node RowsThe Nodes setting is similar to Spill but only applies to outline nodes This setting is useful when data is organizedinto groups and the node rows contain information in a format different from the data rows For this you must setthe C1FlexGridAllowMerging property to Nodes

長いテキストを隣接する空のセルにこぼしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumSpill

C

長いテキストを隣接する空のセルにこぼしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumSpill

VBNET

FlexGrid for WinForms

148 Copyright copy GrapeCity Inc All rights reserved

Following code shows how to handle long text in node rows of the WinForms FlexGrid

ノード行の長いテキストを隣接する空のセルにスピルします c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumNodes

C

ノード行の長いテキストを隣接する空のセルにスピルしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumNodes

VBNET

カスタムのマージ

FlexGrid by default gives you enough options to merge in most common scenarios using AllowMerging propertyHowever there may be instances where you want to customize the merging options to get more out of your grid Youcan customize the default merging behavior in two ways

Method 1 Use IComparer InterfaceBy default the grid merges adjacent cells containing same non-null value In default scenario string comparisons arecase-sensitive and blanks are included However you can also merge cells using a case-insensitive comparison andtrimming blanks by writing a custom class that implements IComparer interface and assign it to CustomComparerproperty of the C1FlexGrid class

Method 2 Override the GetMergedRange MethodAnother way is to create a new class that derives from the C1FlexGrid class and overrides the GetMergedRangeand GetData methods to provide your own custom merging logic It merges the cells based on contextual

FlexGrid for WinForms

149 Copyright copy GrapeCity Inc All rights reserved

understanding of data in FlexGrid which is implemented through the overridden methods in the sample The belowexample demonstrates custom merging in timetable of each lecturer using the WinForms FlexGrid

public override CellRange GetMergedRange(int row int col bool clip) 結合のロジックで使用するID列のインデックスを保存します _colIndex = ColsIndexOf(LecturerID)

結合する時にカスタムデータを使用するようにフラグを設定します _doingMerge = true

基本クラスの結合のロジックを呼び出します(GetDataメソッドを使用してデータを取得します) CellRange cellRange = baseGetMergedRange(row col clip)

GetDataが通常どおりに動作するようにフラグをリセットします _doingMerge = false

結合された範囲を返します return cellRange

public override Object GetData(int row int col) 結合範囲を決定するためのデータを取得します ID列のコンテンツを追加して異なるIDの行のセルがマージされないようにします if (_doingMerge ampamp _colIndex gt -1 ampamp col = _colIndex) SystemDiagnosticsDebugWriteLine($rowcol) return baseGetDataDisplay(row col) + baseGetDataDisplay(row _colIndex)

C

FlexGrid for WinForms

150 Copyright copy GrapeCity Inc All rights reserved

For detailed implementation of more scenarios of custom merging see the product Projects named CustomMergeCustomMerge2 CustomMerge3 CustomMerge4

Note The abovementioned product samples are located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installingWinForms Edition using ComponentOneControlPanelexe

表示測定編集などするデータを取得します 基本クラスに通常どおり処理させます return baseGetData(row col)

Public Overrides Function GetMergedRange(ByVal row As Integer ByVal col As Integer ByVal clip As Boolean) As CellRange 結合のロジックで使用するID列のインデックスを保存します _colIndex = ColsIndexOf(LecturerID)

結合する時にカスタムデータを使用するようにフラグを設定します _doingMerge = True

基本クラスの結合のロジックを呼び出します(GetDataメソッドを使用してデータを取得します) Dim cellRange As CellRange = MyBaseGetMergedRange(row col clip)

GetDataが通常どおりに動作するようにフラグをリセットします _doingMerge = False

結合された範囲を返します Return cellRangeEnd Function

Public Overrides Function GetData(ByVal row As Integer ByVal col As Integer) As Object 結合範囲を決定するためのデータを取得します ID列のコンテンツを追加して異なるIDの行のセルがマージされないようにします If _doingMerge AndAlso _colIndex gt -1 AndAlso col ltgt _colIndex Then DebugWriteLine($rowcol) Return MyBaseGetDataDisplay(row col) + MyBaseGetDataDisplay(row _colIndex) End If

表示測定編集などするデータを取得します 基本クラスに通常どおり処理させます Return MyBaseGetData(row col)End Function

VBNET

FlexGrid for WinForms

151 Copyright copy GrapeCity Inc All rights reserved

グループ

Grouping refers to organizing the grid data into a hierarchical structure where rows with common column value aredisplayed as a group The feature also lets you expand or collapse the groups to facilitate easier analysis of grid data

In FlexGrid grouping can be achieved through code as well as through user interaction via column context menuand FlexGridGroupPanel control This topic discusses these ways and additional operations related to grouping

Grouping through CodeFlexGrid provides GroupDescriptions property to describe how data source items are grouped in the grid Thisproperty accepts the instance of any collection which implements IList interface (eg List) as its value The items of thecollection describe grouping using a property name as the criterion

Following code shows how to apply grouping in the WinForms FlexGrid through code

Grouping through Group Panel

CustomerIDでデータをグループ化しますc1FlexGrid1GroupDescriptions = new ListltGroupDescriptiongt() new GroupDescription(CustomerID)

C

CustomerIDでデータをグループ化しますc1FlexGrid1GroupDescriptions = New List(Of GroupDescription)() From New GroupDescription(CustomerID)

VBNET

FlexGrid for WinForms

152 Copyright copy GrapeCity Inc All rights reserved

FlexGrid also lets you create groups at runtime using an extension control named C1FlexGridGroupPanel which isprovided by the C1WinC1FlexGridGroupPanel assembly

To achieve grouping in FlexGrid at runtime add the C1FlexGridGroupPanel control to the form and bind it with thegrid to be bound using FlexGrid property of the C1FlexGridGroupPanel class Once a grid is bound to the grouppanel control you can drag and drop the columns to panel in order to group the grid by that column To create anested hierarchy of dragged columns you can drag multiple columns in the desired order You can also set themaximum number of groups allowed within FlexGrid using MaxGroups property of the C1FlexGridGroupPanel classBy default all the created groups appear in the expanded state To change this setting and display the groups incollapsed state by default you can set the AutoExpandAllGroups property to false The group panel control alsoprovides the Text property to display a string when no columns are dropped on the panel

Use the code below to apply grouping in WinForms FlexGrid through the FlexGridGroupPanel control

C1FlexGridGroupPanel c1FlexGridGroupPanel = new C1FlexGridGroupPanel()c1FlexGridGroupPanelBounds = new SystemDrawingRectangle(00 650 150)thisControlsAdd(c1FlexGridGroupPanel) C1FlexGridGroupPanelの一般プロパティを設定しますc1FlexGridGroupPanelFlexGrid = c1FlexGrid1c1FlexGridGroupPanelText = Drag the columns herec1FlexGridGroupPanelMaxGroups = 5c1FlexGridGroupPanelAutoExpandAllGroups = true

C

Dim c1FlexGridGroupPanel As C1FlexGridGroupPanel = New C1FlexGridGroupPanel() c1FlexGridGroupPanelBounds = New DrawingRectangle(0 0 650 150) MeControlsAdd(c1FlexGridGroupPanel)

VBNET

FlexGrid for WinForms

153 Copyright copy GrapeCity Inc All rights reserved

Grouping through Context MenuFlexGrid provides support for column context menu at run-time to facilitate quick actions related to columnoperations One of these context menu options is Group By This Column You can use this context menu option togroup the grid data by any of the columns at run-time Once grouping is applied you also get the Ungroup option toremove grouping To enable the column context menu you need to set ColumnContextMenuEnabled propertyprovided by the C1FlexGrid class to true By default this property is set to false

Grouping and MoreApart from the default features grouping in FlexGrid comes with many other options to give you ample flexibility tomeet your requirements

Use the SubtotalPosition property to change the position of group row which gets displayed above the groupby defaultSet the HideGroupedColumns property to true to hide the columns by which grid is groupedChange the format of group header by using the GroupHeaderFormat property By default the group row

C1FlexGridGroupPanelの一般プロパティを設定します c1FlexGridGroupPanelFlexGrid = c1FlexGrid1 c1FlexGridGroupPanelText = Drag the columns here c1FlexGridGroupPanelMaxGroups = 5 c1FlexGridGroupPanelAutoExpandAllGroups = True

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = true

C

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = True

VBNET

FlexGrid for WinForms

154 Copyright copy GrapeCity Inc All rights reserved

displays a string of namevalue formatSet the C1FlexGridAllowMerging property to AllowMergingEnumNodes to spill the long group headercontent into the adjacent empty cells For more information see Handle Text in Node RowsDisplay aggregate value of columns in group header by using Aggregate property of the Column classUse AllowSorting property to sort the groups based on their valuesUse the GridTreeStyle property to customize the appearance of outline tree that shows the grouping inFlexGrid For more information see Style the Tree Grid

FlexGrid for WinForms

155 Copyright copy GrapeCity Inc All rights reserved

集計

Summarizing data is one of the most important features of the grid where you can easily group the similar data andcalculate various types of aggregates such as Sum Average Count Max Min and more

In FlexGrid you can easily summarize data by using SubTotal method of the C1FlexGrid class It adds subtotal rows thatcontain aggregate data for the regular (non-subtotal) rows and also supports the hierarchical aggregates The method hasvarious overloads which gives you enough flexibility to deal with multiple summarizing related scenarios All theseoverloads have one parameter in common that is AggregateEnum which lets you set the type of aggregate you want toimplement Other parameters in various overloads let you set the outline level start and end column and column thatcontains values to be aggregated

Create SubtotalsBelow example demonstrates the use of SubTotal method in the WinForms FlexGrid for calculation of average aggregatebased on Score column

Style SubtotalsWhen the Subtotal method adds the rows with the aggregate information it automatically assigns in-built subtotal styles

グリッドに存在する既存の小計をすべてクリアしますc1FlexGrid1Subtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加しますc1FlexGrid1Subtotal(AggregateEnumAverage 1 3 3 4 Average for 0)

C

グリッドに存在する既存の小計をすべてクリアしますc1FlexGrid1Subtotal(AggregateEnumClear)

レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加しますc1FlexGrid1Subtotal(AggregateEnumAverage 1 3 3 4 Average for 0)

VBNET

FlexGrid for WinForms

156 Copyright copy GrapeCity Inc All rights reserved

to the new rows You can customize the appearance of the subtotal rows by changing the properties of the outline stylesin the designer with the Style Editor or using the code Below example demonstrates styling of subtotals at three levels inthe WinForms FlexGrid

Customize SubtotalsFlexGrid in addition to built-in aggregate options lets you create custom expressions in bound mode and use them assubtotals in groups along with aggregates You can specify the custom expressions for a column using GroupExpressionproperty of the Column class Below example demonstrates how to create a custom expression as a subtotal for Qualifiedcolumn of the WinForms FlexGrid

小計をレベル0でスタイル設定しますCellStyle s = c1FlexGrid1Styles[CellStyleEnumSubtotal0]sBackColor = ColorBlacksForeColor = ColorWhitesFont = new Font(c1FlexGrid1Font FontStyleBold) 小計をレベル1でスタイル設定しますs = c1FlexGrid1Styles[CellStyleEnumSubtotal1]sBackColor = ColorDarkBluesForeColor = ColorWhite

小計をレベル2でスタイル設定しますs = c1FlexGrid1Styles[CellStyleEnumSubtotal2]sBackColor = ColorDarkRedsForeColor = ColorWhitec1FlexGrid1AutoSizeCols()

C

Dim s As CellStyle = c1FlexGrid1Styles(CellStyleEnumSubtotal0) sBackColor = ColorBlack sForeColor = ColorWhite sFont = New Font(c1FlexGrid1Font FontStyleBold)

s = c1FlexGrid1Styles(CellStyleEnumSubtotal1) sBackColor = ColorDarkBlue sForeColor = ColorWhite

s = c1FlexGrid1Styles(CellStyleEnumSubtotal2) sBackColor = ColorDarkRed sForeColor = ColorWhite c1FlexGrid1AutoSizeCols()

VBNET

FlexGrid for WinForms

157 Copyright copy GrapeCity Inc All rights reserved

public void CustomizeSubTotal(C1FlexGrid c1FlexGrid1) ListltGroupDescriptiongt grps = new ListltGroupDescriptiongt() 列「Course」のグループを作成します GroupDescription grp = new GroupDescription(Course ListSortDirectionDescending true) grpsAdd(grp) 上記のグループに従ってFlexGridをグループ化します c1FlexGrid1GroupDescriptions = grps カスタムの計算式を使用してFlexGridに新しい列を追加します var column = c1FlexGrid1ColsAdd() columnName = Qualified columnDataType = typeof(object) columnCaption = Qualified(gt5000) columnAllowEditing = false columnExpression = [Attendance] [Score] GroupExpression の実装 c1FlexGrid1Cols[Score]GroupExpression = =Average([Score]) c1FlexGrid1Cols[Attendance]GroupExpression = =Average([Attendance]) c1FlexGrid1Cols[Qualified]GroupExpression = =iif(Average([Score][Attendance])lt5000falsetrue) c1FlexGrid1AutoSizeCols()

C

Public Sub CustomizeSubTotal(ByVal c1FlexGrid1 As C1FlexGrid) Dim grps As List(Of GroupDescription) = New List(Of GroupDescription)() 列「Course」のグループを作成します Dim grp As GroupDescription = New GroupDescription(Course ListSortDirectionDescending True) grpsAdd(grp)

上記のグループに従ってFlexGridをグループ化します c1FlexGrid1GroupDescriptions = grps

カスタムの計算式を使用してFlexGridに新しい列を追加します Dim column = c1FlexGrid1ColsAdd()

VBNET

FlexGrid for WinForms

158 Copyright copy GrapeCity Inc All rights reserved

columnName = Qualified columnDataType = GetType(Object) columnCaption = Qualified(gt5000) columnAllowEditing = False columnExpression = [Attendance] [Score]

GroupExpression の実装 c1FlexGrid1Cols(Score)GroupExpression = =Average([Score]) c1FlexGrid1Cols(Attendance)GroupExpression = =Average([Attendance]) c1FlexGrid1Cols(Qualified)GroupExpression = =iif(Average([Score][Attendance])lt5000falsetrue) c1FlexGrid1AutoSizeCols()End Sub

FlexGrid for WinForms

159 Copyright copy GrapeCity Inc All rights reserved

ツリーグリッド

OverviewOne of the unique and popular features of the FlexGrid control is the ability to add hierarchical grouping to regulardata grid and display it in a tree like structure called Tree Grid The Tree Grid control is very similar to the one you seein a TreeView control It shows an indented structure with collapse or expand icon next to each node row so the usercan expand and collapse the outline to see the desired level of detail by clicking on the nodes

Although you can create simple outline trees using FlexGrid grouping Tree Grid helps you implement more advanceduse cases such as displaying customer and order details In a usual grid showing such data it is difficult to see thedetails of each customer and order In such case you can create a Tree Grid to group the data in a hierarchicalstructure for better view and accessibility of information

Quick BindingLoading data in a Tree Grid is exactly the same as loading in a regular grid If the data source is available at designtime you can use the Visual Studio Property Window to set the grids DataSource property of the C1FlexGrid class andbind the grid to the data without writing even a single line of code For detailed steps see Bound Mode

You can also set the DataSource property through code Following code shows how to use the DataSource propertyto populate data in the WinForms Tree Grid

private void Bound_Node_Load(object sender EventArgs e) FlexGridを連結します BindGrid(_gridBound)

public void BindGrid(C1FlexGrid grid) DataTable _dt = new DataTable() データを取得します var fields = Country City SalesPerson Quantity ExtendedPrice var sql = stringFormat(SELECT 0 FROM Invoices ORDER BY 0 fields)

C

FlexGrid for WinForms

160 Copyright copy GrapeCity Inc All rights reserved

The code uses an OleDbDataAdapter to fill a DataTable with data then assigns datatable to DataSource property ofthe grid To turn this regular grid in a Tree grid you need to insert the node rows which is discussed in the sectionbelow

Create Nodes (Bound and Unbound Mode)To create a Tree Grid FlexGrid introduces a concept of Node rows These rows do not contain regular data and aresimply header rows under which similar data is grouped just like nodes in a usual TreeView control You can alsodefine the hierarchy of these nodes by setting the Level property These nodes can be collapsed and expanded to hideor show the data they contain The Tree Grid can be displayed in any column defined by the GridTreeColumnproperty By default this property is set to -1 which causes the tree not to be displayed at all

Bound Mode (Using InsertNode Method)

You can create node rows using InsertNode method of the RowCollection class which inserts a new node row at a

var da = new OleDbDataAdapter(sql GetConnectionString()) daFill(_dt) グリッドにデータを連結します gridDataSource = _dt ExtendedPrice 列を書式設定します gridCols[ExtendedPrice]Format = n2

static string GetConnectionString() string path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) + ComponentOne SamplesCommon string conn = provider=microsoftjetoledb40data source=0c1nwindmdb return stringFormat(conn path)

Private Sub Bound_Node_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを連結します BindGrid(_gridBound) End Sub

Public Sub BindGrid(ByVal grid As C1FlexGrid) Dim _dt As DataTable = New DataTable() データを取得します Dim fields = Country City SalesPerson Quantity ExtendedPrice Dim sql = StringFormat(SELECT 0 FROM Invoices ORDER BY 0 fields) Dim da = New OleDbDataAdapter(sql GetConnectionString()) daFill(_dt) グリッドにデータを連結します gridDataSource = _dt ExtendedPrice 列を書式設定します gridCols(ExtendedPrice)Format = n2 End Sub

Private Shared Function GetConnectionString() As String Dim path As String = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) amp ComponentOne SamplesCommon Dim conn As String = provider=microsoftjetoledb40data source=0c1nwindmdb Return StringFormat(conn path) End Function

VBNET

FlexGrid for WinForms

161 Copyright copy GrapeCity Inc All rights reserved

specified index This is the low-level way of inserting totals and building outlines

The GroupBy method used here inserts node rows by grouping identical values To obtain a Node object you caneither use return value of the InsertNode method or retrieve the node for an existing row using the IsNode property

Use the following code to create nodes using InsertNode method in the bound WinForms Tree Grid

private void Bound_Node_Load(object sender EventArgs e) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) GroupBy(_gridBound Country 0) GroupBy(_gridBound City 1) public void CreateTree(C1FlexGrid grid) gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)

void GroupBy(C1FlexGrid grid string columnName int level) レベル0でグループのスタイル設定します CellStyle s0 = gridStylesAdd(Group0) s0BackColor = ColorGray s0ForeColor = ColorWhite s0Font = new Font(gridFont FontStyleBold) レベル1でグループのスタイル設定します CellStyle s1 = gridStylesAdd(Group1) s1BackColor = ColorLightGray s1ForeColor = ColorBlack object current = null for (int r = gridRowsFixed r lt gridRowsCount r++)

C

FlexGrid for WinForms

162 Copyright copy GrapeCity Inc All rights reserved

if (gridRows[r]IsNode) var value = grid[r columnName] if (objectEquals(value current)) 値が変更されました ノードを挿入します gridRowsInsertNode(r level) if (level == 0) gridRows[r]Style = s0 else if (level == 1) gridRows[r]Style = s1 最初のスクロール可能な列にグループ名を表示します grid[r gridColsFixed] = value 現在の値を更新します current = value gridAutoSizeCols()

Private Sub Bound_Node_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) GroupBy(_gridBound Country 0) GroupBy(_gridBound City 1)End Sub

Public Sub CreateTree(ByVal grid As C1FlexGrid) gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)End Sub

Private Sub GroupBy(ByVal grid As C1FlexGrid ByVal columnName As String ByVal level As Integer) レベル0でグループのスタイル設定します Dim s0 As CellStyle = gridStylesAdd(Group0) s0BackColor = ColorGray s0ForeColor = ColorWhite s0Font = New Font(gridFont FontStyleBold) レベル1でグループのスタイル設定します Dim s1 As CellStyle = gridStylesAdd(Group1) s1BackColor = ColorLightGray s1ForeColor = ColorBlack Dim current As Object = Nothing Dim r As Integer = gridRowsFixed

While r And lt gridRowsCount End While

r += 1

If True Then

If Not gridRows(r)IsNode Then Dim value = grid(r columnName)

VBNET

FlexGrid for WinForms

163 Copyright copy GrapeCity Inc All rights reserved

The code also calls the AutoSizeCols method to ensure that the column is wide enough to accommodate the TreeGrid Finally it calls the GridTreeShow method to display the nodes

Also the Node class provides following methods and properties based on TreeView object model which can be usedto manage the Tree Grid

Checked Gets or sets the check state of cell defined by NodeRow and GridTreeColumnCollapsedExpanded Gets or sets collapsed or expanded state of the nodeData Gets or sets value in the cell defined by NodeRow and GridTreeColumnImage Gets or sets image in the cell defined by NodeRow and GridTreeColumnLevel Gets or sets node level in the Tree Grid

You can also explore the outline structure using the following properties and methods

Children Gets number of child nodes under this nodeGetCellRange Gets the CellRange object that described range of rows that belong to this nodeGetNode Gets the node that has a given relationship to this node (parent first child next sibling and so on)Nodes Gets a node array containing child nodes of this node

Bound Mode (Using Subtotal Method)

In bound mode another way to create nodes is using the Subtotal method To make the Tree Grid really useful thenode rows must include summary information for the data they contain

If you create Tree Grid using the Subtotal method the subtotals are added automatically The method scans theentire grid and automatically inserts node rows with optional subtotals at locations where the grid data changes

This is the high-level way of inserting totals and building outlines

If Not ObjectEquals(value current) Then 値が変更されました ノードを挿入します gridRowsInsertNode(r level)

If level = 0 Then gridRows(r)Style = s0 ElseIf level = 1 Then gridRows(r)Style = s1 End If

最初のスクロール可能な列にグループ名を表示します grid(r gridColsFixed) = value 現在の値を更新します current = value End If End IfEnd If gridAutoSizeCols()End Sub

FlexGrid for WinForms

164 Copyright copy GrapeCity Inc All rights reserved

The first parameter of the Subtotal method is AggregateEnum enumeration which calculates various types ofaggregates like Sum Average Count Max Min and others In the code below Subtotal method of the C1FlexGridclass is used for creating nodes in a bound WinForms Tree Grid

private void SubtotalNode_Bound_Load(object sender EventArgs e) FlexGridを取得します BindGrid(_gridBound) shows Tree in Bound FlexGrid CreateTree(_gridBound) 連結されたFlexGridに小計を作成します CreateSubTotal(_gridBound)public void BindGrid(C1FlexGrid grid) DataTable dt = new DataTable() dtColumnsAdd(ID typeof(int)) dtColumnsAdd(Name typeof(string)) dtColumnsAdd(Course typeof(string)) dtColumnsAdd(Score typeof(int)) dtColumnsAdd(Attendance typeof(int)) dtColumnsAdd(Country typeof(string)) サンプルデータ dtRowsAdd(1 Helen Bennett ComputerScience 79 84 Spain) dtRowsAdd(2 Ana Trujillo Biology 78 87 Mexico) dtRowsAdd(3 Antonio Moreno Aeronautics 71 70 Spain) dtRowsAdd(4 Paolo Accorti Biology 74 63 Spain) dtRowsAdd(5 Elizabeth Brown ComputerScience 80 93 Mexico) dtRowsAdd(6 Jaime Yorres Biology 61 48 Spain) dtRowsAdd(7 Yvonne Moncada Aeronautics 85 78 Mexico) dtRowsAdd(8 Martine Ranceacute Aeronautics 67 81 Spain) dtRowsAdd(9 Sergio Gutieacuterrezy ComputerScience 62 58 Mexico) dtRowsAdd(10 Thomas Hardy Aeronautics 94 92 Mexico) dtRowsAdd(11 Patricio Simpson Aeronautics 46 52 Spain) dtRowsAdd(12 Maria Anders ComputerScience 85 73 Spain) gridDataSource = dt gridAutoSizeCols() (gridDataSource as DataTable)DefaultViewSort = Course

C

FlexGrid for WinForms

165 Copyright copy GrapeCity Inc All rights reserved

FlexGridでツリーを作成しますpublic void CreateTree(C1FlexGrid grid) gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1) gridAutoSizeCols()public void CreateSubTotal(C1FlexGrid grid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加します gridSubtotal(AggregateEnumAverage 1 3 3 4 Average for 0) gridAutoSizeCols()

Private Sub SubtotalNode_Bound_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) Creates Subtotal(s) in Bound FlexGrid CreateSubTotal(_gridBound)End Sub

Public Sub BindGrid(ByVal grid As C1FlexGrid) Dim dt As DataTable = New DataTable() dtColumnsAdd(ID GetType(Integer)) dtColumnsAdd(Name GetType(String)) dtColumnsAdd(Course GetType(String)) dtColumnsAdd(Score GetType(Integer)) dtColumnsAdd(Attendance GetType(Integer)) dtColumnsAdd(Country GetType(String))

サンプルデータ dtRowsAdd(1 Helen Bennett ComputerScience 79 84 Spain) dtRowsAdd(2 Ana Trujillo Biology 78 87 Mexico) dtRowsAdd(3 Antonio Moreno Aeronautics 71 70 Spain) dtRowsAdd(4 Paolo Accorti Biology 74 63 Spain) dtRowsAdd(5 Elizabeth Brown ComputerScience 80 93 Mexico) dtRowsAdd(6 Jaime Yorres Biology 61 48 Spain) dtRowsAdd(7 Yvonne Moncada Aeronautics 85 78 Mexico) dtRowsAdd(8 Martine Ranceacute Aeronautics 67 81 Spain) dtRowsAdd(9 Sergio Gutieacuterrezy ComputerScience 62 58 Mexico) dtRowsAdd(10 Thomas Hardy Aeronautics 94 92 Mexico) dtRowsAdd(11 Patricio Simpson Aeronautics 46 52 Spain) dtRowsAdd(12 Maria Anders ComputerScience 85 73 Spain) gridDataSource = dt gridAutoSizeCols() TryCast(gridDataSource DataTable)DefaultViewSort = CourseEnd Sub

FlexGridでツリーを作成しますPublic Sub CreateTree(ByVal grid As C1FlexGrid) gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)

VBNET

FlexGrid for WinForms

166 Copyright copy GrapeCity Inc All rights reserved

Unbound Mode (Using Subtotal Method)

The Subtotal method is a very convenient and flexible way to create a tree grid It has a number of overloads thatallow you to specify which columns are to be grouped on and totaled on by index or by name whether to include acaption in the node rows that it inserts how to perform the grouping and so on

In the code below Subtotal method of the C1FlexGrid class is used for creating nodes in an unbound WinForms TreeGrid

gridAutoSizeCols()End Sub

Public Sub CreateSubTotal(ByVal grid As C1FlexGrid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加します gridSubtotal(AggregateEnumAverage 1 3 3 4 Average for 0) gridAutoSizeCols()End Sub

private void Unbound_Subtotal_Load(object sender EventArgs e) 連結されていないFlexGridにデータを追加します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) 連結されていないFlexGridに小計を作成します CreateSubTotal(_gridUnbound) public void PopulateGrid(C1FlexGrid grid) グリッドにデータを入力します Random rnd = new Random() gridRowsCount = 14 grid[0 1] = Direction grid[0 2] = Region CellRange rg = gridGetCellRange(0 3 0 gridColsCount - 1) rgData = Rnd

C

FlexGrid for WinForms

167 Copyright copy GrapeCity Inc All rights reserved

for (int r = 1 r lt gridRowsCount r++) grid[r 0] = r grid[r 1] = (r lt 7) Inbound Outbound grid[r 2] = (r lt 3) North (r lt 7) South (r lt 10) East West for (int c = 3 c lt gridColsCount c++) grid[r c] = rndNext(1000) gridCols[c]Format = gridAutoSizeCols()

FlexGridでツリーを作成しますprivate void ShowTreeNode(C1FlexGrid grid) ツリーを作成します gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols()

Creates Subtotal in FlexGridpublic void CreateSubTotal(C1FlexGrid grid) Clears any existing subtotal(s) present in grid gridSubtotal(AggregateEnumClear) for (int c = 3 c lt gridColsCount c++) Adds subtotals in grid gridSubtotal(AggregateEnumSum 0 -1 c Grand Total) gridSubtotal(AggregateEnumSum 2 2 c Total for 0) gridAutoSizeCols()

Private Sub Unbound_Subtotal_Load(ByVal sender As Object ByVal e As EventArgs) 連結されていないFlexGridにデータを追加します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) 連結されていないFlexGridに小計を作成します CreateSubTotal(_gridUnbound) End Sub

Public Sub PopulateGrid(ByVal grid As C1FlexGrid) グリッドにデータを入力します Dim rnd As Random = New Random() gridRowsCount = 14 grid(0 1) = Direction grid(0 2) = Region Dim rg As CellRange = gridGetCellRange(0 3 0 gridColsCount - 1) rgData = Rnd Dim r As Integer = 1

While r And lt gridRowsCount End While

VBNET

FlexGrid for WinForms

168 Copyright copy GrapeCity Inc All rights reserved

r += 1

If True Then grid(r 0) = r grid(r 1) = r And lt 7 Inbound Outbound grid(r 2) = r And lt 3 North r And lt 7 South r And lt 10 East West Dim c As Integer = 3

While c And lt gridColsCount End While

c += 1

If True Then grid(r c) = rnd[Next](1000) gridCols(c)Format = End If End If

gridAutoSizeCols() End Sub

FlexGridでツリーを作成します Private Sub ShowTreeNode(ByVal grid As C1FlexGrid) ツリーを作成しますFlexGridでツリーを作成します gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols() End Sub

FlexGridで小計を作成します Public Sub CreateSubTotal(ByVal grid As C1FlexGrid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) Dim c As Integer = 3

While c And lt gridColsCount End While

c += 1

If True Then グリッドに小計を追加します gridSubtotal(AggregateEnumSum 0 -1 c Grand Total) gridSubtotal(AggregateEnumSum 2 2 c Total for 0) End If

gridAutoSizeCols() End Sub

FlexGrid for WinForms

169 Copyright copy GrapeCity Inc All rights reserved

Unbound Mode(Using IsNode Property)

In an unbound grid you can turn regular rows into node rows by simply setting the IsNode property to true If youtry to turn a regular data bound row into a node it causes the grid to throw an exception

Use the following code to create nodes using IsNode property in an unbound WinForms Tree Grid

private void Unbound_Row_Load(object sender EventArgs e) 連結されていないFlexGridにデータを入力します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound)

private void PopulateGrid(C1FlexGrid grid) FlexGridをリセットします gridRowsCount = 0 gridColsCount = 2 string fileName = testxml xmlドキュメントをロードします XmlDocument xdoc = new XmlDocument() xdocLoad(fileName) XMLドキュメントを読み取りFlexGridのノードとして表示します ShowNode(_gridUnbound xdocChildNodes[1] 0) gridAutoSizeCols() FlexGridでツリーを作成しますprivate void ShowTreeNode(C1FlexGrid grid) ツリーを作成します gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols()

FlexGridにxmlノードを追加しますprivate void ShowNode(C1FlexGrid grid XmlNode node int level)

C

FlexGrid for WinForms

170 Copyright copy GrapeCity Inc All rights reserved

コメントノードをスキップします if (nodeNodeType == XmlNodeTypeComment) return 読み取りxmlノードの新しい行を追加します int row = gridRowsCount gridRowsAdd() グリッドのセルにxmlノードデータを割り当てます grid[row 0] = nodeName xmlノードに子が1つしかないかどうかを確認します if (nodeChildNodesCount == 1) グリッドのセルにノード値を設定します grid[row 1] = nodeInnerText 新しい行をノードにします gridRows[row]IsNode = true gridRows[row]NodeLevel = level ノードに子がある場合はそれらも取得します if (nodeChildNodesCount gt 1) 子を取得するために再帰します foreach (XmlNode child in nodeChildNodes) ShowNode(_gridUnbound child level + 1)

Private Sub Unbound_Row_Load(ByVal sender As Object ByVal e As EventArgs) 連結されていないFlexGridにデータを入力します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) End Sub

Private Sub PopulateGrid(ByVal grid As C1FlexGrid) FlexGridをリセットします gridRowsCount = 0 gridColsCount = 2 Dim fileName As String = testxml xmlドキュメントをロードします Dim xdoc As XmlDocument = New XmlDocument() xdocLoad(fileName) XMLドキュメントを読み取りFlexGridのノードとして表示します ShowNode(_gridUnbound xdocChildNodes(1) 0) gridAutoSizeCols() End Sub

FlexGridでツリーを作成します Private Sub ShowTreeNode(ByVal grid As C1FlexGrid) ツリーを作成します gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols() End Sub

FlexGridにxmlノードを追加します Private Sub ShowNode(ByVal grid As C1FlexGrid ByVal node As XmlNode ByVal level As Integer) コメントノードをスキップします If nodeNodeType Is XmlNodeTypeComment Then Return

VBNET

FlexGrid for WinForms

171 Copyright copy GrapeCity Inc All rights reserved

読み取りxmlノードの新しい行を追加します Dim row As Integer = gridRowsCount gridRowsAdd() グリッドのセルにxmlノードデータを割り当てます grid(row 0) = nodeName

xmlノードに子が1つしかないかどうかを確認します If nodeChildNodesCount = 1 Then グリッドのセルにノード値を設定します grid(row 1) = nodeInnerText End If

新しい行をノードにします gridRows(row)IsNode = True gridRows(row)NodeLevel = level

ノードに子がある場合はそれらも取得します If nodeChildNodesCount And gt Then End If

1

If True Then

子を取得するために再帰します For Each child As XmlNode In nodeChildNodes ShowNode(_gridUnbound child level + 1) Next End If End Sub

ノードの操作

Tree Grid not only allows you to present the data in a structured form but it also supports performing variousoperations with the nodes You can add delete move and fetch nodes by using various methods provided bythe Node class

FlexGrid for WinForms

172 Copyright copy GrapeCity Inc All rights reserved

Add NodeYou can add a node at a specific position in the Tree Grid using AddNode method of the Node class This appends anew node row to the collection The method takes NodeTypeEnum enumeration as its argument which lets youspecify a node with respect to another given node

The code below shows how to add a node in the WinForms Tree Grid at a specific location

private void cmbAdd_SelectionChangeCommitted(object sender SystemEventArgs e) 現在の行ノードを取得します Node nd = flexRows[flexRow]Node ユーザーの要求に応じて相対を追加します (could be a child or a sibling) ndAddNode((NodeTypeEnum)(cmbAddSelectedIndex + 2) cmbAddText) flexFocus()

C

Private Sub cmbAdd_SelectionChangeCommitted(ByVal sender As Object ByVal e As EventArgs) 現在の行ノードを取得します Dim nd As Node = flexRows(flexRow)Node ユーザーの要求に応じて相対を追加します (could be a child or a sibling) ndAddNode(CType(cmbAddSelectedIndex + 2 NodeTypeEnum) cmbAddText)

VBNET

FlexGrid for WinForms

173 Copyright copy GrapeCity Inc All rights reserved

Delete NodeYou can delete a selected node from the Tree Grid using RemoveNode method of the Node class

Following code demonstrates how to delete a node from the WinForms Tree Grid

Move NodeThe Tree Grid allows you to move the node rows to a new position using Move method of the Node class Themethod takes NodeMoveEnum enumeration as an argument which lets you specify the direction in which node hasto be moved

Use the code below to move a node of the WinForms Tree Grid to a new position

flexFocus()End Sub

private void btnDelete_Click(object sender SystemEventArgs e) 現在のノードを取得します Node nd = null if ( flexRowsCount gt 0 ampamp flexRow gt= 0 ampamp flexRow lt flexRowsCount) nd = flexRows[flexRow]Node if (nd = null) FlexGridからノードを削除します ndRemoveNode() flexFocus()

C

Private Sub btnDelete_Click(ByVal sender As Object ByVal e As EventArgs) 現在のノードを取得します Dim nd As Node = Nothing

If flexRowsCount gt 0 AndAlso flexRow gt= 0 AndAlso flexRow lt flexRowsCount Then nd = flexRows(flexRow)Node End If

If nd IsNot Nothing Then FlexGridからノードを削除します ndRemoveNode() flexFocus() End IfEnd Sub

VBNET

private void btnMove_Click(object sender SystemEventArgs e) 現在の行のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択した動きを適用します

C

FlexGrid for WinForms

174 Copyright copy GrapeCity Inc All rights reserved

Select NodesIn Tree Grid you can select the nodes to perform different operations using GetNode method of the Node class Themethod takes a parameter called NodeTypeEnum enumeration which specifies a node with respect to another givennode

The code below specifies how to fetch a specific node of the WinForms Tree Grid and show it in selected state

(これにより選択したノードが移動します) if (sender == btnMoveOut) ndMove(NodeMoveEnumOut) else if (sender == btnMoveIn) ndMove(NodeMoveEnumIn) else if (sender == btnMoveUp) ndMove(NodeMoveEnumUp) else if (sender == btnMoveDown) ndMove(NodeMoveEnumDown) else if (sender == btnMoveFirst) ndMove(NodeMoveEnumFirst) else if (sender == btnMoveLast) ndMove(NodeMoveEnumLast) ノードがまだ表示されていることを確認します ndEnsureVisible() flexFocus()

Private Sub btnMove_Click(ByVal sender As Object ByVal e As EventArgs) 現在の行のノードを取得します Dim nd As Node = flexRows(flexRow)Node

ユーザーが選択した動きを適用します (これにより選択したノードが移動します) If sender Is btnMoveOut Then ndMove(NodeMoveEnumOut) ElseIf sender Is btnMoveIn Then ndMove(NodeMoveEnum[In]) ElseIf sender Is btnMoveUp Then ndMove(NodeMoveEnumUp) ElseIf sender Is btnMoveDown Then ndMove(NodeMoveEnumDown) ElseIf sender Is btnMoveFirst Then ndMove(NodeMoveEnumFirst) ElseIf sender Is btnMoveLast Then ndMove(NodeMoveEnumLast) End If

ノードがまだ表示されていることを確認します ndEnsureVisible() flexFocus()End Sub

VBNET

private void cmbSelect_SelectionChangeCommitted(object sender SystemEventArgs e) 現在の行のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択したノードを取得します nd = ndGetNode((NodeTypeEnum)cmbSelectSelectedIndex) 失敗した場合はメッセージを表示します if (nd == null) MessageBoxShow(Cant find + cmbSelectText + for this node) return ノードを選択しそれが表示されていることを確認します(スクロールして表示します)

C

FlexGrid for WinForms

175 Copyright copy GrapeCity Inc All rights reserved

Expand and Collapse NodesYou can expand and collapse all nodes in your Tree Grid application using the Collapsed property of Node class asshown in the code below This feature makes it convenient to navigate through node headers as a group whenrequired

Following code shows how to expand and collapse nodes of the WinForms Tree Grid

ndSelect() ndEnsureVisible() flexFocus()

Private Sub cmbSelect_SelectionChangeCommitted(ByVal sender As Object ByVal e As EventArgs) 現在の行のノードを取得します Dim nd As Node = flexRows(flexRow)Node ユーザーが選択したノードを取得します nd = ndGetNode(CType(cmbSelectSelectedIndex NodeTypeEnum))

失敗した場合はメッセージを表示します If nd Is Nothing Then MessageBoxShow(Cant find amp cmbSelectText amp for this node) Return End If

ノードを選択しそれが表示されていることを確認します(スクロールして表示します) nd[Select]() ndEnsureVisible() flexFocus()End Sub

VBNET

foreach (Row row in flexRowsCastltRowgt()Where(rw =gt rwIsNode == true)) Node node = rowNode nodeCollapsed = false

foreach (Row row in flexRowsCastltRowgt()Where(rw =gt rwIsNode == true)) Node node = rowNode nodeCollapsed = true

C

For Each row As Row In flexRowsCast(Of Row)()Where(Function(rw) rwIsNode = True) Dim node As Node = rowNode nodeCollapsed = False Next

For Each row As Row In flexRowsCast(Of Row)()Where(Function(rw) rwIsNode = True) Dim node As Node = rowNode nodeCollapsed = True Next

VBNET

FlexGrid for WinForms

176 Copyright copy GrapeCity Inc All rights reserved

Drag and Drop NodesIn Tree Grid you can drag and drop a selected node to a specific position by handling the MouseUp MouseDownand MouseMove events

The code below lets the user drag and drop nodes of the WinForms Tree Grid

private void flex_MouseDown(object sender MouseEventArgs e) m_DragInfocheckDrag = false 左ボタンを押すと移動しません ドラッグするマウスの追跡を開始します if (eButton = MouseButtonsLeft) return if (chkDragChecked || m_DragInfodragging) return if (flexMouseRow lt flexRowsFixed || flexMouseCol = 0) return 現在の行とマウスの位置を保存します m_DragInforow = flexRow m_DragInfomouseDown = new Point(eX eY) チェックを開始します m_DragInfocheckDrag = true

private void flex_MouseMove(object sender MouseEventArgs e) チェックしてユーザーが許容範囲を超えた場合はドラッグを開始します if (m_DragInfocheckDrag || eButton = MouseButtonsLeft) return if (MathAbs(eX - m_DragInfomouseDownX) + MathAbs(eY - m_DragInfomouseDownY) lt= DRAGTOL) return フラグを更新します m_DragInfodragging = true Sets cursor and highlight node CellStyle cs = flexStyles[SourceNode] flexCursor = CursorsNoMove2D flexSetCellStyle(m_DragInforow 0 cs) ここにドロップできるかどうかを確認します Cursor c = (NoDropHere()) CursorsNo CursorsNoMove2D if (c = flexCursor) flexCursor = c private bool NoDropHere() カーソルの下の行は無効です if (flexMouseRow lt flexRowsFixed) return true カーソルの下の列が無効です if (flexMouseCol lt flexColsFixed) return true if (flexGetDataDisplay(flexRow 0) == SKU) return true return false private void flex_MouseUp(object sender MouseEventArgs e) マウスが再び下がるまでチェックしないでください m_DragInfocheckDrag = false Not dragging were done if (m_DragInfodragging) return ドラッグを停止します m_DragInfodragging = false flexSetCellStyle(m_DragInforow 0 (CellStyle)null) flexCursor = CursorsDefault ドロップが許可されているかどうかをテストします

C

FlexGrid for WinForms

177 Copyright copy GrapeCity Inc All rights reserved

if (NoDropHere()) return ノードを新しい親ノードに移動します Node ndSrc = flexRows[m_DragInforow]Node Node ndDst = flexRows[flexRow]Node ndSrcMove(NodeMoveEnumChildOf ndDst) ndSrcSelect()

internal struct DRAGINFO public bool dragging 現在ドラッグ中 public bool checkDrag 現在マウスをチェックしてドラッグを開始しています public int row ドラッグされている行のインデックス public Point mouseDown マウスダウンの位置

Private Sub flex_MouseDown(ByVal sender As Object ByVal e As MouseEventArgs) m_DragInfocheckDrag = False 左ボタンを押すと移動しません ドラッグするマウスの追跡を開始します If eButton IsNot MouseButtonsLeft Then Return If Not chkDragChecked OrElse m_DragInfodragging Then Return If flexMouseRow lt flexRowsFixed OrElse flexMouseCol ltgt 0 Then Return 現在の行とマウスの位置を保存します m_DragInforow = flexRow m_DragInfomouseDown = New Point(eX eY) チェックを開始します m_DragInfocheckDrag = True End Sub

Private Sub flex_MouseMove(ByVal sender As Object ByVal e As MouseEventArgs) チェックしてユーザーが許容範囲を超えた場合はドラッグを開始します If Not m_DragInfocheckDrag OrElse eButton IsNot MouseButtonsLeft Then Return If MathAbs(eX - m_DragInfomouseDownX) + MathAbs(eY - m_DragInfomouseDownY) lt= DRAGTOL Then Return フラグを更新します m_DragInfodragging = True カーソルを設定しノードを強調表示します Dim cs As CellStyle = flexStyles(SourceNode) flexCursor = CursorsNoMove2D flexSetCellStyle(m_DragInforow 0 cs) ここにドロップできるかどうかを確認します Dim c As Cursor = If((NoDropHere()) CursorsNo CursorsNoMove2D) If c IsNot flexCursor Then flexCursor = c End Sub

Private Function NoDropHere() As Boolean カーソルの下の行は無効です If flexMouseRow lt flexRowsFixed Then Return True カーソルの下の列が無効です If flexMouseCol lt flexColsFixed Then Return True If flexGetDataDisplay(flexRow 0) Is SKU Then Return True Return False End Function

Private Sub flex_MouseUp(ByVal sender As Object ByVal e As MouseEventArgs) マウスが再び下がるまでチェックしないでください m_DragInfocheckDrag = False If Not m_DragInfodragging Then Return ドラッグを停止します m_DragInfodragging = False

VBNET

FlexGrid for WinForms

178 Copyright copy GrapeCity Inc All rights reserved

flexSetCellStyle(m_DragInforow 0 CType(Nothing CellStyle)) flexCursor = Cursors[Default] ドロップが許可されているかどうかをテストします If NoDropHere() Then Return ノードを新しい親ノードに移動します Dim ndSrc As Node = flexRows(m_DragInforow)Node Dim ndDst As Node = flexRows(flexRow)Node ndSrcMove(NodeMoveEnumChildOf ndDst) ndSrc[Select]() End Sub

Friend Structure DRAGINFO Public dragging As Boolean 現在ドラッグ中 Public checkDrag As Boolean 現在マウスをチェックしてドラッグを開始しています Public row As Integer ドラッグされている行のインデックス Public mouseDown As Point マウスダウンの位置 End Structure

データの操作

In Tree Grid just like a usual grid you can also perform various operations at data level such as sorting and retainingthe changes

SortingTo apply sorting in Tree Grid you can select the parent node and sort the child nodes using Sort Method of the NodeClass You can specify the sorting order by using the SortFlags enumeration

Following code applies sorting on the WinForms Tree Grid

FlexGrid for WinForms

179 Copyright copy GrapeCity Inc All rights reserved

Retain the ChangesSo far we have discussed how to create trees and totals using the high-level Subtotal method as well as lower-level InsertNode and Aggregate methods

At this point it is important to remember that the Tree Grid is created based on the data but is not bound to it in anyway and is not automatically maintained when there are changes to the grid or to the data

For example if the user modifies a value in the column the subtotals will not be automatically updated If the usersorts the grid it refreshes the data and the subtotals disappear

There are two common ways to maintain the Tree Grid

1 Prevent the user from making any changes that would invalidate the tree This is the easiest option You can setthe grids AllowEditing AllowDragging and AllowSorting properties to false and prevent any changes thatwould affect the tree

2 Update the tree when there are changes to the data or to the grid You can attach handlers to thegrids AfterDataRefresh AfterSort and AfterEdit events and re-generate the outline appropriately

The second option is usually more interesting as it provides a quick and simple tool for dynamic data analysis Thisapproach is illustrated by a product sample Analyze shipped with the FlexGrid control The sample creates an initialoutline and allows users to reorder the columns When the column order changes the sample automatically re-sortsthe data and re-creates the outline

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing

private void btnSort_Click(object sender SystemEventArgs e) 現在のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択した並べ替えを適用します (これにより選択したノードの子が並べ替えられます) if (sender == btnSortAscending) ndSort(SortFlagsAscending) else ndSort(SortFlagsDescending) 完了 flexFocus()

C

Private Sub btnSort_Click(ByVal sender As Object ByVal e As EventArgs) 現在のノードを取得します Dim nd As Node = flexRows(flexRow)Node

ユーザーが選択した並べ替えを適用します (これにより選択したノードの子が並べ替えられます) If sender Is btnSortAscending Then ndSort(SortFlagsAscending) Else ndSort(SortFlagsDescending) End If

完了 flexFocus()End Sub

VBNET

FlexGrid for WinForms

180 Copyright copy GrapeCity Inc All rights reserved

WinForms Edition using ComponentOneControlPanelexe

In Create Nodes section we also learnt about implementing GroupBy method that inserts node rows groupingidentical values on a given column The code scans all the columns skipping existing node rows so it can be called toadd several levels of nodes and keeps track of the current value for the column being grouped on When the currentvalue changes a node row is inserted showing the new group name in the first scrollable column

However there are some challenges to maintain the grouping like the method assumes that data is sorted accordingto the outline structure Also the GroupBy method may insert rows which would cause the grid to flicker To avoidthis you would normally set the Redraw property to false before making the updates and set it back to true whendone

The DeferRefresh class is a simple utility that sets the grids Redraw property to false and restores its original valuewhen it is disposed This ensures that Redraw is properly restored even when exceptions happen during the updatesThe BindGrid method ensures that the grid is sorted in the order required by our outline structure

ツリーグリッドのカスタマイズ

FlexGrid allows you to customize Tree Grid by styling as well as by using various elements like checkboxes toexpandcollapse nodes or images as node icons A customized Tree Grid can make the outline tree nodes look moredistinctive and structured making it visually appealing and more understandable

Style Tree GridStyling a Tree Grid is similar to styling the FlexGrid control The Tree property returns a reference to a GridTree objectthat exposes several methods and properties used to customize the Tree Grid Following is the list of some commonlyused properties

Column Gets or sets the index of the column that contains the outline tree Setting this property to -1 causesthe outline tree to be hidden from the usersIndent Gets or sets the indent in pixels between adjacent node levels Higher indent levels cause the tree tobecome widerStyle Gets or sets the type of outline tree to display Use this property to determine whether the tree shouldinclude a button bar at the top to allow users to collapseexpand the entire tree whether lines andor symbolsshould be displayed and whether lines should be displayed connecting the tree to data rows as well as noderowsLineColor Gets or sets the color of the connecting linesLineStyle Gets or sets the style of the connecting lines

For more information on styling the tree grid see Styling and Appearance topic in FlexGrid documentation

Display Tree with CheckBoxesTo create a custom Tree Grid with checkbox and images you need to first initialize FlexGrid for creating Tree Grid andthen add nodes to the tree by using AddNode method of the RowCollection class

Now to implement checkboxes in Tree Grid you need to maintain the checkboxes in parent and child nodes Thismethod uses Checked property of the Node class which defines whether to show a checkbox for the node or not

FlexGrid for WinForms

181 Copyright copy GrapeCity Inc All rights reserved

The code below shows how to display checkboxes on tree nodes of the WinForms Tree Grid

void c1FlexGrid1_CellChecked(object sender C1WinC1FlexGridRowColEventArgs e) すべての子にチェック値を適用します var node = thisc1FlexGrid1Rows[eRow]Node UpdateCheckChildren(node) 親にチェック値を適用します UpdateCheckParent(node)

void UpdateCheckChildren(C1WinC1FlexGridNode node) var checkState = nodeChecked foreach (C1WinC1FlexGridNode child in nodeNodes) childChecked = checkState UpdateCheckChildren(child)

void UpdateCheckParent(C1WinC1FlexGridNode node) このノードの親を取得します var parent = nodeParent if (parent = null)

C

FlexGrid for WinForms

182 Copyright copy GrapeCity Inc All rights reserved

チェックされたチェックされていない子をカウントします int cntChecked = 0 int cntUnchecked = 0 int cntGrayed = 0 foreach (C1WinC1FlexGridNode child in parentNodes) switch (childChecked) case C1WinC1FlexGridCheckEnumChecked cntChecked++ break case C1WinC1FlexGridCheckEnumUnchecked cntUnchecked++ break case C1WinC1FlexGridCheckEnumGrayed cntGrayed++ break 親のチェック状態を更新します if (cntGrayed gt 0 || (cntChecked gt 0 ampamp cntUnchecked gt 0)) parentChecked = C1WinC1FlexGridCheckEnumGrayed else if (cntChecked gt 0 ampamp cntUnchecked == 0) parentChecked = C1WinC1FlexGridCheckEnumChecked else if (cntUnchecked gt 0 ampamp cntChecked == 0) parentChecked = C1WinC1FlexGridCheckEnumUnchecked 祖父も更新します UpdateCheckParent(parent)

Private Sub c1FlexGrid1_CellChecked(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) すべての子にチェック値を適用します Dim node = Mec1FlexGrid1Rows(eRow)Node UpdateCheckChildren(node) 親にチェック値を適用します UpdateCheckParent(node) End Sub

Private Sub UpdateCheckChildren(ByVal node As C1WinC1FlexGridNode) Dim checkState = nodeChecked

For Each child As C1WinC1FlexGridNode In nodeNodes childChecked = checkState MeUpdateCheckChildren(child) Next End Sub

Private Sub UpdateCheckParent(ByVal node As C1WinC1FlexGridNode) このノードの親を取得します Dim parent = nodeParent

If parent IsNot Nothing Then チェックされたチェックされていない子をカウントします

VBNET

FlexGrid for WinForms

183 Copyright copy GrapeCity Inc All rights reserved

Display Tree with ImagesTo add the images as your Tree Grid node icons you can use the AddImageFolder method for creating nodes relatedto files and assigning images to the nodes

Dim cntChecked As Integer = 0 Dim cntUnchecked As Integer = 0 Dim cntGrayed As Integer = 0

For Each child As C1WinC1FlexGridNode In parentNodes

Select Case childChecked Case C1WinC1FlexGridCheckEnumChecked cntChecked += 1 Case C1WinC1FlexGridCheckEnumUnchecked cntUnchecked += 1 Case C1WinC1FlexGridCheckEnumGrayed cntGrayed += 1 End Select Next

親のチェック状態を更新します If cntGrayed gt 0 OrElse cntChecked gt 0 AndAlso cntUnchecked gt 0 Then parentChecked = C1WinC1FlexGridCheckEnumGrayed ElseIf cntChecked gt 0 AndAlso cntUnchecked = 0 Then parentChecked = C1WinC1FlexGridCheckEnumChecked ElseIf cntUnchecked gt 0 AndAlso cntChecked = 0 Then parentChecked = C1WinC1FlexGridCheckEnumUnchecked End If

祖父も更新します UpdateCheckParent(parent) End If End Sub

FlexGrid for WinForms

184 Copyright copy GrapeCity Inc All rights reserved

Use the code below to display images or icons along with nodes of the WinForms Tree Grid

void AddImageFolder(string path int level) int cnt = 0 try ディレクトリ内のすべてのファイルをループします foreach (string file in DirectoryGetFiles(path)) ファイルごとにノードを作成しFlexGridに追加します var node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(file) 画像をノードに割り当てるためのコード ShowImage(node file) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt++ if (cnt gt 20) break catch try パスのすべてのサブディレクトリをループします foreach (string subPath in DirectoryGetDirectories(path))

C

FlexGrid for WinForms

185 Copyright copy GrapeCity Inc All rights reserved

ファイルごとにノードを作成しFlexGridに追加します var node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(subPath) 画像をノードに割り当てるためのコード ShowImage(node subPath) 現在のディレクトリのサブディレクトリファイルをトラバースします AddImageFolder(subPath level + 1) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt++ if (cnt gt 20) break catch

Private Sub AddImageFolder(ByVal path As String ByVal level As Integer) Dim cnt As Integer = 0

Try

ディレクトリ内のすべてのファイルをループします For Each file As String In DirectoryGetFiles(path) ファイルごとにノードを作成しFlexGridに追加します Dim node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(file)

画像をノードに割り当てるためのコード ShowImage(node file) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt += 1 If cnt gt 20 Then Exit For Next

Catch End Try

Try

パスのすべてのサブディレクトリをループします For Each subPath As String In DirectoryGetDirectories(path) ファイルごとにノードを作成しFlexGridに追加します Dim node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(subPath) 画像をノードに割り当てるためのコード ShowImage(node subPath) 現在のディレクトリのサブディレクトリファイルをトラバースします AddImageFolder(subPath level + 1) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt += 1 If cnt gt 20 Then Exit For Next

Catch End TryEnd Sub

VBNET

FlexGrid for WinForms

186 Copyright copy GrapeCity Inc All rights reserved

The above code uses a custom method called ShowImage to set the image for nodes based on its file extensions

public void ShowImage(C1WinC1FlexGridNode node string path) パスからファイル拡張子を取得します string extension = PathGetExtension(path) パスがファイルに属している場合 if (extension = ) ファイル拡張子に基づいてノードの画像を設定します switch (extension) case txt nodeImage = PropertiesResourcesTxt break case resx nodeImage = PropertiesResourcesTxt break case licx nodeImage = PropertiesResourcesTxt break case cs nodeImage = PropertiesResourcesTxt break case vb nodeImage = PropertiesResourcesTxt break case exe nodeImage = PropertiesResourcesExe break case dll nodeImage = PropertiesResourcesDll break case sln nodeImage = PropertiesResourcesVS break case csproj nodeImage = PropertiesResourcesVS break case bmp nodeImage = PropertiesResourcesImg break case png nodeImage = PropertiesResourcesImg break case gif nodeImage = PropertiesResourcesVideo break case accdb nodeImage = PropertiesResourcesAccess break default nodeImage = PropertiesResourcesUnknown break それ以外のパスはディレクトリフォルダに属しています else nodeImage = PropertiesResourcesFolder

C

FlexGrid for WinForms

187 Copyright copy GrapeCity Inc All rights reserved

Public Sub ShowImage(ByVal node As C1WinC1FlexGridNode ByVal path As String) パスからファイル拡張子を取得します Dim extension As String = PathGetExtension(path)

パスがファイルに属している場合 If Not Equals(extension ) Then

ファイル拡張子に基づいてノードの画像を設定します Select Case extension Case txt nodeImage = PropertiesResourcesTxt Case resx nodeImage = PropertiesResourcesTxt Case licx nodeImage = PropertiesResourcesTxt Case cs nodeImage = PropertiesResourcesTxt Case vb nodeImage = PropertiesResourcesTxt Case exe nodeImage = PropertiesResourcesExe Case dll nodeImage = PropertiesResourcesDll Case sln nodeImage = PropertiesResourcesVS Case csproj nodeImage = PropertiesResourcesVS Case bmp nodeImage = PropertiesResourcesImg Case png nodeImage = PropertiesResourcesImg Case gif nodeImage = PropertiesResourcesVideo Case accdb nodeImage = PropertiesResourcesAccess Case Else nodeImage = PropertiesResourcesUnknown それ以外のパスはディレクトリフォルダに属しています End Select Else nodeImage = PropertiesResourcesFolder End IfEnd Sub

VBNET

FlexGrid for WinForms

188 Copyright copy GrapeCity Inc All rights reserved

クリップボード

FlexGrid provides flexibility to perform various clipboard operations such as cut copy and paste on the editable griddata To enable automatic handling of common clipboard keys you need to set the AutoClipboard property to trueThe property handles following clipboard operations and their corresponding keys

Copy CTRL+C Ctrl+INS

Cut CTRL+X SHIFT+DEL

Paste CTRL+V SHIFT+INS

Delete DEL

The abovementioned clipboard operations do not have any affect on the styles and images and only work on gridheaders and data You can choose which part of the selected content to copy out of row header column headerand data by using the ClipboardCopyMode property When a datamap or multicolumn combobox exists in thecopied range only the display value is copied Also note that hidden cells are also copied when copying a cellrange To exclude hidden cells from copying see Exclude Hidden Cells

The code below demonstrates how to enable clipboard operations in the WinForms FlexGrid

Clipboard Operations through CodeYou can also perform clipboard operations through code The example below shows how to perform copying andpasting operations on button click

Use the code below to perform the clipboard operations through code in the WinForms FlexGrid

キーボードからクリップボード操作を有効にします c1FlexGrid1AutoClipboard = true データとすべてのヘッダーをコピーするようにコピーモードを設定します c1FlexGrid1ClipboardCopyMode = C1WinC1FlexGridClipboardCopyModeEnumDataAndAllHeaders

C

キーボードからクリップボード操作を有効にしますc1FlexGrid1AutoClipboard = True

データとすべてのヘッダーをコピーするようにコピーモードを設定しますc1FlexGrid1ClipboardCopyMode = C1WinC1FlexGridClipboardCopyModeEnumDataAndAllHeaders

VBNET

private void CopyButton_Click(object sender EventArgs e) クリップボードにコピーするグリッドのデータのみをコピーできるようにします c1FlexGrid1ClipboardCopyMode = ClipboardCopyModeEnumDataOnly

Clipプロパティに改行コードを追加しクリップボードに設定します ClipboardSetDataObject(c1FlexGrid1Clip + r) MessageBoxShow($Copied Range [c1FlexGrid1Rowc1FlexGrid1Col]-[c1FlexGrid1RowSelc1FlexGrid1ColSel])

C

FlexGrid for WinForms

189 Copyright copy GrapeCity Inc All rights reserved

Exclude Hidden CellsIn FlexGrid by default hidden cells are also copied when copying a cell range through keyboard operations enabledusing the AutoClipboard property However you can exclude the hidden rows and columns by using the code below

Following code shows how you can exclude the hidden cells from clipboard operations performed on the WinFormsTree Grid

private void PasteButton_Click(object sender EventArgs e) クリップボードのテキストを取得します IDataObject data = ClipboardGetDataObject() if (dataGetDataPresent(DataFormatsText)) string str1 str2 クリップボードからデータを取得します str1 = (string)dataGetData(DataFormatsText)

クリップボードから最後の行のフィードコードを削除します str2 = str1Remove(str1Length - 1 1)

範囲を選択してデータを貼り付けます c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col c1FlexGrid1RowsCount - 1 c1FlexGrid1ColsCount - 1 true) c1FlexGrid1Clip = str2 c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col)

Private Sub CopyButton_Click(ByVal sender As Object ByVal e As EventArgs) クリップボードにコピーするグリッドのデータのみをコピーできるようにします c1FlexGrid1ClipboardCopyMode = ClipboardCopyModeEnumDataOnly

Clipプロパティに改行コードを追加しクリップボードに設定します ClipboardSetDataObject(c1FlexGrid1Clip amp MicrosoftVisualBasicConstantsvbCr) MessageBoxShow($Copied Range [c1FlexGrid1Rowc1FlexGrid1Col]-[c1FlexGrid1RowSelc1FlexGrid1ColSel])End Sub

Private Sub PasteButton_Click(ByVal sender As Object ByVal e As EventArgs) クリップボードのテキストを取得します Dim data As IDataObject = ClipboardGetDataObject()

If dataGetDataPresent(DataFormatsText) Then Dim str1 str2 As String クリップボードからデータを取得します str1 = CStr(dataGetData(DataFormatsText))

クリップボードから最後の行のフィードコードを削除します str2 = str1Remove(str1Length - 1 1)

範囲を選択してデータを貼り付けます c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col c1FlexGrid1RowsCount - 1 c1FlexGrid1ColsCount - 1 True) c1FlexGrid1Clip = str2 c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col) End If

VBNET

C

FlexGrid for WinForms

190 Copyright copy GrapeCity Inc All rights reserved

列を非表示にしますc1FlexGrid1Cols[2]Visible = falsec1FlexGrid1AutoClipboard = true

次にCtrl + Cを押す前に非表示の列を含むいくつかのセルを選択しますprivate void c1FlexGrid1_KeyDown_1(object sender KeyEventArgs e) [Ctrl + C]でコピーします if ((eControl == true) ampamp (eKeyCode == KeysC)) 自動処理が行われないためキー入力を無効にします eHandled = true 選択したセル範囲のCellRangeオブジェクトを取得します C1WinC1FlexGridCellRange cr cr = c1FlexGrid1Selection

string StrCopy = for (int i = crr1 i lt= crr2 i++) if (c1FlexGrid1Rows[i]Visible == true) for (int j = crc1 j lt= crc2 j++) if (c1FlexGrid1Cols[j]Visible == true) StrCopy = StrCopy + c1FlexGrid1[i j]ToString() if (j = crc2) StrCopy = StrCopy + t StrCopy = StrCopy + n クリップボードに設定します ClipboardSetDataObject(StrCopy) MessageBoxShow(Copied data n + StrCopy)

列を非表示にします c1FlexGrid1Cols(2)Visible = False c1FlexGrid1AutoClipboard = True

次にCtrl + Cを押す前に非表示の列を含むいくつかのセルを選択しますPrivate Sub c1FlexGrid1_KeyDown_1(ByVal sender As Object ByVal e As KeyEventArgs)

[Ctrl + C]でコピーします If eControl = True AndAlso eKeyCode = KeysC Then 自動処理が行われないためキー入力を無効にします eHandled = True 選択したセル範囲のCellRangeオブジェクトを取得します Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1Selection Dim StrCopy =

VBNET

FlexGrid for WinForms

191 Copyright copy GrapeCity Inc All rights reserved

For i = crr1 To crr2

If c1FlexGrid1Rows(i)Visible = True Then For j = crc1 To crc2

If c1FlexGrid1Cols(j)Visible = True Then StrCopy = StrCopy amp c1FlexGrid1(i j)ToString()

If j ltgt crc2 Then StrCopy = StrCopy amp MicrosoftVisualBasicConstantsvbTab End If End If Next

StrCopy = StrCopy amp MicrosoftVisualBasicConstantsvbLf End If Next クリップボードに設定します ClipboardSetDataObject(StrCopy) MessageBoxShow(Copied data amp MicrosoftVisualBasicConstantsvbLf amp StrCopy) End IfEnd Sub

FlexGrid for WinForms

192 Copyright copy GrapeCity Inc All rights reserved

保存ロードと印刷

FlexGrid provides various built-in options so that you can easily save a grid and its content in a text excel or an XML file You can even load these saved filesto another grid or can save it as backup of a particular state of the grid You can also save the grid image in your desired format Not just this you can alsoprint the grid or selected areas of the grid if you need to have a hard copy This topic discusses various options related save load and print available in thegrid

Topic Content

Save Discusses about how to save the grid and its contents in different formats

Save as Text FileSave as Excel FileSave as XMLSave as Image

Load Discusses about how to load grid content from various file formats

Load from Text FileLoad from Excel FileLoad from DatabaseLoad from XML

Print Discusses about how to print the grid and other print related options

Print GridPrint OptionsCustomize Print Preview Dialog

保存

FlexGrid provides various methods to save the grid in the desired format such as text excel xml and image formatsThis feature is enabled through an assembly named C1WinC1FlexGridImportExportdll hence you need to addreference to this assembly to save the grid

Save as Text FileTo save grid content as a text file you can use the SaveGrid method of the Extensions class The method hasparameters that let you choose delimiter encoding and also lets you specify which portion of grid should be savedThe resulting text files can later be loaded back into the control or into other applications that support comma or tab-delimited files such as Microsoft Excel

Following code shows how to save content of the WinForms FlexGrid as a text file

private void btnSaveTxt_Click(object sender EventArgs e) c1FlexGrid1SaveGrid(ExportedGridtxt FileFormatEnumTextComma FileFlagsAsDisplayed | FileFlagsIncludeFixedCells)

C

Private Sub btnSaveTxt_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1SaveGrid(ExportedGridtxt FileFormatEnumTextComma FileFlagsAsDisplayed Or FileFlagsIncludeFixedCells)End Sub

VBNET

FlexGrid for WinForms

193 Copyright copy GrapeCity Inc All rights reserved

Save as Excel FileTo save grid as an excel file you can use the abovementioned SaveGrid method and simply set the format parameterto FileFormatEnumExcel You dont need to have Microsoft Excel installed on your computer However SaveGridmethod can only save the data in a workbook with single worksheet

To get an additional control over how you save your data to an excel file you can use the SaveExcel method insteadIn this case the process of saving excel files converts most data types and formatting information including row andcolumn dimensions fonts colors formats and cell alignment However some other features such as frozen andmerged cells images data maps and cell borders are not translated while converting to an excel file

Use the code below to save the WinForms FlexGrid as an Excel file

Save as XMLTo serialize grid contents into an XML document you can simply call WriteXML method of the C1FlexGrid class andparse path of the XML document as a parameter The method serializes all grid contents into the Xml documentincluding the data stored in the cells row and column properties styles and images Objects of custom types storedin the grid are also serialized as long as they have an associated SystemComponentModelTypeConverter thatprovides conversions to and from string

Below code demonstrates how to save contents of the WinForms FlexGrid to an XML document

Save as ImageTo save a grid as an image you can create the grid image using CreateImage method of the C1FlexGrid class andsave that image object at the specified path You can also specify a cell range or pass a cell range object as itsparameter to save a specific portion of the grid as an image

Use the code below to save the WinForms FlexGrid as an image

private void btnSaveExcl_Click(object sender EventArgs e) c1FlexGrid1SaveExcel(ExportedGridxlsx FileFlagsAsDisplayed | FileFlagsIncludeFixedCells)

C

Private Sub btnSaveExcl_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1SaveExcel(ExportedGridxlsx FileFlagsAsDisplayed Or FileFlagsIncludeFixedCells)End Sub

VBNET

private void btnSaveXML_Click(object sender EventArgs e) c1FlexGrid1WriteXml(ExportedGridxml)

C

Private Sub btnSaveXML_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1WriteXml(ExportedGridxml)End Sub

VBNET

FlexGrid for WinForms

194 Copyright copy GrapeCity Inc All rights reserved

private void btnSaveImg_Click(object sender EventArgs e) Image gridImage = c1FlexGrid1CreateImage() gridImageSave(ExportedGridpng)

C

Private Sub btnSaveImg_Click(ByVal sender As Object ByVal e As EventArgs) Dim gridImaage As Image = c1FlexGrid1CreateImage() gridImaageSave(ExportedGridpng)End Sub

VBNET

ロード

FlexGrid not only lets you save the grid to various formats but also lets you load data from various formats such textexcel XML or databases This feature is enabled through an assembly named C1WinC1FlexGridImportExportdllhence you need to add reference to this assembly to load the grid with data from these sources

Load from Text FileTo load data from a text file FlexGrid provides LoadGrid method of the Extensions class The method has parametersthat let you choose delimiter encoding etc You can also load text files saved using SaveGrid method When loadingtext files rows and columns are added to the grid if needed to accommodate the file contents The method supportsformats such as comma-delimited text files (CSV format) tab-delimited text files and even MS Excel files (xls)

Following code shows how to populate data in the WinForms FlexGrid by loading it from a text file

Load from Excel FileTo load grid from an excel file you can use the abovementioned LoadGrid method and simply set the formatparameter to FileFormatEnumExcel You dont need to have Microsoft Excel installed on your computer However theLoadGrid method can only load the data from first worksheet of a workbook

To get an additional control over how you load your data from an excel file you can use the LoadExcel methodinstead In this case the process of loading excel files converts most data types and formatting information includingrow and column dimensions fonts colors formats and cell alignment However there are still some exceptions Forexample the grid loads the values in excel cells but cannot load the underlying formulas Other features such asfrozen and merged cells images data maps and cell borders are not translated either

Use the code below to load contents in the WinForms FlexGrid from an excel file

private void btnLoadTxt_Click(object sender EventArgs e) c1FlexGrid1LoadGrid(ExportedGridtxt FileFormatEnumTextComma )

C

Private Sub btnLoadTxt_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1LoadGrid(ExportedGridtxt FileFormatEnumTextComma)End Sub

VBNET

FlexGrid for WinForms

195 Copyright copy GrapeCity Inc All rights reserved

Load from DatabaseTo load grid data from a database you can use the DataReader objects This process is different from data bindingwhich keeps a live connection between one or more controls and the underlying data source

Below code demonstrates how to load contents in the WinForms FlexGrid from the database

private void btnLoadExcl_Click(object sender EventArgs e) c1FlexGrid1LoadExcel(ExportedGridxlsx)

C

Private Sub btnLoadExcl_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1LoadExcel(ExportedGridxlsx)End Sub

VBNET

private void btnLoadDB_Click(object sender EventArgs e) DataReaderを準備します string strConn = data source=MYMACHINEinitial catalog=Northwind SystemDataSqlClientSqlConnection myConn = new SystemDataSqlClientSqlConnection(strConn) SystemDataSqlClientSqlCommand myCMD = new SystemDataSqlClientSqlCommand(SELECT FROM Employees myConn) myConnOpen() SystemDataSqlClientSqlDataReader myReader = myCMDExecuteReader()

DBスキーマからグリッド構造を構築します DataTable dt = myReaderGetSchemaTable() c1FlexGrid1ColsCount = 1 foreach (DataRow dr in dtRows) Column c =c1FlexGrid1ColsAdd() cCaption = cName = (string)dr[ColumnName] cDataType = (Type)dr[DataType]

グリッドにデータを入力します c1FlexGrid1RowsCount = 1 int row = 1 int cols = dtColumnsCount object[] v = (object[])ArrayCreateInstance(typeof(object) cols) while (myReaderRead()) myReaderGetValues(v) c1FlexGrid1AddItem(v row++ 1)

クリーンアップします c1FlexGrid1AutoSizeCols() myReaderClose() myConnClose()

C

FlexGrid for WinForms

196 Copyright copy GrapeCity Inc All rights reserved

Load from XMLTo deserialize grid contents from an XML document you can simply call ReadXML method of the C1FlexGrid classand parse path of the XML document as a parameter

Use the code below to load contents for the WinForms FlexGrid from an XML document

Private Sub btnLoadDB_Click(ByVal sender As Object ByVal e As EventArgs) DataReaderを準備します Dim strConn As String = data source=MYMACHINEinitial catalog=Northwind Dim myConn As New SqlClientSqlConnection(strConn) Dim myCMD As New SqlClientSqlCommand(SELECT FROM Employees myConn) myConnOpen() Dim myReader As SqlClientSqlDataReader = myCMDExecuteReader() DBスキーマからグリッド構造を構築します Dim dt As DataTable = myReaderGetSchemaTable() _flexColsCount = 1 Dim dr As DataRow For Each dr In dtRows Dim c As C1WinC1FlexGridColumn = _flexColsAdd() cCaption =(cName lt= CStr(dr(ColumnName))) cDataType = CType(dr(DataType) Type) Next dr グリッドにデータを入力します _flexRowsCount = 1 Dim row As Integer = 1 Dim cols As Integer = dtColumnsCount Dim v As Object() = CType(ArrayCreateInstance(GetType(Object) cols) Object()) While myReaderRead() myReaderGetValues(v) _flexAddItem(v row + 1 1) End While クリーンアップします _flexAutoSizeCols() myReaderClose() myConnClose()End Sub

VBNET

private void btnLoadXML_Click(object sender EventArgs e) c1FlexGrid1ReadXml(ExportedGridxml)

C

Private Sub btnLoadXML_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1ReadXml(ExportedGridxml)End Sub

VBNET

FlexGrid for WinForms

197 Copyright copy GrapeCity Inc All rights reserved

印刷

FlexGrid lets you print the grid and perform various basic and advanced print settings using its built-in methods andproperties

Print GridFlexGrid provides PrintGrid method of the C1FlexGrid class which lets you print the grid contents with some basicprinting options The method has an optional parameter PrintGridFlags that allows you to specify how to print thegrid such as its scaling mode and whether to display various print related dialog boxes You can also set text in headerand footer of the printed grid using this method

Following code shows how to use PrintGrid method to print the WinForms FlexGrid

Print OptionsTo set advanced printing options such as header and footer fonts page margins and page orientation you can usePrintParameter property of the C1FlexGrid class

Use the code below to print the WinForms FlexGrid with advanced print options

プレビューダイアログを表示し指定したヘッダとフッターでグリッドを印刷しますc1FlexGrid1PrintGrid(C1FlexGrid PrintGridFlagsFitToPageWidth | PrintGridFlagsShowPreviewDialog C1FlexGridtt + StringFormat(DateTimeNowToString() d) ttPage 0 of 1)

C

プレビューダイアログを表示し指定したヘッダとフッターでグリッドを印刷しますc1FlexGrid1PrintGrid(C1FlexGrid PrintGridFlagsFitToPageWidth Or PrintGridFlagsShowPreviewDialog C1FlexGrid amp vbTab amp vbTab amp StringFormat(DateNowToString() d) vbTab amp vbTab amp Page 0 of 1)

VBNET

FlexGrid for WinForms

198 Copyright copy GrapeCity Inc All rights reserved

Customize Print Preview DialogYou can customize the print preview dialog by using PrintPreviewDialog property of the GridPrinter class Theproperty can be accessed through PrintParameter property of the C1FlexGrid class The code below uses thePrintPreviewDialog property to display a maximized preview dialog with a custom caption

Below code demonstrates how to customize the print preview dialog of the WinForms FlexGrid

グリッドのPrintDocumentオブジェクトを取得しますSystemDrawingPrintingPrintDocument pd = c1FlexGrid1PrintParametersPrintDocument

ページを設定します(横向き15 左マージン)pdDefaultPageSettingsLandscape = truepdDefaultPageSettingsMarginsLeft = 150

ヘッダとフッタのフォントを設定しますc1FlexGrid1PrintParametersHeaderFont = new Font(Arial Black 14 FontStyleBold)c1FlexGrid1PrintParametersFooterFont = new Font(Arial Narrow 8 FontStyleItalic)

C

グリッドのPrintDocumentオブジェクトを取得しますDim pd As DrawingPrintingPrintDocument = c1FlexGrid1PrintParametersPrintDocument

ページを設定します(横向き15 左マージン)pdDefaultPageSettingsLandscape = TruepdDefaultPageSettingsMarginsLeft = 150

ヘッダとフッタのフォントを設定しますc1FlexGrid1PrintParametersHeaderFont = New Font(Arial Black 14 FontStyleBold)c1FlexGrid1PrintParametersFooterFont = New Font(Arial Narrow 8 FontStyleItalic)

VBNET

Form dlg = c1FlexGrid1PrintParametersPrintPreviewDialog as Form dlgText = Order Details dlgStartPosition = FormStartPositionCenterParent dlgWindowState = FormWindowStateMaximized c1FlexGrid1PrintGrid(Orders PrintGridFlagsShowPreviewDialog)

C

Dim dlg As Form = TryCast(c1FlexGrid1PrintParametersPrintPreviewDialog Form) dlgText = Order Details dlgStartPosition = FormStartPositionCenterParent dlgWindowState = FormWindowStateMaximized c1FlexGrid1PrintGrid(Orders PrintGridFlagsShowPreviewDialog)

VBNET

FlexGrid for WinForms

199 Copyright copy GrapeCity Inc All rights reserved

外観とスタイル設定

FlexGrid provides built-in visual styles as well as various design time and run time options so that you can style the grid and its elements as per the needsand appearance of your application The grid also provides style editors to let you customize appearance of your grid without writing a single line of codeFor more information about these editors and design time styling see Editors

This section discusses the built-in options provided by FlexGrid as well as various other ways to customize the appearance of grid and its elements

Topic Snapshot Content

Built-in Options Discusses about the available visual styles and built-in collection of styles

Visual StylesStyles Collection

Custom Styles Discusses how to create and apply the custom styles

Approach 1 Style an ObjectApproach 2 Create Re-usable Style

Customize Grid Discusses about customization at grid level

Set Alternate RowSet Background Image

Customize Border Discusses about customization of cell borders at row column or grid level

Customize Grid BorderCustomize RowColumn BorderCustomize Cell Border

Customize Text Discusses about various aspects of styling the grid text

Change FontSet MarginSet Vertical TextWrap TextDisplay Trimmed TextAlign TextApply Text Effect

Custom Glyphs Discusses about applying custom glyphs in the grid

組み込みオプション

Visual StylesFlexGrid provides six built-in visual styles so that you can easily customize the appearance of FlexGrid based on any ofthe Microsoft Office 2007 and 2010 themes These visual styles can be accessed through VisualStyle property ofthe C1FlexGrid class Apart from MS Office based visual styles you can also set this property to Custom and SystemWhen set to Custom the grid does not apply any visual styles and uses the grid properties for rendering When theproperty is set to System the grid renders its appearance based on current system settings

FlexGrid for WinForms

200 Copyright copy GrapeCity Inc All rights reserved

The property can be set using designer as well as through code To set the property at design time click smart tag toopen the C1FlexGrid Tasks menu and select a visual style from the VisualStyle combobox To apply visual style in theWinForms FlexGrid through code use the code below

Styles CollectionFlexGrid provides built-in collection of styles for predefined cell types and states such as normal cells fixed cellsfocused cells and so on You can use these built-in styles at design time as well as through code In design view youcan access these styles through the C1FlexGrid Style Editor which can be opened by clicking Styles option in Tasksmenu This collection of styles is represented by the CellStyleCollection class which can be accessed through Stylesproperty of the C1FlexGrid class Each built-in style is an object of the CellStyle class and holds various propertiessuch as BackColor DataType and Format

Following code shows how to use the styles from Styles collection of the WinForms FlexGrid

視覚スタイルをOffice2010Blueスキームに設定しますc1FlexGrid1VisualStyle = VisualStyleOffice2010Blue

C

視覚スタイルをOffice2010Blueスキームに設定しますc1FlexGrid1VisualStyle = VisualStyleOffice2010Blue

VBNET

組み込みセルスタイルNormalのプロパティを設定しますc1FlexGrid1Styles[Normal]BackColor = ColorAzurec1FlexGrid1Styles[Normal]ForeColor = ColorBlueViolet

固定セルの背景色を設定しますc1FlexGrid1Styles[Fixed]BackColor = ColorAqua

C

FlexGrid for WinForms

201 Copyright copy GrapeCity Inc All rights reserved

You can also add your own custom styles to Styles collection by using the Add method For more information abouthow to create and apply custom styles to grid cells see Custom Styles

組み込みセルスタイルNormalのプロパティを設定しますc1FlexGrid1Styles(Normal)BackColor = ColorAzurec1FlexGrid1Styles(Normal)ForeColor = ColorBlueViolet

固定セルの背景色を設定しますc1FlexGrid1Styles(Fixed)BackColor = ColorAqua

VBNET

カスタムのスタイル

Approach 1 Style an ObjectTo style a specific row column or a cell range of the WinForms FlexGrid you can use StyleNew property of the rowcolumn or cell range object

This approach is useful for styling a particular object when style is not expected to be reused To reuse a particularstyle you must create a style using the CellStyle object as discussed in the section below

Approach 2 Create Re-usable StyleIn this approach you can create a custom style as an object of CellStyle class and add it to the Styles collection usingthe Add method Then define its properties and apply it to a row column or cell range whenever required Asmentioned above this approach is very useful when you need to repeatedly use a particular style

Use the code below to create re-usable custom styles for your WinForms FlexGrid

特定の行にカスタムスタイルを適用しますc1FlexGrid1Rows[1]StyleNewBackColor = ColorAzurec1FlexGrid1Rows[1]StyleNewForeColor = ColorBlueViolet

C

特定の行にカスタムスタイルを適用しますc1FlexGrid1Rows(1)StyleNewBackColor = ColorAzurec1FlexGrid1Rows(1)StyleNewForeColor = ColorBlueViolet

VBNET

新しいスタイルを作成しスタイルコレクションに追加しますCellStyle cs = thisc1FlexGrid1StylesAdd(Custom) 新しいカスタムスタイルのプロパティを定義しますcsBackColor = ColorAzurecsForeColor = ColorBlueViolet

行にカスタムスタイルを適用しますc1FlexGrid1Rows[1]Style = cs

C

VBNET

FlexGrid for WinForms

202 Copyright copy GrapeCity Inc All rights reserved

新しいスタイルを作成しスタイルコレクションに追加しますDim cs As CellStyle = Mec1FlexGrid1StylesAdd(Custom)

新しいカスタムスタイルのプロパティを定義しますcsBackColor = ColorAzurecsForeColor = ColorBlueViolet

行にカスタムスタイルを適用しますc1FlexGrid1Rows(1)Style = cs

グリッドのカスタマイズ

FlexGrid also lets you customize overall look of the grid not to just increase its aesthetic value but also increases itsreadability You can add the alternate rows which make the grid more readable Also you can set image for instance awatermark or a company logo in background of the grid

Set Alternate RowTo set the alternate row color and styles in the grid you can use the built-in style Alternate either at design time orat runtime To apply style at design time you need to access the FlexGrid Style Editor and set properties for Alternatestyle

To apply alternate row style in the WinForms FlexGrid through code you need to use the CellStyle item Alternate ofthe CellStyleCollection class and set various properties for setting the alternate style

代替行の前色を設定します c1FlexGrid1Styles[Alternate]ForeColor = ColorWhite

代替行の背景色を設定します c1FlexGrid1Styles[Alternate]BackColor = ColorCadetBlue

C

FlexGrid for WinForms

203 Copyright copy GrapeCity Inc All rights reserved

Set Background Image in GridTo set the background image on a grid you can use the BackgroundImage property and assign the path of the imagefile to it Another property called BackgroundImageLayout property lets you choose whether and how to renderimage on the grid

Use the code below to set the background image on the WinForms FlexGrid

代替行の前色を設定しますc1FlexGrid1Styles(Alternate)ForeColor = ColorWhite

代替行の背景色を設定しますc1FlexGrid1Styles(Alternate)BackColor = ColorCadetBlue

VBNET

背景画像をグリッドに設定しますc1FlexGrid1BackgroundImage = ImageFromFile(CIMG-20190524-WA0037png)c1FlexGrid1BackgroundImageLayout = ImageLayoutStretch

C

背景画像をグリッドに設定しますc1FlexGrid1BackgroundImage = ImageFromFile(CIMG-20190524-WA0037png)c1FlexGrid1BackgroundImageLayout = ImageLayoutStretch

VBNET

境界線のカスタマイズ

The FlexGrid control lets you customize the border of grid row column and even cells by changing its style colordirection and so on

FlexGrid for WinForms

204 Copyright copy GrapeCity Inc All rights reserved

Customize Grid BorderTo customize border of the grid control you can use the BorderStyle property which accepts valuesfrom BorderStyleEnum provided by the C1WinFlexGridUtilBaseControls namespace

Following code shows how to customize border of the WinForms FlexGrid control

Customize RowColumn BorderTo customize the border style of a particular row or column you must access the Border item of CellStyle classusing StyleNew property and set its properties such as border style direction and color The grid controlprovides BorderStyleEnum as well as BorderDirEnum to set the border style and direction respectively

Use the below code to change border of rows or columns of the WinForms FlexGrid

Customize Cell BorderTo customize border of every cell in the grid you can access the built-in style Normal and set its border propertiesSimilarly you can change the style of specific types of cells such fixed or frozen by accessing their correspondingstyles from Styles collection

Below code lets you customize the border of normal cells of the WinForms FlexGrid

グリッドの境界線を3次元の境界線に変更しますc1FlexGrid1BorderStyle = C1WinC1FlexGridUtilBaseControlsBorderStyleEnumFixed3D

C

グリッドの境界線を3次元の境界線に変更しますc1FlexGrid1BorderStyle = C1WinC1FlexGridUtilBaseControlsBorderStyleEnumFixed3D

VBNET

最初の列の境界線スタイルを設定しますc1FlexGrid1Cols[1]StyleNewBorderStyle = BorderStyleEnumGroovec1FlexGrid1Cols[1]StyleNewBorderColor = ColorRedc1FlexGrid1Cols[1]StyleNewBorderDirection = BorderDirEnumVertical

最初の行の境界線スタイルを設定しますc1FlexGrid1Rows[1]StyleNewBorderStyle = BorderStyleEnumRaisedc1FlexGrid1Rows[1]StyleNewBorderColor = ColorBlue

C

最初の列の境界線スタイルを設定しますc1FlexGrid1Cols(1)StyleNewBorderStyle = BorderStyleEnumGroovec1FlexGrid1Cols(1)StyleNewBorderColor = ColorRedc1FlexGrid1Cols(1)StyleNewBorderDirection = BorderDirEnumVertical

最初の行の境界線スタイルを設定しますc1FlexGrid1Rows(1)StyleNewBorderStyle = BorderStyleEnumRaisedc1FlexGrid1Rows(1)StyleNewBorderColor = ColorBlue

VBNET

FlexGrid for WinForms

205 Copyright copy GrapeCity Inc All rights reserved

すべてのグリッドセルの境界線スタイルを設定しますc1FlexGrid1StylesNormalBorderStyle = BorderStyleEnumDouble

C

すべてのグリッドセルの境界線スタイルを設定しますc1FlexGrid1StylesNormalBorderStyle = BorderStyleEnumDouble

VBNET

テキストのカスタマイズ

FlexGrid lets you customize text in various ways such as changing its font margin orientation alignment effects and soon This topic caters to various aspects of text styling by taking a particular row object However if you wish to use anexisting built-in style or want to create your own custom style to re-use it see the corresponding topics

Change FontTo change font of text in a particular row or column object you can use Font property of its CellStyle Following codeshows how to change font of the WinForms FlexGrid row

カスタムスタイルを特定の行に適用しますc1FlexGrid1Rows[1]StyleNewFont = new Font(verdana 10 FontStyleUnderline)c1FlexGrid1Rows[0]StyleNewFont = new Font(verdana 10 FontStyleBold)

C

カスタムスタイルを特定の行に適用しますc1FlexGrid1Rows(1)StyleNewFont = new Font(verdana 10 FontStyleUnderline)c1FlexGrid1Rows(0)StyleNewFont = new Font(verdana 10 FontStyleBold)

VBNET

FlexGrid for WinForms

206 Copyright copy GrapeCity Inc All rights reserved

However if you want to change font of the whole grid you can set Font property of the C1FlexGrid class Followingcode shows how to change font of the entire WinForms FlexGrid

Set MarginTo set margin on text of a particular row or column you can set Margins property of the CellStyle Use the code belowto change margins in WinForms FlexGrid row

Set Vertical TextTo change the orientation and display a text as vertical text you can set TextDirection property of CellStyle of theobject Also to display the vertical text properly you may have to adjust height of the target cells depending upon thetext length Below code lets you set vertical text in the WinForms FlexGrid row

Wrap TextTo wrap a text which is longer than the available cell width you can set the WordWrap property of its CellStyle to trueFollowing code demonstrates how to apply text wrap in the WinForms FlexGrid row

グリッドの内容全体のフォントを変更しますc1FlexGrid1Font = new Font(verdana 10 FontStyleItalic)

C

グリッドの内容全体のフォントを変更しますc1FlexGrid1Font = New Font(verdana 10 FontStyleItalic)

VBNET

右側のマージンを設定しますc1FlexGrid1Rows[1]StyleNewMarginsRight = 10

C

右側のマージンを設定しますc1FlexGrid1Rows(1)StyleNewMarginsRight = 10

VBNET

行の内容のテキスト方向を設定しますc1FlexGrid1Rows[1]StyleNewTextDirection = TextDirectionEnumDown 行の高さを設定して垂直方向のテキストを表示しますc1FlexGrid1Rows[1]Height = 60

C

行の内容のテキスト方向を設定しますc1FlexGrid1Rows(1)StyleNewTextDirection = TextDirectionEnumDown

行の高さを設定して垂直方向のテキストを表示しますc1FlexGrid1Rows(1)Height = 60

VBNET

C

FlexGrid for WinForms

207 Copyright copy GrapeCity Inc All rights reserved

Display Trimmed TextTo display trimmed text when text is longer than the cell width set Trimming property of the style which takes its valuesfrom StringTrimming enumeration Use the code below to trim the long text to display ellipsis character in theWinForms FlexGrid row

Align TextYou can set the text alignment or position of the text with respect to cell by using the TextAlign property The propertyaccepts values from the TextAlignEnum enumeration

Use the code below to apply text alignment on the WinForms FlexGrid row

Apply Text EffectTo set various effects on the text you can use the TextEffect property which accepts its values from TextEffectEnumenumeration

Apply text on the WinForms FlexGrid row using the following code

セルの幅に応じて特定の行のテキストを折り返しますc1FlexGrid1Rows[1]StyleNewWordWrap = true

セルの幅に応じて特定の行のテキストを折り返しますc1FlexGrid1Rows(1)StyleNewWordWrap = True

VBNET

長いテキストをトリミングして最後に省略記号を表示しますc1FlexGrid1Rows[1]StyleNewTrimming = StringTrimmingEllipsisCharacter

C

長いテキストをトリミングして最後に省略記号を表示しますc1FlexGrid1Rows(1)StyleNewTrimming = StringTrimmingEllipsisCharacter

VBNET

テキストの配置を設定しますc1FlexGrid1Rows[1]StyleNewTextAlign = TextAlignEnumLeftCenter

C

テキストの配置を設定しますc1FlexGrid1Rows(1)StyleNewTextAlign = TextAlignEnumLeftCenter

VBNET

上げ表示するテキストを設定しますc1FlexGrid1Rows[1]StyleNewTextEffect = TextEffectEnumRaised

C

上げ表示するテキストを設定します c1FlexGrid1Rows(1)StyleNewTextAlign = TextAlignEnumLeftCenter

VBNET

FlexGrid for WinForms

208 Copyright copy GrapeCity Inc All rights reserved

カスタムのグリフ

FlexGrid lets you change the default glyph images used in the grid to indicate various actions such as column filteringand sorting This behavior of grid is exposed through GridGlyphs class which is a collection of images used by the gridto represent filtered state sorting order checkbox states and so on These images can be accessed through Glyphsproperty of the C1FlexGrid class which accepts values from GlyphEnum enumeration

Change the default glyphs used for filter editor and filtered column in the WinForms FlexGrid to a custom image usingthe code below

Note that setting this property to null restores the default glyph In order to hide a glyph you can set the Glyphproperty to a blank image

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilterEditor] = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilteredColumn] = ImageFromFile(filterico)

C

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilterEditor) = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilteredColumn) = ImageFromFile(filterico)

VBNET

FlexGrid for WinForms

209 Copyright copy GrapeCity Inc All rights reserved

永続的な状態

Grid persistence refers to saving the current state of the grid for later use and then restoring it back when needed Forinstance the user may apply grouping sorting filtering or some styling to the grid which he wants to use after fewmore operations or on opening the application again This behavior can be achieved by persisting the grids state

There are two steps to implement persistence of the grid state First we have to serialize the grid state and then werestore it In this topic we discuss how to persist the filtered sorted and grouped state of the FlexGrid control

You can implement persisting grid states by using XMLWriter and XMLReader class of the SystemXML namespace Tosave the grid state you can use the WriteStartElement method to write the specified start tag andWriteAttributeString method to write the filter sort and group attributes Finally call WriteEndElement method toclose the WriteStartElement method and save the state in the form of stream string or a file

Use the code below to serialize the state of WinForms FlexGrid to an XML file for later use

フィルタグループ並べ替えの定義をファイルに書き込みますprivate void WriteStateToXML(string filePath) using (XmlWriter writer = XmlWriterCreate(filePath)) writerWriteStartElement(FlexGrid) writerWriteStartElement(Definition ) writerWriteAttributeString(Filter flexGridFilterDefinition) writerWriteAttributeString(Sort flexGridSortDefinition) writerWriteAttributeString(Group flexGridGroupDefinition) writerWriteEndElement() writerWriteEndElement() writerFlush()

C

フィルタグループ並べ替えの定義をファイルに書き込みますPrivate Sub WriteStateToXML(ByVal filePath As String)

VBNET

FlexGrid for WinForms

210 Copyright copy GrapeCity Inc All rights reserved

To load the saved state back into the grid you can use the GetAttribute method of the object to read the filter sortand group attributes Then assign them to the FilterDefinition SortDefinition or GroupDefinition properties of theFlexGrid respectively

Use the code below to load saved state of the WinForms FlexGrid

Using writer = XmlWriterCreate(filePath) writerWriteStartElement(FlexGrid) writerWriteStartElement(Definition ) writerWriteAttributeString(Filter flexGridFilterDefinition) writerWriteAttributeString(Sort flexGridSortDefinition) writerWriteAttributeString(Group flexGridGroupDefinition) writerWriteEndElement() writerWriteEndElement() writerFlush() End UsingEnd Sub

保存したファイルからフィルタ並べ替えグループの定義を読み取りFlexGridに適用しますprivate void ReadStateXML(string filePath)

using (XmlReader reader = XmlReaderCreate(filePath)) readerReadToFollowing(Definition) flexGridSortDefinition = readerGetAttribute(Sort) flexGridFilterDefinition = readerGetAttribute(Filter) flexGridGroupDefinition = readerGetAttribute(Group) readerClose()

C

保存したファイルからフィルタ並べ替えグループの定義を読み取りFlexGridに適用しますPrivate Sub ReadStateXML(ByVal filePath As String) Using reader = XmlReaderCreate(filePath) readerReadToFollowing(Definition) flexGridSortDefinition = readerGetAttribute(Sort) flexGridFilterDefinition = readerGetAttribute(Filter) flexGridGroupDefinition = readerGetAttribute(Group) readerClose() End Using

VBNET

FlexGrid for WinForms

211 Copyright copy GrapeCity Inc All rights reserved

NET 5 リファレンス

FlexGrid for WinForms

212 Copyright copy GrapeCity Inc All rights reserved

NET 452 リファレンス

FlexGrid for WinForms

213 Copyright copy GrapeCity Inc All rights reserved

  • 目次
  • FlexGrid for WinForms
  • 主な特長
  • 機能比較
    • FlexGrid の比較
    • WinFormsグリッドの比較
      • クイックスタート
      • 設計時サポート
        • タスクメニュー
        • エディタ
          • データ
            • 非連結モード
            • 連結モード
              • 連結モードでの操作
                    • 基本操作
                    • ユーザー操作
                    • エディタ
                      • チェックボックス
                      • 数値
                      • 日付
                      • コンボボックス
                      • マスク
                      • マップリスト
                      • セルボタン
                        • 検証
                        • データ注釈
                        • スパークライン
                        • ヘッダとフッタ
                        • サイズ変更
                            • 基本操作
                            • ユーザー操作
                            • ヘッダ
                            • 行の詳細
                            • サイズ変更
                              • セル
                                • 基本操作
                                • セルの書式設定
                                  • グリッド
                                    • 基本操作
                                    • キーボードによる移動
                                    • パフォーマンスの向上
                                      • スクロールバー
                                      • 選択
                                      • 編集
                                        • 編集モード
                                        • 編集の無効化
                                          • 並べ替え
                                            • 並べ替えの操作
                                            • 並べ替えのインジケータ
                                              • フィルタ
                                                • フィルタの操作
                                                  • フィルタの種類
                                                    • フィルタUI
                                                      • 検索
                                                      • マージ
                                                        • 自動マージ
                                                        • はみ出して表示されるセルの処理
                                                        • カスタムのマージ
                                                          • グループ
                                                          • 集計
                                                          • ツリーグリッド
                                                            • ノードの操作
                                                            • データの操作
                                                            • ツリーグリッドのカスタマイズ
                                                              • クリップボード
                                                              • 保存ロードと印刷
                                                                • 保存
                                                                • ロード
                                                                • 印刷
                                                                  • 外観とスタイル設定
                                                                    • 組み込みオプション
                                                                    • カスタムのスタイル
                                                                    • グリッドのカスタマイズ
                                                                    • 境界線のカスタマイズ
                                                                    • テキストのカスタマイズ
                                                                    • カスタムのグリフ
                                                                      • 永続的な状態
                                                                      • NET 5 リファレンス
                                                                      • NET 452 リファレンス
Page 3: FlexGrid for WinForms

ユーザー操作 83-85

ヘッダ 85-88

行の詳細 88-93

サイズ変更 93-95

セル 96

基本操作 96-99

セルの書式設定 100-104

グリッド 105

基本操作 105-107

キーボードによる移動 107-109

パフォーマンスの向上 109-114

スクロールバー 115-116

選択 117-119

編集 120

編集モード 120-121

編集の無効化 121-122

並べ替え 123

並べ替えの操作 123-127

並べ替えのインジケータ 127

フィルタ 128

フィルタの操作 128-132

フィルタの種類 132-139

フィルタUI 139-141

検索 142-143

マージ 144

自動マージ 144-147

はみ出して表示されるセルの処理 147-149

カスタムのマージ 149-151

グループ 152-155

集計 156-159

ツリーグリッド 160-172

ノードの操作 172-179

データの操作 179-181

FlexGrid for WinForms

2 Copyright copy GrapeCity Inc All rights reserved

ツリーグリッドのカスタマイズ 181-188

クリップボード 189-192

保存ロードと印刷 193

保存 193-195

ロード 195-197

印刷 197-199

外観とスタイル設定 200

組み込みオプション 200-202

カスタムのスタイル 202-203

グリッドのカスタマイズ 203-204

境界線のカスタマイズ 204-206

テキストのカスタマイズ 206-208

カスタムのグリフ 209

永続的な状態 210-211

NET 5 リファレンス 212

NET 452 リファレンス 213

FlexGrid for WinForms

3 Copyright copy GrapeCity Inc All rights reserved

FlexGrid for WinForms

FlexGrid for WinForms is one of the fastest datagrids available in the market that renders and displays large data sets quicker than any other NET datagrid It is a powerfulgrid packed with basic as well as advanced features like in-cell editing sorting filtering merging grouping and much more Moreover it displays the hierarchical dataefficiently using tree grids with multiple columns aggregates subtotals and row details Not just this the control offers robust API and extensive design-time support sothat you can give your end-users a familiar Excel-like experience

The FlexGrid control binds with any of the NET data sources such as ADONET data source objects and custom business objects It also lets you work in the unbound modegiving you the power to manually add each row or column and set the cell values

One of the main strengths of FlexGrid is the ability to customize almost every aspect of appearance of the entire grid and individual cells In addition to standard formatstrings and cell styling FlexGrid goes above and beyond most NET datagrid components by providing complete control over the cell drawing using its OwnerDrawCell event

Besides the main C1FlexGrid control FlexGrid for WinForms also contains a C1FlexGridClassic control derived from C1FlexGrid It provides an object model that is virtuallyidentical to the VSFlexGrid ActiveX control and is mainly targeted for customers who want to migrate their existing VSFlexGrid projects from ActiveX to the latest technology

Not just this if you are developing your own custom grid control you can use C1FlexGridClassic as a reference The C1FlexGridClassic control is a perfect example of customgrid control created with C1FlexGrid control as base class We ship its source code as a product sample named Classic

Release Notes Product Samples

See the version-wise updates for all controls here Product samples are located at DocumentsComponentOne SamplesWinFormsvxxxC1FlexGridCS onyour system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

Documentation Blogs

Create your First Application with FlexGrid

FlexGrid at Design-time

Work with Columns and Editors

Filter Grid Data

Enable Merging in FlexGrid

Create Groups

Create a Tree Grid

Financial Data Displays using FlexGrid

FlexGrid Performance Compare WinForms WPF UWP

Creating Custom Styles for FlexGrid

Add Dynamic Grouping to your WinForms Data Grid

Implement responsive columns in a WinForms data grid

Creating a Derived Accordion Control with FlexGrid

Show RadioButton in a ComponentOne FlexGrid Tree

Videos Demo Samples

Meet FlexGrid WinForms and WPF Grid Demo

Note ComponentOne FlexGrid for WinForms is compatible with both NET 452 and NET 5

API Reference

C1WinFlexGrid452 Assembly C1WinFlexGrid5 Assembly

FlexGrid for WinForms

4 Copyright copy GrapeCity Inc All rights reserved

主な特長

Code-free Development

Why write code when a click is enough With rich design-time options beginning from binding to styling whichare accessible through the tasks menu and various editors FlexGrid lets you do a lot even without writing a single lineof code

Advanced Cell Editing

Choose from a variety of built-in editors or just create one for yourself FlexGrid offers various built-in cell editors sothat you can choose from simple text editing drop-down lists combo lists cell buttons masks and so on Not justthis with an option to create your own custom cell editors you can change your cells to accept or display almostany type of data

Work in Bound Mode or Unbound Mode

Bound grid or unbound populate the data seamlessly FlexGrid lets you bind the grid with any of the NET datasources such as ADONET and DataObjects for NET You can also work in unbound mode and let FlexGrid manage thedata itself

Present Hierarchical Data

View data the way that is best for you and your users When FlexGrid is bound to a hierarchical data source eachmaster record can be expanded or collapsed to show or hide the details in child grids which may contain moredetails The result is a data tree similar to the type of grid presented by Microsoft Access when displayinghierarchical data When bound the control detects subordinate data sources and creates additional instances of itselfto display child tables

Summarize Data and Show Aggregates

Get a quick outline of your grid data by summarizing it FlexGrid allows you to summarize data by adding a subtotalrow and display aggregates such as sum average count and so on for the specified column

Make it a Tree

Easily display your hierarchical data by converting your grid into a tree FlexGrid lets you represent your bound orunbound hierarchical data in Tree Grid which is similar to a TreeView control and gives a clean yet accessible structureto the data

Built-in Data Filtering

Let your users filter the data by value by condition or just give them both the options to choose from FlexGridprovides advanced built-in filtering with column filter value filter and condition filter already in place Still does notwork for you Create your own custom filter using rich FlexGrid API

Grouping

Group programmatically or at run-time With FlexGrid both are possible FlexGrid lets you group either through codeand even give your users an option to group at run-time using the FlexGridGroupPanel control or through contextmenu

Instant Search

Search the entire grid in one go and locate entries among millions of records instantly FlexGridprovides FlexGridSearchPanel control which lets the user type in the search box filters the records that match thetyped text and also highlights the search results

Merge Cells

Give your grid a tidy look by merging the cells with the same values FlexGrid lets you merge the contiguous cells withthe same values the way you want With free and restricted auto-merge options the grid can intelligently decidewhich cells to merge

Save and Load Multiple Formats

Back up the grid data or load it back in a jiffy FlexGrid lets you save the grid in your favorite format be it a text fileexcel file or XML You can even load content from these formats Not just this you can also load grid data from a

FlexGrid for WinForms

5 Copyright copy GrapeCity Inc All rights reserved

database using DataReader objects

Show Sparklines

Perk up your grid with the tiny charts FlexGrid allows you to add sparklines to grid columns so that you can easilydisplay trends and fluctuations in a single cell and make your grid data more useful and attractive at the same time

Perform Clipboard Operations

Move your text easily with Ctrl+C and Ctrl+V FlexGrid lets you perform clipboard operations on the grid data andheaders using your favorite keys

Assign Field Names to Columns

No need to remember the index of columns just call them by name FlexGrid automatically assigns column keysto field names when the grid is data-bound or you may assign them through code You can refer to a column using aColIndex(ColKey) syntax later which will retrieve the column you want even if your user has moved it to a differentposition on the grid

Use Data Annotations

Hint the user with data annotations FlexGrid lets you add data annotations in the form of metadata tags to theclasses and other objects to display messages and tips for the users

UI Automation and Support

Enable accessible and rich client applications through UI Automation (UIA) FlexGrid control supports UI Automationusing frameworks such as TestStackWhite You can enable applications such as screen readers coded UI testing toexamine user-interface elements and even simulated user interaction through code

Note UI Automation works only for the 452 version of C1FlexGrid and NET framework 47 or above applicationtarget frameworks

Add Special Drawing Effects

Make your grid look different and attractive with special drawing effects FlexGrid lets you paint special drawingeffects such as lines bitmaps and icons in the grid cells Additionally you can even scale images and addtransparency to them

Display Images in Cells

Need to display images in columns not an issue at all With FlexGrid you can display images along with data You caneven bind grid columns to image lists an easy and efficient way to display graphical information from data sources

Integrated Printing

Print the grid with a single statement FlexGrid gives you control over paper orientation margins header and footertext as well as the dialog boxes to set up the printer or see a preview You can even implement advanced printingoptions such as adding page breaks or custom elements to each page by using printing events

Styling

Use the visual styles or create your own custom styling use the designer or write your own code FlexGrid gives youenormous options to customize the appearance of the grid to match your requirements You can customize everyelement of the FlexGrid starting from headers and icons to borders and subtotal rows

FlexGrid for WinForms

6 Copyright copy GrapeCity Inc All rights reserved

機能比較

This section compares the features of various FlexGrids available across different platforms as well as shows acomparison with MS DataGridView

Topic Content

ComparingFlexGrids

Lists the difference between ActiveX version(VSFlexGrid control) and NET version of the FlexGridcontrol making it easy to migrate your grid from AciveX to NET

VSFlexGrid (ActiveX) and C1FlexGrid (NET)

ComparingWinForms Grids

Shows comparison between features of grids available in ComponentOne WinForms Edition andMS DataGridView

FlexGrid or True DBGridComparing ComponentOne Grids with MS DataGridView

FlexGrid の比較

VSFlexGrid (ActiveX) and C1FlexGrid (NET)ComponentOne provides ActiveX as well as NET version of the FlexGrid control While the ActiveX version is known asVSFlexGrid the NET version is shipped in the name of C1FlexGrid Being a NET version C1FlexGrid came laterinto the picture and instead of porting from the already existing VSFlexGrid we decided to create a brand new gridcontrol written from the ground up in C with the same design principles but with a new object model that is moremodern clean and powerful than the one in the ActiveX control

This section caters to original users of the VSFlexGrid control who want to migrate their applications from ActiveX tothe NET version that is the C1FlexGrid control To facilitate the hassle-free migration and a smooth learning curvethe NET version provides the C1FlexGridClassic control that derives from the C1FlexGrid class and provides an objectmodel that is virtually identical to the VSFlexGrid control The C1FlexGridClassic control is available in the form of aproduct sample Classic so that you may know exactly how to use the new object model This sample can also beused as a reference for creating the custom grid controls based on the C1FlexGrid class

Note The Classic sample is located at DocumentsComponentOne SamplesWinFormsv452C1FlexGridCS onyour system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

For users creating new applications we recommend using the new C1FlexGrid control However for the users who areporting their existing applications from ActiveX to NET we recommend using the C1FlexGridClassic control tominimize the programming effort Following table highlights some of the key differences between VSFlexGrid andC1FlexGrid

VSFlexGrid (ActiveX) C1FlexGrid (NET)

RowsCols1 Rows and Cols properties are used to

get or set the number of rows andcolumns

2 VSFlexGrid uses the TextMatrixproperty to represent the rows andcolumns

1 In C1FlexGrid Rows and Cols propertiesreturn the rows and column collectionsThe collections have readwriteproperties that return the number ofelements and fixed elements in eachcollection

FlexGrid for WinForms

7 Copyright copy GrapeCity Inc All rights reserved

For instance in ActiveX you would write

Dim r c c = 1

For r = c1FlexGrid1FixedRows To

c1FlexGrid1Rows - 1

DebugPrint

c1FlexGrid1TextMatrix(rc)

Next

2 C1FlexGrid uses indexers to representrows and columns

For instance in NET you would write

Dim r c c = 1

For r = c1FlexGrid1RowsFixed To

c1FlexGrid1RowsCount - 1

DebugPrint(c1FlexGrid1(r c))

Next

CellCell range The Cell property is one of the mostpowerful elements of the VSFlexGrid objectmodel It allows you to get or set anyproperty of any cell or cell range with asingle command Using a single propertymeans using variants and this prevents thecompiler from catching many subtleproblems in case you make mistakes whilecoding

For instance in ActiveX you would write

flexCell(flexcpPicture 5 5

10 10)

= theImage

In C1FlexGrid CellRange object has replacedthe Cell property to expose type-safeproperties and methods for accessing cellrange So if variable theImage contained astring instead of an image you get a compilererror and not a runtime error Also you getcommand-completion when writing the codebecause the types for each property are known

For instance in NET you would write

Dim rg As CellRange

rg =

c1FlexGrid1GetCellRange(551010)

rgImage = theImage

Typed Columns In the ActiveX version the ColDataTypeproperty allows you to set the type of datathat each column contains This informationis used mainly for sorting columns thatcontain dates or numbers

In the NET version Cols[i]DataType propertydetermines the type of data the column holdsBy default the DataType property for allcolumns is set to object that is you can storeany type of data in any column You can set thedata type to specific types however the gridtries to coerce any data stored in the grid tothe proper type

For instance in NET you would write

c1FlexGrid1Cols(2)DataType =

GetType(Integer)

Sets the value to 12

c1FlexGrid1(1 2) = 12

Can not convert hello string to

integer

Fires the GridError event

Retains the original value

c1FlexGrid1(2 2) = hello

Styles In VSFlexGrid you can customize theappearance of individual cells or cell rangesusing the Cell property

For instance in ActiveX you would write

Set the backcolor of second row

c1FlexGrid1Cell(flexcpBackColor

In C1FlexGrid cell appearance can becustomized using the CellStyle object

For instance in NET you would write

Create a cell style

Dim redStyle As CellStyle =

c1FlexGrid1Styles

FlexGrid for WinForms

8 Copyright copy GrapeCity Inc All rights reserved

2 0 2

c1FlexGrid1Cols-1) = vbRed

Demerit

To change the appearance of all red cellsyou need to clear all styles and start again oryou need to scan for red cells and thenchange their appearance

Add(Red)

redStyleBackColor = ColorRed

Set the backcolor of second row

c1FlexGrid1Rows(2)Style =

redStyle

Merit

The main advantage of this approach is that thenew style is an object that can be changed orassigned to new ranges For instance tochange the fore-color and text font of red cellsyou would write

c1FlexGrid1Styles(Red)ForeColor

= ColorWhite

c1FlexGrid1Styles(Red)Font =

new Font(Arial 9)

The VSFlexGrid control had many propertiesthat affected the way the grid was displayed(eg BackColor BackColorAlternateBackColorBkg BackColorFixedBackColorFrozen BackColorSel and so on)

The C1FlexGrid control replaces all theseproperties with a collection of CellStyle objectsso you can write something likeStylesFixedBackColor orStylesHighlightForeColor This makes theobject model simpler more consistent andmore powerful You can change the built-instyles or define your own and assign them torows columns or arbitrary cell ranges

WinFormsグリッドの比較

FlexGrid or True DBGridComponentOne offers two grid components in WinForms Edition FlexGrid and True DBGrid While both of these are robust and easy-to-usegrids allowing you to browse edit add delete and manipulate tabular data they still have their own strengths and capabilities

Both ComponentOne WinForms Edition grids can be used in bound as well as unbound mode but C1FlexGrid allows you to work more easilyin unbound mode With C1FlexGrid you can customize trees and make use of its cell merging capabilities FlexGrid is also apt for deriving acustomized grid

If you are planning to develop or migrate to NET 5 or higher it is recommended to use C1FlexGrid While we will continue to supportC1TrueDBGrid in NET 5 it no longer receives new enhancements and features like C1FlexGrid

Comparing ComponentOne Grids with MS DataGridViewThis section gives you a quick comparison between the two ComponentOne WinForms Edition grids and the standard MS DataGridViewavailable for WinForms platform For easy navigation we have broadly divided these features into different categories Click on thecorresponding category in the right hand pane or scroll down to know more about availability of a particular feature

Data Binding

Features FlexGrid TrueDBGrid MS DataGridView

Binding Data Sources

Binding Data Sources with hierarchical datarelations

With custom code

Unbound data storage and manipulations

Data Presentation

FlexGrid for WinForms

9 Copyright copy GrapeCity Inc All rights reserved

Features FlexGrid TrueDBGrid MS DataGridView

Hierarchical Styles With custom code

TreeView-like Styles

MultiLine Data View

Grouping

Built-in Drag And Drop

Horizontal and Vertical Interactive Splits

Child grids within master grid support

Drop-Down Objects Support

Drop-Down Multicolumn Object support

Drop-Down Multicolumn Bindable and SortableObject support

Data Exchange

Features FlexGrid TrueDBGrid MS DataGridView

Export Data (Delimited Text XLS and XLSX)

Export Data in other formats (PDF HTML RTFJPG and other)

Load data from Excel files

Enhanced Printing data from grid and PrintPreview support

Cell Manipulations

Features FlexGrid TrueDBGrid MS DataGridView

In-Cell Objects

Enhanced Cell Editing with Custom Editors

Merging Cells and Rows

Customize Cells Merging

Drag And Drop Columns and rows

Automatic Cell Sizing

Fixed Non-scrolling Columns

Excel-style Cell Selection

Customize each Cell Rendering

Zooming Cells

Run-Time CellTips

Data Manipulations with Cell Ranges

Layout and Styling

Features FlexGrid TrueDBGrid MS DataGridView

Visual Styles Support

Dynamic Support of 38 Decoration Themes

Office 2007 and 2010 Styling

Alternating Row Colors

Customizable Cell Border Style

FlexGrid for WinForms

10 Copyright copy GrapeCity Inc All rights reserved

Add Special Drawing Effects

Data-Sensitive Display

Input and Navigation

Features FlexGrid TrueDBGrid MS DataGridView

Input Masking

Simplify Data Input

Automatic Data Translation

Spell Checking support

Customizable Keyboard Navigation and keysbehavior

Right-To-Left navigation

Touch Support

Clipboard support

Rich Scrolling Capabilities

Data Manipulations

Features FlexGrid TrueDBGrid MS DataGridView

Sorting

Multi-column Sorting

Built-in Data Filtering

Extended and Conditional Filtering

Customizable filter form

Additional Filter Bar row

Multi-language Filtering

AutoSearch

Range Aggregates

Localization

Features FlexGrid TrueDBGrid MS DataGridView

Right-To-Left support

Net localization support

Regional settings support

Other Features

Features FlexGrid TrueDBGrid MS DataGridView

Optimize performance for displaying largeamount of data in bound and unbound mode

Just-In-Time Data Loading

Server-side Data Virtualization withC1DataSource

Automatic Lookup Columns with C1DataSource

Design-time extended support

Assembly size 1508 K 2108 K Part of

FlexGrid for WinForms

11 Copyright copy GrapeCity Inc All rights reserved

SystemWindowsForms

FlexGrid for WinForms

12 Copyright copy GrapeCity Inc All rights reserved

クイックスタート

This quick start will guide you through the steps of creating a simple grid application using the FlexGrid control Follow thesteps below to get started

FlexGrid for WinForms

13 Copyright copy GrapeCity Inc All rights reserved

This section demonstrates how to create a FlexGrid application in NET 452 by binding it to an externaldatasource You can also create a class to supply data to the grid as shown in the NET 5 tab Similarly you can usebelow steps to bind FlexGrid to a datasource in NET 5 However note that some design-time steps may vary in caseof NET 5

Set Up the Application1 Create a new Windows Forms app(NET Framework)2 Configure your project and set the Framework property3 Drag and drop the FlexGrid control from the Visual Studio toolbox onto the form

Observe An empty grid is added to the form at design time

Bind FlexGrid to a Data SourceThere are two ways to bind data with the FlexGrid control either choose to bind at design time or through code atrun time

Binding at Design Time

1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Click the Choose Data Source drop down button and select Add Project Data Source option to open the

Data Source Configuration Wizard3 On Choose a Data Source Type page select Database and click Next4 On Choose a Database Model page select Dataset and click Next5 On Choose Your Data Connection page click New Connection to open the Add Connection dialog6 Against the DataSource field click Change button to open the Change Data Source dialog7 Select Microsoft Access Database File and click OK to return to the Add Connection dialog8 Against the Database file name field click Browse and navigate to the database file Provide the User name

and Password if required to connect to the database file This example uses C1NWindmdb file located atthe following location by defaultDocumentsComponentOne SamplesCommon

9 Click Test Connection to make sure that you have successfully connected to the database or server and clickOK

NET 452

FlexGrid for WinForms

14 Copyright copy GrapeCity Inc All rights reserved

10 Click OK again to close the Add Connection dialog box11 Click Next 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 Choose the appropriate option as per your requirement12 Save the connection string in the application configuration file by checking the Yes save the connection as

box and entering a name13 Click Next to switch to the Choose Your Database Objects page14 Choose a table say Products from the Tables node and click Finish15 The above steps add a dataset and connection string to your project Also Visual Studio automatically creates

the following code to fill the datasetC

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて

移動または削除できます

thisproductsTableAdapterFill(thisc1NWindDataSetProducts)

VBNET

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移

動または削除できます

MeProductsTableAdapterFill(Mec1NWindDataSetProducts)

Binding at Run Time

To bind the grid through code first we need to create a database connection string Then use an object of dataadapter (in this case OleDbDataAdapter) to create a query to fetch products from the data table and fill it in thedata table which is assigned to the DataSource property of C1FlexGrid class

C

グリッドをデータソースに連結します

string conn = GetConnectionString()OleDbDataAdapter da = new OleDbDataAdapter(select from products conn)DataTable dt = new DataTable(Products)daFill(dt)c1FlexGrid1DataSource = dt

VBNET

グリッドをデータソースに連結します

Dim conn As String = GetConnectionString()Dim da As OleDbDataAdapter = New OleDbDataAdapter(select from products conn)Dim dt As DataTable = New DataTable(Products)daFill(dt)c1FlexGrid1DataSource = dt

Note that the above sample code uses a custom method named GetConnectionString to create a connection stringwith database

C

static string GetConnectionString() string path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) + ComponentOne SamplesCommon string conn = provider=microsoftjetoledb40data source=0c1nwindmdb return stringFormat(conn path)

VBNET

Private Shared Function GetConnectionString() As String Dim path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) amp

FlexGrid for WinForms

15 Copyright copy GrapeCity Inc All rights reserved

ComponentOne SamplesCommon Dim conn = provider=microsoftjetoledb40data source=0c1nwindmdb Return StringFormat(conn path)End Function

Configure the FlexGrid controlThis section walks you through the design-time and run-time steps to configure the grid with some basic settingsThese settings and features are explained in detail in the topics below

Configuring Grid at Design Time

Click smart tag to open the C1FlexGrid Tasks MenuClick the Styles option to open C1FlexGrid Styles EditorSelect Fixed from Built-in Styles pane customize some settings such as Backcolor Font and ForeColor andclick OKTo fit the grid to the form click the Dock in Parent Container optionFor customizing a column click the column (say Unit Price column) to open C1FlexGrid Column TasksMenuClick the ellipsis alongside Format field to open the Format String dialogSelect Currency as Format Type and click OK

Configuring Grid at Run Time

Add following code to configure the grid and its columns at run time

C

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = new Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols[6]Format = c

VBNET

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = New Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols(6)Format = c

FlexGrid for WinForms

16 Copyright copy GrapeCity Inc All rights reserved

This section demonstrates how to create a FlexGrid application in NET 5 by populating its data from a custom classYou can also use an external datasource to supply data to the grid as shown in NET 452 tab However note thatsome design-time steps given in the aforementioned tab may vary in case of NET 5 Similarly you can use belowsteps to bind FlexGrid to an internal datasource in NET 452

Set Up the Application1 Create a new Windows Forms app(NET Framework)2 Configure your project and set the Framework property3 Initialize the FlexGrid control and add it to the form

C

コントロールを初期化します

C1FlexGrid flexGrid = new C1FlexGrid() フォームにコントロールを追加します

thisControlsAdd(flexGrid)

VBNET

コントロールを初期化します

Dim flexGrid As C1FlexGrid = New C1FlexGrid() フォームにコントロールを追加します

MeControlsAdd(flexGrid)

Bind FlexGrid to a Data Source1 Create a custom class Product to be used as a data source

C

カスタムクラスProductを作成します

public class Product static Random _rnd = new Random()

NET 5

FlexGrid for WinForms

17 Copyright copy GrapeCity Inc All rights reserved

static string[] _names = Macko|Surfair|Pocohey|StudebySplit(|) static string[] _lines = Computers|Washers|Stoves|CarsSplit(|) static string[] _colors = Red|Green|Blue|WhiteSplit(|) public Product() Name = _names[_rndNext() _namesLength] Line = _lines[_rndNext() _linesLength] Color = _colors[_rndNext() _colorsLength] Price = 30 + _rndNextDouble() 1000 Cost = 3 + _rndNextDouble() 300 Discontinued = _rndNextDouble() lt 2 Introduced = DateTimeTodayAddDays(_rndNext(-600 0)) public string Name get set public string Color get set public string Line get set public double Price get set public double Cost get set public DateTime Introduced get set public bool Discontinued get set

VBNET

カスタムクラスProductを作成します

Public Class Product Private Shared _rnd As Random = New Random() Private Shared _names As String() = Macko|Surfair|Pocohey|StudebySplit(|c) Private Shared _lines As String() = Computers|Washers|Stoves|CarsSplit(|c) Private Shared _colors As String() = Red|Green|Blue|WhiteSplit(|c)

Public Sub New() Name = _names(_rnd[Next]() Mod _namesLength) Line = _lines(_rnd[Next]() Mod _linesLength) Color = _colors(_rnd[Next]() Mod _colorsLength) Price = 30 + _rndNextDouble() 1000 Cost = 3 + _rndNextDouble() 300 Discontinued = _rndNextDouble() lt 2 Introduced = DateTodayAddDays(_rnd[Next](-600 0)) End Sub

Public Property Name As String Public Property Color As String Public Property Line As String Public Property Price As Double Public Property Cost As Double Public Property Introduced As Date Public Property Discontinued As BooleanEnd Class

2 Initialize a list of type ProductC

Productがクラス型であるProduct型のリストを初期化します

ListltProductgt _products = new ListltProductgt()

FlexGrid for WinForms

18 Copyright copy GrapeCity Inc All rights reserved

VBNET

Productがクラス型であるProduct型のリストを初期化します

Dim _products As List(Of Product) = New List(Of Product)()

3 Initialize a For loop and add products to the list

C

forループを初期化し製品をリストに追加します

for (int i = 0 i lt100 i++) _productsAdd(new Product())

VBNET

forループを初期化し製品をリストに追加します

For i As Integer = 0 To 100 - 1 _productsAdd(New Product())Next

4 Bind FlexGrid to the created data sourceC

FlexGridにデータを連結します flexGridDataSource = _products

VBNET

FlexGridにデータを連結します flexGridDataSource = _products

Configure the FlexGrid controlAdd following code to configure the grid and its columns at run time

C

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = new Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols[6]Format = c

VBNET

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = New Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols(6)Format = c

FlexGrid for WinForms

19 Copyright copy GrapeCity Inc All rights reserved

設計時サポート

FlexGrid for WinForms comes with various design time options to make your programming tasks a lot easier In addition to smart tag context menu andproperty grid FlexGrid provides tasks menus and editors as well While C1FlexGrid Tasks menu lets you work on the entire grid in design time the ColumnTasks menu provides options to set some common properties for each column of the grid At the same time various editors such as C1FlexGrid ColumnEditor and C1FlexGrid Style Editor provide detailed properties to customize the columns and styles

This section discusses about various design-time options available in the FlexGrid control

Topic Snapshot Content

Tasks Menus Discusses about the C1FlexGrid Tasks menu the Column Tasks menu and their options

C1FlexGrid Tasks MenuC1FlexGrid Column Tasks Menu

Editors Discusses about the various editors and how to access them

C1FlexGrid Column EditorC1FlexGrid Style EditorCaption Style EditorColumn Style Editor

タスクメニュー

C1FlexGrid Tasks MenuC1FlexGrid Tasks menu provides you an easy access to the commonly used properties of FlexGrid It also providesoptions to open various editors such as C1FlexGrid Column Editor C1FlexGrid Style Editor

To access the C1FlexGrid Tasks menu click the smart tag ( ) in the upper right corner of the grid Following tableexplains various options available through the C1FlexGrid Tasks menu

Option Description

ChooseDataSource

The dropdown opens the list of available data sourcesand gives you Add Project Data Source option to openData Source Configuration Wizard

For more information on how to add a new data sourceto the project see Bound Mode

EnableAddingRows

The checkbox toggles the AllowAddNew propertywhich allows users to add new row to the grid at runtime When checked ON it displays a template row withstar at the bottom of the grid to enter the new record

EnableDeletingRows

The checkbox toggles the AllowDelete property whichallows users to delete the selected rows by pressing theDelete key

EnableEditing

The checkbox toggles the AllowEditing property whichallows users to edit the grid

Enable Column Reordering The checkbox sets the AllowDragging property toColumns which allows users to re-order the columns by draggingthe column headers

Enable Column Filtering The checkbox toggles the FlexGridAllowFiltering property to

FlexGrid for WinForms

20 Copyright copy GrapeCity Inc All rights reserved

enable or disable the filtering on grid columns

VisualStyle The dropdown lets you choose the built-in visual styles availablein the grid By default the value is set to Custom

Designer The option opens C1FlexGrid Column Editor which allows you toset the properties of each column of the grid

Styles The option opens C1FlexGrid Style Editor which allows youto customize the various pre-defined styles or create the newstyles at design time

Display Hidden Columns The checkbox lets you display or hide grid columns in the designview Note that this option is NOT associated with the run-timevisibility of columns Hence even if this checkbox is checked ONcolumns with Visible property set to False still remain hiddenwhen the application is run

Column Tasks The option switches the task menu to C1FlexGrid Column Tasksmenu which provides options to set the properties for theselected column

About C1FlexGrid The option displays a dialog box displaying the information suchas version of the FlexGrid control

Dock in Parent Container This option sets the Dock property of the grid to Fill which resizesthe grid to occupy the whole form space Clicking the option alsoswitches the text and provides option to Undock in ParentContainer which restores the grid to its original size

C1FlexGrid Column Tasks MenuC1FlexGrid Column Tasks menu provides you an easy access to the commonly used properties of grid columns Italso provides options to open editors named Caption Style and Column Style

To access the C1FlexGrid Column Tasks menu double-click header of the column to be configured at design-timeAnother way to open C1FlexGrid Column Tasks menu is to click on the smart tag ( ) in the upper right corner of thegrid and then navigate to the Column Tasks option Following table explains various options available through theC1FlexGrid Column Tasks menu

FlexGrid for WinForms

21 Copyright copy GrapeCity Inc All rights reserved

Option Description

ColumnCaption

The field allows you to specify the value of Captionproperty which sets text in header cell of the column

DataField

The dropdown opens a list of available fields in the datasource to choose from and sets value of Name property ofthe column

DataType

The dropdown opens a list of available data types and letsyou set the data type of the selected column This fieldcorresponds to the DataType property of the column

EditMask

The field lets you specify value of EditMask property whichsets mask for the selected column The ellipsis button onthe right side of the field opens the Input Mask dialog boxwhere you can select from the list of pre-defined masks

FormatString

The field lets you specify the value of Format propertywhich sets format string to display data value from source

ComboList

The field lets you specify the list of multiple values fromwhich user can choose The ellipsis button on the right sideof the field lets you open the Combo List dialog box whereyou can specify the value options

Allow Sorting The checkbox toggles the AllowSorting property to enable ordisable sorting in the column By default sorting is enabled for allcolumns

Allow Editing The checkbox toggles the AllowEditing property to make thecolumn read-only or editable By default editing is enabled for allcolumns

Allow Resizing The checkbox toggles the AllowResizing property which allows usersto adjust the size of column at run time By default resizing isenabled for all columns

Allow Dragging The checkbox toggles the AllowDragging property to enable ordisable re-ordering of the column at run time By default dragging isenabled for all columns

Allow Merging The checkbox toggles the AllowMerging property to enable ordisable merging two adjacent column cells having same values Bydefault merging is disabled for all columns

Allow Filtering The dropdown lets you specify the value of ColumnAllowFilteringproperty and choose the type of filter for each column The availableoptions are Default ByValue ByCondition Custom or None

Visible The checkbox lets you set the visibility of the column in the grid atrun time by toggling value of its Visible property

FlexGrid for WinForms

22 Copyright copy GrapeCity Inc All rights reserved

Caption Style The option opens the Caption Style editor which gives you options tostyle the text alignment background and border for the header cellof column

Column Style The option opens the Column Style editor which gives you options tostyle the text alignment background and border for the column text

C1FlexGrid Tasks The option switches the task menu to C1FlexGrid Tasks menu whichprovides options to set the properties for the entire grid

Dock in Parent Container The option sets the Dock property of the grid to Fill which resizes thegrid to occupy the whole form Clicking the option also switches thetext and provides option to Undock in Parent Container whichrestores the grid to its original size by setting the Dock property toNone

エディタ

Apart from the tasks menu FlexGrid also provides various editors that help you set a number of properties related togrid its columns and their styles

C1FlexGrid Column EditorFlexGrid provides the C1FlexGrid Column Editor making it easy to work with columns at design-time instead ofwriting code The editor lets you set various properties related to columns such as Caption DataTypeAllowFiltering and AllowMerging through its property pane on left hand side Toolbar on the top of this editorgives you options such as reloading data from the data source adding removing and resizing columns You can evenstyle the column text using the options given in this toolbar For further customization of column text you can usethe Column Style editor to access more specific properties

FlexGrid for WinForms

23 Copyright copy GrapeCity Inc All rights reserved

There are three ways in which you can access the C1FlexGrid Column Editor at design time

Smart Tag Click the smart tag ( ) in the upper right corner of the grid and select Designer from theC1FlexGrid Tasks menuProperty Window Select the grid go to the Properties window and click the ellipsis button (hellip) next to theCols propertyContext Menu Right-click the grid and select Designer from the context menu

C1FlexGrid Style EditorFlexGrid provides the C1FlexGrid Style editor which lets you style the grid at design time by customizing the built-instyles and creating the new ones The editor offers a list of styles for specific types of cell on left hand side and aproperty window on right hand side to customize these styles The list of styles is divided into two sections thedefault Built-in Styles and Custom Styles Towards the bottom there are Add and Remove buttons to add anddelete the custom styles and a Clear button to revert the editor to default settings The AutoFormat button in theend opens a secondary dialog C1FlexGrid Auto Format which lists the pre-defined set of styles and also shows apreview in the Preview pane

FlexGrid for WinForms

24 Copyright copy GrapeCity Inc All rights reserved

There are three ways in which you can access the C1FlexGrid Style Editor at design-time

Smart Tag Click the smart tag ( ) in the upper right corner of the grid and select Styles from theC1FlexGrid Tasks menuProperty Window Select the grid go to the Properties window and click the ellipsis button (hellip) next to theStyles propertyContext Menu Right-click the grid and select Styles from the context menu

Caption Style EditorFlexGrid provides the Caption Style editor which allows you to set styling related properties of the column header celland its text The editor comprises of four tabs Text Alignment Border and Background for customizing variousaspects of the header cells

To access the Caption Style editor click smart tag ( ) click the C1FlexGrid Column Tasks option on the task menu toopen column tasks and then go to Caption Style option

FlexGrid for WinForms

25 Copyright copy GrapeCity Inc All rights reserved

Column Style EditorSimilar to Caption Style editor FlexGrid provides another editor the Column Style editor for styling the column textThe editor has got the same options as that of Caption Style editor The only difference is that Caption Style editorcustomizes the column header text while this editor works on the general text in the column cells

To access the Column Style editor click smart tag ( ) click the C1FlexGrid Column Tasks option on the task menu toopen column tasks and then go to Column Style option

FlexGrid for WinForms

26 Copyright copy GrapeCity Inc All rights reserved

データ

This section discusses about various ways to populate data in the FlexGrid control

Topic Snapshot Content

Unbound Mode Discusses how to populate data in the unbound grid

Bound Mode Discusses ways of populating data in the grid through data binding and various operations on bound grid

Binding at design timeBinding at run time using DataSource propertyBinding at run time using SetDataBinding methodOperations in Bound Mode

非連結モード

As the name suggests in unbound mode grid is not bound to any data source and data is stored in the control itselfIn this case you need to provide data by adding rows and columns either at design time or programmatically throughrow and column collections You can also create an empty grid to let user enter the data

An unbound grid is not a very common scenario as grid does not store the data and hence user needs to manage itmanually However unbound grids suits better to some business scenarios like creation and maintenance of recordsFor instance you can use the grid in unbound mode for recording the date-wise sales data or to maintain the dailyinventory changes Below example demonstrates a grid with data populated through code

In C1FlexGrid you can add empty rows or columns by setting the Count property of row or column objects Also youcan use the Add method of these collections to add the empty rows and columns to a grid To set data in the cellsyou can either use the familiar index notation(Item property) or the SetData method For more information on settingdata in the cells see Storing and Retrieving Data

Use the code below to populate data in unbound FlexGrid for WinForms

連結されていない列を追加しますColumn col = _flexColsAdd()colName = colCaption = Unbound_flex[1 Unbound] = 123

C

連結されていない列を追加しますDim col As Column = C1FlexGrid1ColsAdd()colName = UnboundcolCaption = Unbound

VBNET

FlexGrid for WinForms

27 Copyright copy GrapeCity Inc All rights reserved

連結モード

Bound mode as the name suggests refers to a state where grid fetches its data from an underlying data source Databinding also allows multiple data consumers to be connected to a data provider in the synchronized manner

FlexGrid supports data binding to most of the commonly used data sources such as ObservableCollection IListltTgtListltTgt Array BindingSource ADONET objects such as DataSet DataTable etc

There are three ways of binding FlexGrid to a data source

Binding at design timeBinding at run time using DataSource propertyBinding at run time using SetDataBinding method

Binding at Design Time1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Click the Choose Data Source drop down button and select Add Project Data Source option to open the

Data Source Configuration Wizard3 On Choose a Data Source Type page select Database and click Next4 On Choose a Database Model page select Dataset and click Next5 On Choose Your Data Connection page click New Connection to open the Add Connection dialog6 Against the DataSource field click Change button to open the Change Data Source dialog7 Select Microsoft Access Database File and click OK to return to the Add Connection dialog8 Against the Database file name field click Browse and navigate to the database file Provide the User name

and Password if required to connect to the database file This example uses C1NWindmdb file located at thefollowing location by defaultDocumentsComponentOne SamplesCommon

FlexGrid for WinForms

28 Copyright copy GrapeCity Inc All rights reserved

9 Click Test Connection to make sure that you have successfully connected to the database or server and clickOK

10 Click OK again to close the Add Connection dialog box11 Click Next 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 Choose the appropriate option as per your requirement12 Save the connection string in the application configuration file by checking the Yes save the connection as

box and entering a name13 Click Next to switch to the Choose Your Database Objects page14 Choose a table say Products from the Tables node and click Finish15 The above steps add a dataset and connection string to your project Also Visual Studio automatically creates

the following code to fill the dataset

Binding at Run Time Using DataSource PropertyFlexGrid provides the DataSource property to bind the FlexGrid control to a data source at run time You need toassign a data source object to the DataSource property of FlexGrid If the data source object contains more than onetable you can set the DataMember property to table name to specify the target table

Following code uses DataSource property to bind data to the WinForms FlexGrid

Note that the above sample code uses a custom method named GetData to supply data You can set up the datasource as per your requirements Following code shows an example of creating data for WinForms FlexGrid

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移動または削除できます thisproductsTableAdapterFill(thisc1NWindDataSetProducts)

C

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移動または削除できます MeProductsTableAdapterFill(Mec1NWindDataSetProducts)

VBNET

c1FlexGrid1BeginUpdate()C1DataCollectionltCustomergt c1DataCollection = new C1DataCollectionltCustomergt(GetData())c1FlexGrid1DataSource = new C1DataCollectionBindingList(c1DataCollection)c1FlexGrid1EndUpdate()

C

c1FlexGrid1BeginUpdate()Dim c1CollectionView As C1DataCollectionC1DataCollection(Of Customer) = New C1DataCollectionC1DataCollection(Of Customer)(GetData())c1FlexGrid1DataSource = New C1DataCollectionBindingListC1DataCollectionBindingList(c1CollectionView)c1FlexGrid1EndUpdate()

VBNET

ObservableCollectionltCustomergt GetData() var data = new ObservableCollectionltCustomergt() for (int i = 0 i lt 25 i++)

C

FlexGrid for WinForms

29 Copyright copy GrapeCity Inc All rights reserved

Binding at Run Time Using SetDataBinding MethodFlexGrid also provides the SetDataBinding method using which you can set DataSource and DataMember propertiesboth using a single call The following code demonstrates an example of rendering a parent table and its child tablesin different grids with the help of the SetDataBinding method

Below code demonstrates how to bind data to WinForms FlexGrid using SetDataBinding method

dataAdd(new Customer()) return data

Private Function GetData() As ObservableCollection(Of Customer) Dim data = New ObservableCollection(Of Customer)()

For i = 0 To 25 - 1 dataAdd(New Customer()) Next

Return dataEnd Function

VBNET

グリッドにデータセットを連結します_flexCustomersBeginUpdate()_flexCustomersSetDataBinding(ds Customers)_flexCustomersEndUpdate()

_flexOrdersBeginUpdate()_flexOrdersSetDataBinding(ds CustomersCustomerOrders)_flexOrdersEndUpdate()

_flexOrderDetailsBeginUpdate()_flexOrderDetailsSetDataBinding(ds CustomersCustomerOrdersOrderDetails)_flexOrderDetailsEndUpdate()

C

グリッドにデータセットを連結します_flexCustomersBeginUpdate()_flexCustomersSetDataBinding(ds Customers)_flexCustomersEndUpdate() _flexOrdersBeginUpdate()_flexOrdersSetDataBinding(ds CustomersCustomerOrders)_flexOrdersEndUpdate() _flexOrderDetailsBeginUpdate()_flexOrderDetailsSetDataBinding(ds CustomersCustomerOrdersOrderDetails)_flexOrderDetailsEndUpdate()

VBNET

連結モードでの操作

Adding Unbound Column in Bound ModeIn the bound mode grid fetches the data from data source and display it as records and bound columns To add a column to

FlexGrid for WinForms

30 Copyright copy GrapeCity Inc All rights reserved

display data that does not exist in the data source you need to add unbound columns at design time or through code

Adding unbound column at design time

1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Bind the grid control with a data source For detailed steps about how to bind FlexGrid to a data source see Bound

Mode3 Click the Designer option to open the C1FlexGrid Column Editor4 In the right hand side pane select an existing column from the grid preview5 Click Insert Column options in the toolbar to add a column before or after the selection

Adding unbound column through code

FlexGrid provides Add Insert and InsertRange method of the ColumnCollection class to add an unbound column to the gridWhile Add method adds a column at the end the Insert method lets you specify the position where you want to add a newcolumn Similarly you can add multiple columns at a specified position by using the InsertRange method

Use the code below to add unbound column in a bound WinForms FlexGrid

連結されていない列を追加しますColumn col = _flexColsAdd()colName = colCaption = Unbound_flex[1 Unbound] = 123

C

連結されていない列を追加しますDim col As Column = C1FlexGrid1ColsAdd()colName = UnboundcolCaption = Unbound

VBNET

FlexGrid for WinForms

31 Copyright copy GrapeCity Inc All rights reserved

Set Values in Unbound ColumnTo define values in the unbound column of bound grid you need to usethe SetUnboundValue and GetUnboundValue events of the C1FlexGrid class First create a hash table to store the enteredvalues then use the SetUnboundValue event to set unbound value in the hash table using a unique key to identify therecord and use GetUnboundValue event to get the value stored in the hash table using its unique key and set unboundvalue to be displayed in the cell

Following code shows how to set values in an unbound column added to a bound WinForms FlexGrid

Displaying Data in Fixed ColumnTo set values in the fixed columns you need to set DrawMode property of the C1FlexGrid class to OwnerDraw in the formload event and then create the OwnerDrawCell event to set values in the fixed column cells In this example we are settingrow numbers in the fixed column of a bound WinForms FlexGrid

get value from hashtable using ProductID as keyvoid _flex_GetUnboundValue(object sender C1WinC1FlexGridUnboundValueEventArgs e) DataRowView drv = (DataRowView)_flexRows[eRow]DataSource eValue = _hash[drv[ProductID]]

store value in hashtable using ProductID as keyvoid _flex_SetUnboundValue(object sender C1WinC1FlexGridUnboundValueEventArgs e) DataRowView drv = (DataRowView)_flexRows[eRow]DataSource _hash[drv[ProductID]] = eValue

C

Private Sub C1FlexGrid1_GetUnboundValue(sender As Object e As C1WinC1FlexGridUnboundValueEventArgs) Handles C1FlexGrid1GetUnboundValue Dim drv As DataRowView = DirectCast(C1FlexGrid1Rows(eRow)DataSource DataRowView) eValue = _hash(drv(ProductID))End Sub

Private Sub C1FlexGrid1_SetUnboundValue(sender As Object e As C1WinC1FlexGridUnboundValueEventArgs) Handles C1FlexGrid1SetUnboundValue Dim drv As DataRowView = DirectCast(C1FlexGrid1Rows(eRow)DataSource DataRowView) _hash(drv(ProductID)) = eValueEnd Sub

VBNET

FlexGrid for WinForms

32 Copyright copy GrapeCity Inc All rights reserved

Auto-adjust Column WidthFlexGrid provides AutoResize property of the C1FlexGrid class to adjust the width of columns automatically according tothe text length You need to set the property to true before binding it to the data source to load the grid with appropriatecolumn width You can also call AutoSizeCol method to adjust the width of the specified column

Use the code below auto-adjust the column width according to the text in WinForms FlexGrid

Display Bitmap Image in FieldIn most of the scenarios grid directly fetches the images from the data source However if the grid is bound to a databasewhich stores images as OLE objects such as Microsoft Access a little bit of extra processing is required to fetch bitmapimages In such case you need to convert the image data stored as byte array to a memory stream and then usethe OwnerDrawCell event to load the image In the form load event you need to set the DrawMode property toOwnerDraw Also adjust the height of row to display the image properly

Following code demonstrates how to display bitmap image in fields of WinForms FlexGrid

private void C1FlexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if ((eRow gt= thisc1FlexGrid1RowsFixed) amp (eCol == (thisc1FlexGrid1ColsFixed - 1))) eText = eRowToString() または任意のテキスト

C

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If eRow gt= Mec1FlexGrid1RowsFixed And eCol Is Mec1FlexGrid1ColsFixed - 1 Then eText = eRowToString() または任意のテキスト End IfEnd Sub

VBNET

すべての列の幅を自動的に調整します c1FlexGrid1AutoResize = true

4列目の幅を自動調整します c1FlexGrid1AutoSizeColumns(3)

C

すべての列の幅を自動的に調整します c1FlexGrid1AutoResize = True

4列目の幅を自動調整します c1FlexGrid1AutoSizeColumns(3)

VBNET

private void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) if(eMeasuring ampamp eRowgt=c1FlexGrid1RowsFixed ampamp eCol gt=

C

FlexGrid for WinForms

33 Copyright copy GrapeCity Inc All rights reserved

Note that the above sample code uses a custom method LoadImage method to convert the images from byte array to amemory stream

c1FlexGrid1ColsFixed) 「Photo」はblob(byte [])に保存された画像です if (c1FlexGrid1Cols[eCol]Name == Picture) mdbからロードしてみてください eImage = LoadImage(c1FlexGrid1[eRow eCol] as byte[])

画像が表示された場合はテキストを入力しないでください if (eImage = null) eText = null

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) If Not eMeasuring AndAlso eRow gt= c1FlexGrid1RowsFixed AndAlso eCol gt= c1FlexGrid1ColsFixed Then

「Photo」はblob(byte [])に保存された画像です If c1FlexGrid1Cols(eCol)Name Is Picture Then mdbからロードしてみてください eImage = LoadImage(TryCast(c1FlexGrid1(eRow eCol) Byte()))

画像が表示された場合はテキストを入力しないでください If eImage IsNot Nothing Then eText = Nothing End If End IfEnd Sub

VBNET

Image LoadImage(byte[] picData) static Image LoadImage(byte[] picData) これが埋め込みオブジェクトであることを確認してください const int bmData = 78 if (picData == null || picDataLength lt bmData + 2) return null if (picData[0] = 0x15 || picData[1] = 0x1c) return null

現在点ではビットマップのみを処理します if (picData[bmData] = B || picData[bmData + 1] = M) return null

画像をロードします Image img = null try MemoryStream ms = new MemoryStream(picData bmData picDataLength - bmData) img = ImageFromStream(ms) catch

画像を返します return img

C

Private Function LoadImageMethod(ByVal picData As Byte()) As Image

VBNET

FlexGrid for WinForms

34 Copyright copy GrapeCity Inc All rights reserved

Private Shared Function LoadImage(ByVal picData As Byte()) As Image これが埋め込みオブジェクトであることを確認してください Const bmData As Integer = 78 If picData Is Nothing OrElse picDataLength lt bmData + 2 Then Return Nothing If picData(0) ltgt ampH15 OrElse picData(1) ltgt ampH1c Then Return Nothing

現在点ではビットマップのみを処理します If picData(bmData) ltgt Bc OrElse picData(bmData + 1) ltgt Mc Then Return Nothing

画像をロードします Dim img As Image = Nothing

Try Dim ms As MemoryStream = New MemoryStream(picData bmData picDataLength - bmData) img = ImageFromStream(ms) Catch End Try

画像を返します Return imgEnd Function

FlexGrid for WinForms

35 Copyright copy GrapeCity Inc All rights reserved

A grid control is a collection of rows and columns Columns generally contain a particular type of information through out while rows are used to recorddifferent types of information about a particular item

In FlexGrid the collection of columns is represented by the ColumnCollection class which can be accessed through Cols property of the C1FlexGrid class Thissection discusses the various operations that can be performed on columns

Topic Snapshot Content

BasicOperations

Discusses about how to perform basic column operations

Set Column CountAdd ColumnDelete ColumnInsert ColumnSet Data TypeSet Fixed ColumnSet Frozen Column

UserInteraction

Discusses about operations that can be performed by the end user at run time

Allow EditingAllow DraggingAllow FreezingAllow SortingAllow FilteringAllow Resizing

Editors Discusses about various built-in editors of FlexGrid and operations related to them Also discusses how to use customeditors in the FlexGrid

CheckBoxNumericDateComboBoxMaskMapped ListCell Button

Validation Discusses how to apply validation and show error information on FlexGrid cells

Sparkline Discusses about how to display Sparkline charts in FlexGrid cells

Header andFooter

Discusses about how to set column header and footer

Set Header TextMerge column headerWrap column header textStyle Column HeaderSet Column Footer

Sizing Discusses about various aspects of column sizing

Set Column WidthAuto-adjust Column WidthSet MinMax Column WidthStar Sizing

基本操作

This topic discusses various basic operations which can be performed on a column

FlexGrid for WinForms

36 Copyright copy GrapeCity Inc All rights reserved

Set Column CountWhen grid is bound to a data source the number of columns is determined by the number of fields available in thedata source However in the case of unbound mode you can set any arbitrary value in the Count property ofthe ColumnCollection class to set the number of columns to be displayed in the grid

Use the code below to set the number of columns to be added to WinForms FlexGrid in unbound mode

Add ColumnFlexGrid provides two ways to add a new column using the ColumnCollection class You can either use Add methodor increment the value of Count property provided by the class to add new columns Also note that if a new columnis added to a bound grid using these methods it is added as an unbound column only

Following are the two approaches to add column to a WinForms FlexGrid

Delete ColumnTo delete a particular column from the grid you can use Remove method of the ColumnCollection class and specifythe column you want to delete as its parameter In the unbound grid you can also reduce the number of columns bychanging the value of Count property This removes columns from the end of the column collection TheColumnCollection class also provides RemoveRange method which allows you to remove a range of columns

列数を設定します c1FlexGrid1ColsCount = 4

C

列数を設定しますc1FlexGrid1ColsCount = 4

VBNET

方法1 列コレクションのAddメソッドを使用します C1WinC1FlexGridColumn c c = c1FlexGrid1ColsAdd() cCaption = New Column

方法2 列コレクションのCountプロパティを変更します c1FlexGrid1ColsCount += 1 c1FlexGrid1Cols[c1FlexGrid1ColsCount - 1]Caption = New Column

C

方法1 列コレクションのAddメソッドを使用します Dim c As C1WinC1FlexGridColumn c = c1FlexGrid1ColsAdd() cCaption = New Column

方法2 列コレクションのCountプロパティを変更します c1FlexGrid1ColsCount += 1 c1FlexGrid1Cols(c1FlexGrid1ColsCount - 1)Caption = New Column

VBNET

FlexGrid for WinForms

37 Copyright copy GrapeCity Inc All rights reserved

Below code snippet shows all the three approaches to delete column from the WinForms FlexGrid

Insert ColumnTo insert a column in FlexGrid at a specific location you can use Insert method of the ColumnCollection class whichlets you specify the position where columns are to be inserted You can also insert multiple columns in the grid byusing the InsertRange method These methods add the unbound columns only even if the grid is a bound grid

Use any of the following approaches to insert a column in the WinForms FlexGrid at the specified location

方法1 列コレクションのRemoveメソッドを使用して2番目の列を削除します c1FlexGrid1ColsRemove(2)

方法2 Countプロパティを変更して最後の列を削除します c1FlexGrid1ColsCount -= 1

方法3 RemoveRangeメソッドを使用して2番目から始まる4つの列を削除します c1FlexGrid1ColsRemoveRange(2 4)

C

方法1 列コレクションのRemoveメソッドを使用して2番目の列を削除します c1FlexGrid1ColsRemove(2)

方法2 Countプロパティを変更して最後の列を削除します c1FlexGrid1ColsCount -= 1

方法3 RemoveRangeメソッドを使用して2番目から始まる4つの列を削除します c1FlexGrid1ColsRemoveRange(2 4)

VBNET

C1WinC1FlexGridColumn c

方法1 Insertメソッドを使用して2番目の位置に列を挿入します c = c1FlexGrid1ColsInsert(2) cCaption = Inserted Column

方法2 InsertRangeメソッドを使用して2番目の位置に3つの列を挿入します c1FlexGrid1ColsInsertRange(2 3)

C

Dim c As C1WinC1FlexGridColumn 方法1 Insertメソッドを使用して2番目の位置に列を挿入します c = c1FlexGrid1ColsInsert(2) cCaption = Inserted Column 方法2 InsertRangeメソッドを使用して2番目の位置に3つの列を挿入します c1FlexGrid1ColsInsertRange(2 3)

VBNET

FlexGrid for WinForms

38 Copyright copy GrapeCity Inc All rights reserved

Set Data TypeIn case of a bound FlexGrid data type of each bound column is automatically picked from the data source dependingon the data However in the case of unbound mode you can set the data type of columns by specifyingthe DataType property of Column class You can also set the Data Type property at design time by using theColumn Tasks menu For more information on tasks menus see Tasks Menus Note that when a particular data type isset to a FlexGrid column its cells accept the user input of keys accepted by the data type only For instance you cannot input alphabets in a Numeric type cell

Set the data type of an unbound column in WinForms FlexGrid as shown in the code below

Set Fixed ColumnFixed columns refer to the columns with non-editable cells which are always visible in the left hand side of the grideven if user scrolls the grid horizontally In FlexGrid fixed columns can be set using Fixed property ofthe ColumnCollection class This property accepts an integer value that specifies the number of columns to be fixed

Use the code below to set one column as fixed in the WinForms FlexGrid

Set Frozen ColumnFrozen columns similar to fixed columns are non-scrollable but can be edited by the user In FlexGrid frozen columnscan be set by using Frozen property provided by the ColumnCollection class

To set frozen columns in the WinForms FlexGrid use the code below

最初の列のデータ型を設定します c1FlexGrid1Cols[1]DataType = typeof(int)

C

最初の列のデータ型を設定しますc1FlexGrid1Cols(1)DataType = GetType(Integer)

VBNET

1つの列を固定列として設定しますc1FlexGrid1ColsFixed = 1

C

1つの列を固定列として設定しますc1FlexGrid1ColsFixed = 1

VBNET

最初の4列を静止として設定しますc1FlexGrid1ColsFrozen = 4

C

最初の4列を静止として設定しますc1FlexGrid1ColsFrozen = 4

VBNET

FlexGrid for WinForms

39 Copyright copy GrapeCity Inc All rights reserved

ユーザー操作

This topic discusses how you can let end users interact with the FlexGrid columns

Allow EditingBy default FlexGrid allows to edit all columns of the grid However you can choose to disable editing of a particularcolumn by setting AllowEditing property of the Column object to false You can also disable editing of the whole gridby setting the C1FlexGridAllowEditing property to false For more information on editing see Edit

Following code shows how to disable editing of WinForms FlexGrid while keeping only one column editable

Allow DraggingFlexGrid by default allows user to reorder columns by dragging a column header and dropping it to the targetposition However you can change this behavior by using the FlexGridAllowDragging propertyand ColumnAllowDragging property To disable dragging of a particular column you can set theColumnAllowDragging property of that column to false On the other hand setting the FlexGridAllowDraggingproperty to either Rows or None disables the column reordering at grid level This property accepts the valuesfrom AllowDraggingEnum You can also disable column reordering at design time by checking off the Enable ColumnReordering checkbox in the C1FlexGrid Tasks menu For more information on tasks menus see Tasks Menus

グリッド全体で編集を無効にしますc1FlexGrid1AllowEditing = false

3列目でのみ編集を有効にしますc1FlexGrid1Cols[3]AllowEditing = true

C

グリッド全体で編集を無効にしますc1FlexGrid1AllowEditing = False

3列目でのみ編集を有効にしますc1FlexGrid1Cols(3)AllowEditing = True

VBNET

FlexGrid for WinForms

40 Copyright copy GrapeCity Inc All rights reserved

Below code demonstrates how to enable dragging of columns in WinForms FlexGrid

Allow FreezingTo allow end user to freeze the columns at runtime you can use the AllowFreezing property of the C1FlexGrid classwhich accepts values from AllowFreezingEnum When this property is set to Columns or Both a lock sign appearswhen mouse is hovered over the edge of header column User can click and drag the lock sign to freeze the columns

Following code shows how to allow users to freeze the columns in WinForms FlexGrid

Allow PinningFlexGrid lets you allow your users to pin a particular column or column range at run time by using the AllowPinningproperty of the C1FlexGrid class Setting the property adds a Pin button( ) in the column header which allows usersto pin columns at run-time so they remain in view as the user scrolls the grid horizontally The property accepts itsvalues from AllowPinning enumeration which lets you set pinning for a single column or a column range Whenproperty is set to ColumnRange user can pin or unpin all the columns starting from left till the clicked column in onego

グリッド全体ですべての列のドラッグを許可します c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumColumns

特定の列のドラッグを無効にしますc1FlexGrid1Cols[3]AllowDragging = false

C

グリッド全体ですべての列のドラッグを許可します c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumColumns

特定の列のドラッグを無効にします c1FlexGrid1Cols(3)AllowDragging = False

VBNET

実行時に列のフリーズを許可します c1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumColumns

C

実行時に列のフリーズを許可しますc1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumColumns

VBNET

FlexGrid for WinForms

41 Copyright copy GrapeCity Inc All rights reserved

Use the code below to let user pin multiple columns in the WinForms FlexGrid

Allow SortingIn FlexGrid column sorting is enabled for the whole grid by default and value of AllowSorting property of theC1FlexGrid class is set to Auto In this mode user can sort a single column by clicking the column header andmultiple columns by holding the CTRL key while clicking the column headers On sorting multiple columns the gridshows sort index in the column header next to the sort direction glyph You can also choose to prevent sorting orsimply change the way the columns are sorted through AllowSortingEnum enumeration The AllowSortingEnumenumeration allows you to choose whether to auto sort columns sort single column multiple columns or columnrange or just prevent sorting

You can enable multi-column sorting in the WinForms FlexGrid using the code below When AllowSorting propertyis set to MultiColumn user may sort multiple columns by simply clicking on their headers one after the other

ユーザーが列範囲を固定できるようにしますc1FlexGrid1AllowPinning = C1WinC1FlexGridAllowPinningColumnRange

C

ユーザーが列範囲を固定できるようにしますc1FlexGrid1AllowPinning = C1WinC1FlexGridAllowPinningColumnRange

VBNET

グリッドで複数列の並べ替えを有効にしますc1FlexGrid1AllowSorting = C1WinC1FlexGridAllowSortingEnumMultiColumn

1列のみの並べ替えを無効にしますc1FlexGrid1Cols[1]AllowSorting = false

C

グリッドで複数列の並べ替えを有効にしますc1FlexGrid1AllowSorting = C1WinC1FlexGridAllowSortingEnumMultiColumn

1列のみの並べ替えを無効にしますc1FlexGrid1Cols(1)AllowSorting = False

VBNET

FlexGrid for WinForms

42 Copyright copy GrapeCity Inc All rights reserved

To disable sorting on a particular column you need to set the ColumnAllowSorting property of that column to falseFor more information on sorting see Sort

Allow FilteringFlexGrid doesnt allow filtering at runtime by default However you can enable it by settingthe C1FlexGridAllowFiltering property to true To define the type of filter you want to apply on a particularcolumn you can use the ColumnAllowFiltering property which accepts following values from the AllowFilteringenumeration

AllowFiltering Values Description

Default The grid automatically creates a filter of type ColumnFilter This filteris the combination of a value filter and a condition filter

ByValue The grid automatically creates a filter of type ValueFilter This filteroffers a checkbox list of values to choose from Values that are notchecked in the list are excluded from the filter output

ByCondition The grid automatically creates a filter of type ConditionFilter Thisfilter provides several options such as Equals is Greater thanContains Begins with etc to create conditions You can also combinetwo conditions by using the And and Or operators available in thefilter

Custom The grid does not create a filter automatically and allows you to defineyour own filter and then explicitly assign it to Filter property of theColumn class

None Filtering is disabled for the column

For more information on filtering see Filter

Following code shows how to enable filtering in the WinForms FlexGrid and how to apply filters

Allow ResizingBy default FlexGrid allows resizing of all columns of the grid To change this behavior you can use AllowResizingproperty of the C1FlexGrid class This property accepts values from the AllowResizingEnum enumeration which letsyou resize columns rows both or none The enumeration also gives you options to uniformly resize the rows columnsor both that is if you resize one of the columns or rows the grid automatically resizes rest of the columns or rows as

グリッドレベルでのフィルタリングを許可します c1FlexGrid1AllowFiltering = true

最初の列に条件フィルターを適用します c1FlexGrid1Cols[1]AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

C

グリッドレベルでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = True

最初の列に条件フィルターを適用しますc1FlexGrid1Cols(1)AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

VBNET

FlexGrid for WinForms

43 Copyright copy GrapeCity Inc All rights reserved

well FlexGrid also provides ColumnAllowResizing property which is a Boolean type property and lets you enable ordisable resizing of a particular row or column

Below code shows how to allow users to resize columns of WinForms FlexGrid

Enable Context MenuFlexGrid provides support for column context menu at run-time to facilitate quick actions related to columnoperations To enable the column context menu on right-click you need to set ColumnContextMenuEnabled propertyprovided by the C1FlexGrid class to true By default this property is set to false

The column context menu provides following options

Option Description

Sort Ascending Sorts the column in ascending order

Sort Descending Sorts the column in descending order

Group by This Groups the grid data based on column under mouse pointer

列と行のサイズを均一に変更できますc1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumBoth

最初の列のサイズ変更のみを無効にしますc1FlexGrid1Cols[1]AllowResizing = false

C

列と行のサイズを均一に変更できますc1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumBoth

最初の列のサイズ変更のみを無効にしますc1FlexGrid1Cols(1)AllowResizing = False

VBNET

FlexGrid for WinForms

44 Copyright copy GrapeCity Inc All rights reserved

Column

Ungroup Removes grouping from the grid data The option displays only when grid is in groupedstate

Hide this Column Hides the column under mouse pointer

Auto size Resizes the column according to the length of longest value

Auto size (allcolumns)

Resizes all columns according to the length of longest value in each of them

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = true

C

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = True

VBNET

Option Description

エディタ

This topic discusses various built-in editors of FlexGrid and operations related to them The topic also takes you through thesteps to apply custom editors in the FlexGrid columns

Built-in EditorsFlexGrid provides several built-in editors to enable efficient in-cell editing The grid uses TextBox control as its default editorHowever other built-in editors such as numeric date checkbox and combo box are also supported These editors areautomatically assigned generally based on the value of some specific properties such as DataType property of the column Thetable below summarizes the built-in editors provided by FlexGrid their brief description and the example codes demonstratingthem For more information about built-in editors and their customization click the corresponding hyperlink

Built-inEditor

Snapshot Description Sample Code

Checkbox Gets enabledautomatically whenDataType propertyof the Columnobject is set to

c1FlexGrid1Cols[colIndex]DataType =

typeof(Boolean)

FlexGrid for WinForms

45 Copyright copy GrapeCity Inc All rights reserved

Boolean

Numeric Gets enabledautomatically whenDataType propertyis set to a numericdata type such asInt or Decimal

c1FlexGrid1Cols[colIndex]DataType =

typeof(Int32)

Date Gets enabledautomatically if theDataType propertyof column is set toDate or DateTime

c1FlexGrid1Cols[colIndex]DataType =

typeof(DateTime)

ComboBox Gets enabled bysetting multiplevalues separated bypipe inthe ComboListproperty

c1FlexGrid1Cols[colIndex]ComboList =

Red|Green|Blue|Red|White

Mask Gets enabled whenthe EditMaskproperty of columnis set

c1FlexGrid1Cols[colIndex]EditMask =

(999) 999-9999

Mappedlist

Gets enabled whenthe DataMapproperty is set to anIDictionary objectwhich establishesmapping betweenvalues stored in thegrid and thosevisible to a user

ListDictionary customerNames = new

ListDictionary()

customerNamesAdd(AJK18F Sam

Anders)

customerNamesAdd(BBK21D Daneil)

customerNamesAdd(AEF25N Henry

Hussain)

customerNamesAdd(BZD42S Owen

Romanov)

customerNamesAdd(AKC16G Serena

Nguyen)

c1flexGrid1Cols[Name]DataMap =

customerNames

c1flexGrid1ShowButtons =

ShowButtonsEnumWithFocus

Cell Button Gets enabled whenthe ComboListproperty is set to anellipsis() whichautomaticallydisplays a cellbutton in editmode You can then

c1flexGrid1Cols[colIndex]ComboList

=

c1flexGrid1CellButtonClick +=

C1flexGrid1_CellButtonClick

FlexGrid for WinForms

46 Copyright copy GrapeCity Inc All rights reserved

capturethe CellButtonClickevent either toshow a dialog boxor to perform anyother operation

Custom EditorsFlexGrid control provides most of the commonly used editing options through the above-mentioned built-in editors However inaddition you can also use external controls as editors to meet the specialized editing needs Any control that derives from thebase Control class can be easily used as an editor This can be done at design time as well as through code In the examplebelow we are setting the C1ColorPicker control as a cell editor

At Design Time

1 Add the C1FlexGrid control and C1ColorPicker control to the form2 Select Designer option from the C1FlexGrid Tasks menu to open the C1FlexGrid Column Editor3 Select a column and switch to Properties pane on left hand side4 Navigate to the Editor property and set its value to instance of the C1ColorPicker control

At Run Time

To set an external control as editor through code create an instance of the control and assign it to the Editor property ofthe Column object

See the code below to know how to set an external control as editor in WinForms FlexGrid column

カスタムエディタとして使用するC1ColorPickerコントロールのインスタンスを作成します C1WinC1InputC1ColorPicker customeditor = new C1WinC1InputC1ColorPicker() カスタムエディタにEditorプロパティを割り当てます c1FlexGrid1Cols[1]Editor = customeditor

C

FlexGrid for WinForms

47 Copyright copy GrapeCity Inc All rights reserved

For controls which are not derived from the Control base class it is still possible to use them as editors usingIC1EmbeddedEditor interface You can even use the UITypeEditor classes as grid editors This way the FlexGrid control canuse virtually any control as a cell editor For more information about the implementation see the product sample named CustomEditors

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

カスタムエディタとして使用するC1ColorPickerコントロールのインスタンスを作成します Dim customeditor As C1WinC1InputC1ColorPicker = New C1WinC1InputC1ColorPicker()

カスタムエディタにEditorプロパティを割り当てます c1FlexGrid1Cols(1)Editor = customeditor

VBNET

チェックボックス

Display Checkbox for Boolean ValuesFlexGrid by default uses the checkbox editor for representing the Boolean values That is when the DataTypeproperty of a Row or Column object is set to Bool type a checkbox appears in the cells and user can toggle the valueof an editable cell simply by clicking it

To disable this default behavior and display text value instead of a checkbox in a Bool type you can set the Formatproperty of Row or Column object to string values

Default Checkbox Checkbox with Text Checkbox with Non-Boolean Value Three-state Checkbox

Use the code below to set checkbox type editor in a WinForms FlexGrid column and configure it further

データ型をブール値に設定します(チェックボックスを自動的に表示します)c1FlexGrid1Cols[Verified]DataType = typeof(Boolean)

チェックボックスを表示する代わりに文字列値を表示しますc1flexGrid1Cols[Verified]Format = YesNo ブール列のチェックボックスの横にあるテキストを有効にしますc1flexGrid1Cols[Verified]ImageAndText = true

C

データ型をブール値に設定します(チェックボックスを自動的に表示します)c1FlexGrid1Cols(Verified)DataType = GetType(Boolean)

チェックボックスを表示する代わりに文字列値を表示しますc1flexGrid1Cols(Verified)Format = YesNo

ブール列のチェックボックスの横にあるテキストを有効にしますc1flexGrid1Cols(Verified)ImageAndText = True

VBNET

FlexGrid for WinForms

48 Copyright copy GrapeCity Inc All rights reserved

Display Checkbox for Non-Boolean ValuesIn unbound mode you can display a checkbox along with any non-boolean text as well You can use the SetCellCheckmethod to add checkbox to any kind of cells Along with row and column index this method takes valueof CheckEnum enumeration as one of its parameters to specify the state of checkbox at the time of rendering

Following code demonstrates how you can display checkbox for non-boolean values

Set Checkbox AlignmentTo set position of checkbox in the cell you need to use ImageAlign property of the Row or Column object Thisproperty accepts values from the ImageAlignEnum enumeration which lets you hide tile stretch or position the image

Align the checkbox to display in center of a WinForms FlexGrid column using the code below

Change the Checkbox ImageTo change icon image of different states of checkbox you can use the GlyphEnum which can be accessed usingthe Glyphs property For more information about changing glyphs see Custom Glyphs

You can change the images to be used for various checkbox states in WinForms FlexGrid using the code below

チェックオン状態のセル(32)に2つの状態のチェックボックスを設定します c1flexGrid1SetCellCheck(3 2 CheckEnumChecked)

C

チェックオン状態のセル(32)に2つの状態のチェックボックスを設定しますc1flexGrid1SetCellCheck(3 2 CheckEnumChecked)

VBNET

チェックボックスをセルの右中央に揃えますc1flexGrid1Cols[Verified]ImageAlign = ImageAlignEnumRightCenter

C

チェックボックスをセルの右中央に揃えますc1flexGrid1Cols(Verified)ImageAlign = ImageAlignEnumRightCenter

VBNET

カスタム画像をチェックボックスアイコンとして設定します Image imgChk = new Bitmap(ResourcesImagescheckedpng) Image imgUnchk = new Bitmap(ResourcesImagesuncheckedpng) Image imgGray = new Bitmap(ResourcesImagesnullpng) c1flexGrid1Glyphs[GlyphEnumChecked] = imgChk c1flexGrid1Glyphs[GlyphEnumUnchecked] = imgUnchk c1flexGrid1Glyphs[GlyphEnumGrayed] = imgGray

C

カスタム画像をチェックボックスアイコンとして設定します Dim imgChk As Image = New Bitmap(ResourcesImagescheckedpng) Dim imgUnchk As Image = New Bitmap(ResourcesImagesuncheckedpng)

VBNET

FlexGrid for WinForms

49 Copyright copy GrapeCity Inc All rights reserved

Use Three State CheckboxIn addition to usual two state checkbox FlexGrid lets you create three state checkbox as well The simplest way ofenabling the third state is through the CheckEnum While a Boolean checkbox togglesbetween CheckEnumChecked and CheckEnumUnchecked states the three states of a three state checkbox arerepresented by CheckEnumTSChecked CheckEnumTSUnchecked and CheckEnumTSGrayed However in thiscase by default user can not go back to null after switching to checked or unchecked state once In order to cycle acheckbox between three states you need to handle the ValidateEdit event

Use the code below to create a three state checkbox in the WinForms FlexGrid

Dim imgGray As Image = New Bitmap(ResourcesImagesnullpng) c1flexGrid1Glyphs(GlyphEnumChecked) = imgChk c1flexGrid1Glyphs(GlyphEnumUnchecked) = imgUnchk c1flexGrid1Glyphs(GlyphEnumGrayed) = imgGray

private void c1FlexGrid1_ValidateEdit(object sender ValidateEditEventArgs e) if (c1FlexGrid1Cols[eCol]Name == Done) eCancel = true if (c1FlexGrid1[eRow eCol]Equals(false)) c1FlexGrid1[eRow eCol] = true else if (c1FlexGrid1[eRow eCol]Equals(true)) c1FlexGrid1[eRow eCol] = DBNullValue else if (c1FlexGrid1[eRow eCol]Equals(DBNullValue)) c1FlexGrid1[eRow eCol] = false

C

Private Sub c1FlexGrid1_ValidateEdit(ByVal sender As Object ByVal e As ValidateEditEventArgs) If c1FlexGrid1Cols(eCol)Name Is Done Then eCancel = True

If c1FlexGrid1(eRow eCol)Equals(False) Then c1FlexGrid1(eRow eCol) = True ElseIf c1FlexGrid1(eRow eCol)Equals(True) Then c1FlexGrid1(eRow eCol) = DBNullValue ElseIf c1FlexGrid1(eRow eCol)Equals(DBNullValue) Then c1FlexGrid1(eRow eCol) = False End If End IfEnd Sub

VBNET

数値

FlexGrid by default uses the numeric editor to edit the numeric data that is when the data type is set to any of the numeric types such as Int and Decimal Thisbehavior of FlexGrid is controlled by the EditOptions property which provides various editing options through the EditFlags enumeration One of the flagsprovided is UseNumericEditor As the default value of EditOptions property is All UseNumericEditor flag is always ON and hence grid automatically enablesthe numeric editor while editing the numeric data You can access the EditOptions property at design time as well as through code

FlexGrid for WinForms

50 Copyright copy GrapeCity Inc All rights reserved

Numeric Editor Numeric Editor with Format = C0 Numeric Editor with Spin Button Numeric Editor with Calculator

At Design Time

To enable or disable the numeric editor at design time you can access the EditOptions property from the Properties window

At Run Time

At run-time you need to set the UseNumericEditor flag On in the EditOptions property Use the code below to set EditOptions property in the WinFormsFlexGrid

Format Numeric CellTo format the data in a numeric cell FlexGrid provides the Format property of Column as well as Row object In case of the formats that support decimal valuessuch as numeric currency and exponential FlexGrid displays values up to two decimal places by default However you can specify the number of decimals todisplay by appending the value of Format property with that number For instance in order to display values up to three decimal places in a Number type cellyou specify value of Format property as N3 or n3

Note This property doesnt have any effect on the stored value but only on how value is displayed at the run time You can access the formatted valueof a cell using GetDataDisplay(Int32 Int32) method of the C1FlexGrid class

You can set the Format property at design time as well as through code Following table lists the commonly used formats for numeric cells

Format Value Description

Number N or n Specifies the formatting for simple numeric values

Currency C or c Specifies the formatting for monetary values

Exponential or Scientific E or e Specifies the formatting for values using scientific notations

Percentage P or p Specifies the formatting for percentage values

Custom User-defined Takes the value of format string from user

A custom string might require handling in the code

At Design Time

1 In design view click on the FlexGrid smart tag to open the C1FlexGrid Tasks menu2 Click the Column Tasks option and navigate to Format String property3 Click ellipsis button to open the Format String dialog

すべてのフラグをオンに設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsAll

UseNumericEditorフラグのみを設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsUseNumericEditor

C

すべてのフラグをオンに設定しますc1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsAll

UseNumericEditorフラグのみを設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsUseNumericEditor

VBNET

FlexGrid for WinForms

51 Copyright copy GrapeCity Inc All rights reserved

4 Select the required format from the list box on left say Currency5 Set the format specific properties on the right hand side of the dialog Decimal places in this case

At Run Time

To specify the format of a particular numeric type column set the Format property to any of the above mentioned values In this example we have set theformat of column 3 as currency without decimals

Following code shows how to set the format of a WinForms FlexGrid column

Input using Spin ButtonTo create a numeric editor which uses a spin button for input you need to assign instance of an external control such as NumericUpDown to the Editorproperty

Use the code below to create a numeric editor with spin button in the WinForms FlexGrid

Input using CalculatorTo allow user to give input using a calculator in a numeric editor you can use the C1NumericEdit control of C1Input library as an editor So just add thereference to C1WinC1Input and assign an instance of C1NumericEdit control to the Editor property For more information about using an external controlas editor see Custom Editors

To create a numeric editor with calculator use the code below

小数点なしの通貨形式を設定します c1FlexGrid1Cols[3]Format = C0

C

小数点なしの通貨形式を設定しますc1FlexGrid1Cols(3)Format = C0

VBNET

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols[2]Editor = new NumericUpDown()

C

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols(2)Editor = New NumericUpDown()

VBNET

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols[2]Editor = new C1NumericEdit()ShowUpDownButtons=false

C

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols(2)Editor = New C1NumericEdit() With ShowUpDownButtons = False

VBNET

日付

FlexGrid by default uses the Date editor for all the Date and DateTime type of data The Date editor consists of adropdown which opens a calendar when clicked and user can select the desired date by navigating through it Usercan also change the date month or year by simply selecting the corresponding part in the editor and pressing the upand down arrow keys

FlexGrid for WinForms

52 Copyright copy GrapeCity Inc All rights reserved

Default Date Editor Date Editor Without Calendar Date Editor with Spin Button

Use the code below to create a Date editor in a WinForms FlexGrid column

Input without Displaying CalendarAs mentioned earlier in FlexGrid a DateTime type cell automatically displays a dropdown calendar to receive theinput from user However in order to get a date input from user without displaying a calendar you can set a maskusing the EditMask property and then validate the input value using the ValidateEdit event

Following code demonstrates how to create a Date editor without calendar in WinForms FlexGrid

For more information about cell masks and validation see topics Mask and Validation respectively Another way ofhiding the calendar is to get user input using the spin buttons

Input using Spin ButtonBelow code shows how to create Date editor with spin button

To display spin buttons in a Date editor use the SetupEditor event to convert the editor into DateTimePicker and setits ShowUpDown property to true

Set the data type property to DateTime c1FlexGrid1Cols[1]DataType = typeof(DateTime)

C

Set the data type property to DateTimec1FlexGrid1Cols(1)DataType = GetType(Date)

VBNET

Set a mask on column c1flexGrid1Cols[3]EditMask = 00000000

C

Set a mask on columnc1flexGrid1Cols(3)EditMask = 00000000

VBNET

private void C1flexGrid1_SetupEditor(object sender RowColEventArgs e)

C

FlexGrid for WinForms

53 Copyright copy GrapeCity Inc All rights reserved

Set Date FormatTo set the format in a Date type column you need to set the Format property of the Column object

Following table lists the pre-defined formats

Format Value Example

Short Date d 11192003

Long Date D Friday November 19 2003

Short Time t 1215 AM

Long Time T 121530 AM

You can also create a custom format using the various custom format specifiers supported in the Net framework Fordetails see Custom date and time format strings on Microsoft website

Use the following code to create a custom date format in WinForms FlexGrid column

if (c1flexGrid1Cols[eCol]Name == DOB) Cast FlexGrids current cell editor var dateEditor = c1flexGrid1Editor as DateTimePicker

Show UpDown button (replacing the drop-down button for calendar) dateEditorShowUpDown = true

Private Sub C1flexGrid1_SetupEditor(ByVal sender As Object ByVal e As RowColEventArgs) If c1flexGrid1Cols(eCol)Name Is DOB Then Cast FlexGrids current cell editor Dim dateEditor = TryCast(c1flexGrid1Editor DateTimePicker)

Show UpDown button (replacing the drop-down button for calendar) dateEditorShowUpDown = True End IfEnd Sub

VBNET

Set a pre-defined format c1FlexGrid1Cols[DOB]Format = d Set a custom format c1FlexGrid1Cols[OrderDate]Format = ddMMyyyy

C

Set a pre-defined format c1FlexGrid1Cols(DOB)Format = d

Set a custom format c1FlexGrid1Cols(OrderDate)Format = ddMMyyyy

VBNET

FlexGrid for WinForms

54 Copyright copy GrapeCity Inc All rights reserved

Display Country-specific Date FormatAlthough abovementioned formats are the most commonly used date formats but there are cultures which preferusing their specific calendar and date formats in some cases such as Japan You can display those specific calendarsand date formats by using OwnerDrawCell event of the C1FlexGrid class and the SystemGlobalization namespaceThe namespace provides various classes to define culture related information including calendars and date formatsFor instance to display Japanese calendar and Japanese date format you can leveragethe SystemGlobalizationJapaneseCalendar class Similarly you can also display other calendars such as GregorianHebrew Hijri and Korean

Set the country specific date format in WinForms FlexGrid using the code below

Set MinMax DateTo set a range of valid values you can use the DateTimePicker control as editor and set its MinDate and MaxDate

c1flexGrid1Cols[DOB]Format = ddMMyyyy c1flexGrid1DrawMode = DrawModeEnumOwnerDraw c1flexGrid1OwnerDrawCell += C1flexGrid1_OwnerDrawCell private void C1flexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if (c1flexGrid1Cols[eCol]DataType == typeof(DateTime) ampamp eRow gt= c1flexGrid1RowsFixed) eText = DateTimeParse(eText)ToString(yyyy年MM月dd日(dddd) c)

C

C1FlexGrid1Cols(DOB)Format = ddMMyyyy C1FlexGrid1DrawMode = DrawModeEnumOwnerDraw

AddHandler C1FlexGrid1OwnerDrawCell AddressOf C1flexGrid1_OwnerDrawCell

Private Sub C1flexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If C1FlexGrid1Cols(eCol)DataType = GetType(DateTime) AndAlso eRow gt= C1FlexGrid1RowsFixed Then eText = DateTimeParse(eText)ToString(yyyy年MM月dd日(dddd) c) End If End Sub

VBNET

FlexGrid for WinForms

55 Copyright copy GrapeCity Inc All rights reserved

property

Use the code below to set a range of valid dates in WinForms FlexGrid

DateTimePicker dateTimePicker = new DateTimePicker() dateTimePickerFormat = DateTimePickerFormatShort

Sets Max and Min dates dateTimePickerMinDate = new DateTime(2015 05 01) dateTimePickerMaxDate = DateTimeToday

Assigns DateTimePicker control as editor for FirstOrderDate(date) column c1flexGrid1Cols[FirstOrderDate]Editor = dateTimePicker

C

Dim dateTimePicker As DateTimePicker = New DateTimePicker() dateTimePickerFormat = DateTimePickerFormat[Short]

Sets Max and Min dates dateTimePickerMinDate = New DateTime(2015 05 01) dateTimePickerMaxDate = DateToday

Assigns DateTimePicker control as editor for FirstOrderDate(date) column c1flexGrid1Cols(FirstOrderDate)Editor = dateTimePicker

VBNET

コンボボックス

ComboBox cell is a common way of providing the user with a well-defined list of possible values in the form of a drop-down list FlexGrid providesthis multi-option editor in various forms such as dropdown list dropdown combo ellipsis button or a textbox with ellipsis button

Default ComboBox Multi-column ComboBox ComboBox with custom BackColor ComboBox with Images

Display Dropdown List or ComboIn FlexGrid you can create a dropdown list by creating a string containing all the choices separated by pipe characters (for exampleTrue|False|Dont know) and assign it to the ComboList property of Row or Column object This causes the grid to display a drop-down buttonnext to the cell The user can click the dropdown button (or press F2) to display the list of choices available for that cell

Another common situation is where cells have a list of common values but users should be allowed to type a custom value as well This can beaccomplished with drop-down combos a combination of text box and drop-down list In FlexGrid you can create combos by starting the choicelist with a pipe character (for example |True|False|Dont know) and then assign it to the ComboList property

Following code shows how to create a dropdown list or combo editor in the WinForms FlexGrid

FlexGrid for WinForms

56 Copyright copy GrapeCity Inc All rights reserved

The ComboList property can also be set using the Combo List dialog at design time To access the Combo List dialog

1 Open the Column Tasks menu for column for which editor is to be set2 Go to the Combo List option and click the ellipsis button on the right hand side of the field3 Combo List dialog opens where you can specify the option values each in a new line4 You can also choose whether you want to display these values as a Dropdown List or Dropdown Combo Note that it also lets you create

cell button using Ellipsis Button or Textbox amp Ellipsis Button option

Display Multi-column ComboBoxIn FlexGrid you can also display multiple columns in a ComboBox using the MultiColumnDictionary class This class implementsthe IC1MultiColumnDictionary interface and has multiple overloads These overloads let you specify the data source object the key columncolumns that are to be displayed in multiple columns and the column to be displayed when ComboBox is closed

Display a multi-column combobox in a WinForms FlexGrid column using the code below

Note that the above code uses the data source object dt to supply data to the grid You can set up the data source as per your requirements

ドロップダウンリストとしてCustomerIDを割り当てますc1flexGrid1Cols[CustomerID]ComboList = AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

ドロップダウンコンボボックスとしてCustomerIDを割り当てパイプ文字|でリストを開始します c1flexGrid1Cols[CustomerID]ComboList = |AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

C

ドロップダウンリストとしてCustomerIDを割り当てますc1flexGrid1Cols(CustomerID)ComboList = AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

ドロップダウンコンボボックスとしてCustomerIDを割り当てパイプ文字|でリストを開始します c1flexGrid1Cols(CustomerID)ComboList = |AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

VBNET

string[] columnRange = new string[] City Country c1FlexGrid1Cols[City]DataMap = new MultiColumnDictionary(dt City columnRange 0)

C

Dim columnRange = New String() City Countryc1FlexGrid1Cols(City)DataMap = New MultiColumnDictionary(dt City columnRange 0)

VBNET

DataTable dt = new DataTable() dtColumnsAdd(CustomerID typeof(int)) dtColumnsAdd(ContactName typeof(string)) dtColumnsAdd(Designation typeof(string)) dtColumnsAdd(City typeof(string)) dtColumnsAdd(Country typeof(object))

サンプルデータ

C

FlexGrid for WinForms

57 Copyright copy GrapeCity Inc All rights reserved

Set Mapped Data in the ComboBoxTo set a ComboBox having display values different from the actual values you need to use the C1ComboBox as editor and leverageits ItemsDisplayMember and ItemsValueMember properties For instance the example below uses country names as display values while actualvalue is the dialing code of the corresponding country

Following code shows how to set the mapped data in combobox column of the WinForms FlexGrid

dtRowsAdd(1 Maria Anders Sales Representative Madrid Spain ) dtRowsAdd(2 Ana Trujillo Sales Associate Monterrey Mexico ) dtRowsAdd(3 Antonio Moreno Owner Dublin Ireland) dtRowsAdd(4 Thomas Hardy Sales Representative Bristol UK) dtRowsAdd(5 Patricio Simpson Marketing Manager Munich Germany) dtRowsAdd(6 Paolo Accorti Sales Representative Barcelona Spain) dtRowsAdd(7 Martine Ranceacute Owner Puebla Mexico) dtRowsAdd(8 Elizabeth Brown Marketing Manager London UK) dtRowsAdd(9 Jaime Yorres Order Administrator Vienna Austria) dtRowsAdd(10 Yvonne Moncada Marketing Manager Mexico Mexico) dtRowsAdd(11 Helen Bennett OwnerMarketing Cork Ireland) dtRowsAdd(12 Sergio Gutieacuterrezy Order Administrator Sao Paulo Brazil)

c1FlexGrid1DataSource = dt

Dim dt As DataTable = New DataTable()dtColumnsAdd(CustomerID GetType(Integer))dtColumnsAdd(ContactName GetType(String))dtColumnsAdd(Designation GetType(String))dtColumnsAdd(Country GetType(Object))dtColumnsAdd(City GetType(String))

サンプルデータdtRowsAdd(1 Maria Anders Sales Representative Spain Madrid)dtRowsAdd(2 Ana Trujillo Sales Associate Mexico Monterrey)dtRowsAdd(3 Antonio Moreno Owner Ireland Dublin)dtRowsAdd(4 Thomas Hardy Sales Representative UK Bristol)dtRowsAdd(5 Patricio Simpson Marketing Manager Germany Munich)dtRowsAdd(6 Paolo Accorti Sales Representative Spain Barcelona)dtRowsAdd(7 Martine Ranceacute Owner Mexico Puebla)dtRowsAdd(8 Elizabeth Brown Marketing Manager UK London)dtRowsAdd(9 Jaime Yorres Order Administrator Austria Vienna)dtRowsAdd(10 Yvonne Moncada Marketing Manager Mexico Mexico)dtRowsAdd(11 Helen Bennett OwnerMarketing Ireland Cork)dtRowsAdd(12 Sergio Gutieacuterrezy Order Administrator Brazil Sao Paulo)c1FlexGrid1DataSource = dt

VBNET

private void Form1_Load(object sender EventArgs e) 顧客データを取得します Customers = GetCustomers()

FlexGridにデータを入力します c1FlexGrid1DataSource = Customers

国とその国コードのコレクションを作成します ObservableCollectionltCountrygt countries = new ObservableCollectionltCountrygt() countriesAdd(new Country(1 USA)) countriesAdd(new Country(91 India)) countriesAdd(new Country(7 Russia))

C

FlexGrid for WinForms

58 Copyright copy GrapeCity Inc All rights reserved

Set ComboBox DimensionsTo set the height and width of combo box dropdown you need to assign an instance of ComboBox as an editor and then setthe DropDownHeight and DropDownWidth property of that instance

countriesAdd(new Country(54 Argentina)) countriesAdd(new Country(81 Japan)) countriesAdd(new Country(380 Ukraine)) countriesAdd(new Country(98 Iran)) countriesAdd(new Country(45 Denmark)) countriesAdd(new Country(84 Vietnam)) countriesAdd(new Country(49 Germany)) BindingSource countryBS = new BindingSource() countryBSDataSource = countries

C1Comboboxコントロールをインスタンス化して設定します C1ComboBox countryCodeCombo = new C1ComboBox() countryCodeComboItemsDataSource = countryBS

region Mapped Data using C1Combobox

国コードと国名をマッピングするためにプロパティを設定します countryCodeComboItemsDisplayMember = CountryName countryCodeComboItemsValueMember = CountryCode countryCodeComboTextDetached = true countryCodeComboTranslateValue = true

C1ComboboxをDiallingCode列のエディタとして設定します c1FlexGrid1Cols[DiallingCode]Editor = countryCodeCombo endregion

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) 顧客データを取得します Customers = GetCustomers()

FlexGridにデータを入力します c1FlexGrid1DataSource = Customers

国とその国コードのコレクションを作成します Dim countries As ObservableCollection(Of Country) = New ObservableCollection(Of Country)() countriesAdd(New Country(1 USA)) countriesAdd(New Country(91 India)) countriesAdd(New Country(7 Russia)) countriesAdd(New Country(54 Argentina)) countriesAdd(New Country(81 Japan)) countriesAdd(New Country(380 Ukraine)) countriesAdd(New Country(98 Iran)) countriesAdd(New Country(45 Denmark)) countriesAdd(New Country(84 Vietnam)) countriesAdd(New Country(49 Germany)) Dim countryBS As BindingSource = New BindingSource() countryBSDataSource = countries

C1Comboboxコントロールをインスタンス化して設定します Dim countryCodeCombo As C1ComboBox = New C1ComboBox() countryCodeComboItemsDataSource = countryBS

国コードと国名をマッピングするためにプロパティを設定します countryCodeComboItemsDisplayMember = CountryName countryCodeComboItemsValueMember = CountryCode countryCodeComboTextDetached = True countryCodeComboTranslateValue = True

C1ComboboxをDiallingCode列のエディタとして設定します c1FlexGrid1Cols(DiallingCode)Editor = countryCodeComboEnd Sub

VBNET

FlexGrid for WinForms

59 Copyright copy GrapeCity Inc All rights reserved

Use the code below to specify the height and width of the combobox to be displayed in the WinForms FlexGrid

Change Background Color or Font ColorTo change the background color or font color of the ComboBox list create an instance of ComboBox to assign it as editor Then set the BackColorand ForeColor property of that instance

Customize combobox in the WinForms FlexGrid by using the code below

Display Image in the ListTo display images in the ComboBox list you need to use the C1ComboBox as an editor and leverage its ItemsImageList property This property isof type ImageList class that acts as a container for the images which are stored in its Images collection First access the images stored in theproject resources through the ResourceManagerGetResourceSet method and create a collection of mapping between images and itscorresponding names The collection acts as a data source for ComboBox Now create an instance of the ImageList class add images to itsImages collection from data source and assign that instance of ImageList class to the ItemsImageList property to render images in the ComboBoxlist

Following code shows how to display images in the combobox lists of WinForms FlexGrid

ComboBox cb = (ComboBox)c1flexGrid1Editor cbDropDownWidth = 250 cbDropDownHeight = 200

C

Dim cb As ComboBox = CType(c1flexGrid1Editor ComboBox) cbDropDownWidth = 250 cbDropDownHeight = 200

VBNET

ComboBox comboBox = new ComboBox() comboBoxBackColor = ColorBlack comboBoxForeColor = ColorWhite

C

Dim comboBox As ComboBox = New ComboBox() comboBoxBackColor = ColorBlack comboBoxForeColor = ColorWhite

VBNET

コンボボックスに画像を入力します var itemsSource = new ListltFlaggt() ImageList imgFlag = new ImageList() imgFlagImagesClear() var rsrSet = ResourcesResourceManagerGetResourceSet(CultureInfoCurrentCulture true true)

foreach(DictionaryEntry entry in rsrSet) var img = entryValue as Image itemsSourceAdd(new Flag(entryKeyToString() img)) itemsSourceSort(new CompareFlag())

foreach (Flag entry in itemsSource) imgFlagImagesAdd(entryCountryName entryCountryFlag)

countryComboItemsImageList = imgFlag

C

FlexGrid for WinForms

60 Copyright copy GrapeCity Inc All rights reserved

Set Number of Displayed ItemsTo set the number of items to be displayed in a combo box you can use ComboBoxMaxDropDownItems property

Use the code below to limit the number of items to be displayed in combobox list of the WinForms FlexGrid

Sort the ComboBox ListTo sort the items in the ComboBox dropdown list you can use the C1ComboBox as editor and call the Sort method to sort the dropdown itemsgetting displayed in the ComboBox

To display sorted items in comboboxlist of the WinForms FlexGrid use the code below

countryComboItemMode = ComboItemModeHtmlPattern countryComboHtmlPattern = ltdiv ltdiv style=padding0pxgtltimg src=CountryName style=padding-right14pxgtCountryNameltdivgt

コンボボックスに画像を入力します Dim itemsSource = New List(Of Flag)()Dim imgFlag As ImageList = New ImageList()imgFlagImagesClear()Dim rsrSet = ResourcesResourceManagerGetResourceSet(CultureInfoCurrentCulture True True)

For Each entry As DictionaryEntry In rsrSet Dim img = TryCast(entryValue Image) itemsSourceAdd(New Flag(entryKeyToString() img))Next

itemsSourceSort(New CompareFlag())

For Each entry In itemsSource imgFlagImagesAdd(entryCountryName entryCountryFlag)Next

countryComboItemsImageList = imgFlagcountryComboItemMode = ComboItemModeHtmlPatterncountryComboHtmlPattern = ltdiv ltdiv style=padding0pxgtltimg src=CountryName style=padding-right14pxgtCountryNameltdivgt

VBNET

コンボボックスのドロップダウンに表示する国の数を設定します countryComboMaxDropDownItems = 10

C

コンボボックスのドロップダウンに表示する国の数を設定しますcountryComboMaxDropDownItems = 10

VBNET

C1ComboBox countryCombo = new C1ComboBox() countryComboDropDownStyle = DropDownStyleDropDownList Listltstringgt countries = new Listltstringgt USA Canada India Russia Japan Germany countriesSort() countryComboItemsDataSource = countries

C1ComboboxをCountry列のエディタとして設定します c1FlexGrid1Cols[Country]Editor = countryCombo

C

FlexGrid for WinForms

61 Copyright copy GrapeCity Inc All rights reserved

Get the Selected IndexTo get the selected index or value of the selected item you can use the SelectedIndex property or SelectedItem property of the ComboBoxEditorclass The example below uses the ComboCloseUp event to show a message box displaying the selected index and the selected item

Use the code below to fetch the index and value of selected item in combobox list of the WinForms FlexGrid

Dim countryCombo As C1ComboBox = New C1ComboBox() countryComboDropDownStyle = DropDownStyleDropDownList Dim countries As List(Of String) = New List(Of String) From USA Canada India Russia Japan Germany countriesSort() countryComboItemsDataSource = countries

C1ComboboxをCountry列のエディタとして設定します c1FlexGrid1Cols(Country)Editor = countryCombo

VBNET

private void C1FlexGrid1_ComboCloseUp(object sender C1WinC1FlexGridRowColEventArgs e) MessageBoxShow(Selected Index + c1FlexGrid1ComboBoxEditorSelectedIndex + n + Selected Item + c1FlexGrid1ComboBoxEditorSelectedItem)

C

Private Sub C1FlexGrid1_ComboCloseUp(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) MessageBoxShow(Selected Index amp c1FlexGrid1ComboBoxEditorSelectedIndex amp vbLf amp Selected Item + c1FlexGrid1ComboBoxEditorSelectedItem)End Sub

VBNET

マスク

Mask editor refers to pre-defined templates for getting input from users which also automatically validates the userinput as it is typed Mask strings have two types of characters literal characters and template characters While literalcharacters are the ones which become part of the input the template characters serve as placeholders for charactersbelonging to specific categories (for example digits or alphabets) For example the code below assigns a (999) 999-9999 editing mask to the first column which holds phone numbers Here special characters such as braces (()) andhyphen (-) are the literals and the digit 9 is a placeholder that stands for any digit

FlexGrid for WinForms

62 Copyright copy GrapeCity Inc All rights reserved

The FlexGrid control supports masked editing through the EditMask property which can be used with regular textfields and with drop-down combo fields To apply different masks within the same column you can trap the BeforEditevent and set the EditMask property to appropriate value

You can also set the EditMask property at design time using the Input Mask dialog You can access the dialog byclicking the ellipsis button against Edit Mask field in Column Tasks menu It also means that the Edit Mask field isspecific to the column selected at that time

Note that when the EditMask property is set to a non-empty string the grid uses the masked editor even if thecolumn contains DateTime values Usually grid uses the built-in Date editor to edit DateTime type cells

電話番号の編集マスクを設定します c1FlexGrid1Cols(1)EditMask = (999) 999-9999

C

電話番号の編集マスクを設定します c1FlexGrid1Cols(1)EditMask = (999) 999-9999

VBNET

マップリスト

Mapped lists refer to the mapping of data stored in the grid to the values visible to the user Such mapping is oftenused to display user-friendly values when actual data stored in the grid is either encoded or difficult to understand bythe user For instance in an employee record table it would be more convenient for administrative executive to seenames of the employees while database stores the employee IDs

FlexGrid for WinForms

63 Copyright copy GrapeCity Inc All rights reserved

Display Data MappingIn FlexGrid data mapping can be achieved by using the DataMap property This property contains reference to anIDictionary object that establishes mapping between database values and values to be displayed in the gridHashTable ListDictionary and SortedList are some examples of IDictionary objects which provide valid data maps

Following code demonstrates how to display the data mapped list in the WinForms FlexGrid

There is a difference in how HashTable ListDictionary and SortedList classes order the items So when these tables areused with editable columns the order of items rendering in the mapped list also differs depending upon the keys andclass used to create the list

Note that the keys in the data map must be of the same type as the cells being edited For example if a columncontains short integers (Int16) then any data maps associated with the column should have short integer keys

Display Image MappingTo display image mapping in a FlexGrid column you need to set the ImageMap property of Row or Column object toan IDictionary object that establishes mapping between images and the corresponding text values For example if acolumn contains country names you can use this property to display the corresponding flags You can controlwhether to show only images or images with text by using the ImageAndText property of the object

Create an image mapping in the WinForms FlexGrid using the code below

データマップを作成しますListDictionary customerNames = new ListDictionary()customerNamesAdd(AJK18F Sam Anders)customerNamesAdd(BBK21D Daneil)customerNamesAdd(AEF25N Henry Hussain)customerNamesAdd(BZD42S Owen Romanov)customerNamesAdd(AKC16G Serena Nguyen)

データマップをflexgrid列に割り当てますc1flexGrid1Cols[Name]DataMap = customerNames

C

データマップを作成しますDim customerNames As ListDictionary = New ListDictionary()customerNamesAdd(AJK18F Sam Anders)customerNamesAdd(BBK21D Daneil)customerNamesAdd(AEF25N Henry Hussain)customerNamesAdd(BZD42S Owen Romanov)customerNamesAdd(AKC16G Serena Nguyen)

データマップをflexgrid列に割り当てますc1flexGrid1Cols(Name)DataMap = customerNames

VBNET

Hashtable ht = new Hashtable() foreach (Row row in c1flexGrid1Rows) htAdd(row[CustomerID] LoadImage(row[Photo] as byte[])) ImageMapをPhoto列に割り当てます c1flexGrid1Cols[Photo]ImageMap = ht

C

FlexGrid for WinForms

64 Copyright copy GrapeCity Inc All rights reserved

アスペクト比を維持しながら画像をセルに合わせます c1flexGrid1Cols[Photo]ImageAlign = ImageAlignEnumScale c1flexGrid1Cols[Photo]Width = 80

Dim ht As Hashtable = New Hashtable()

For Each row As Row In c1flexGrid1Rows htAdd(row(CustomerID) LoadImage(TryCast(row(Photo) Byte()))) Next

ImageMapをPhoto列に割り当てます c1flexGrid1Cols(Photo)ImageMap = ht

アスペクト比を維持しながら画像をセルに合わせます c1flexGrid1Cols(Photo)ImageAlign = ImageAlignEnumScale c1flexGrid1Cols(Photo)Width = 80

VBNET

セルボタン

Cell button editor refers to a cell with an ellipsis button This editor comes to use when you need to get an operationdone or open a dialog on a button click Such dialogs generally contain multiple different options or settings for a userto choose from

Default Cell Button Cell Button with Text Cell Button with Custom Image

Display Cell ButtonIn FlexGrid you can display a cell button by setting the ComboList property to an ellipsis character You can alsouse a pipe character before ellipsis button to display an ellipsis with text box to let user enter his inputThe CellButtonClick event is fired when user clicks the cell button You can capture this event to implement thedesired operation or display a dialog of your choice

By default the cell button gets displayed when cell enters the edit mode However you can set the ShowButtonsproperty to Always to display the cell button even in non-edit mode

Use the code below to display cell button in a WinForms FlexGrid column

Mark列のComboListプロパティを設定してセルボタンを表示するようにします c1flexGrid1Cols[Mark]ComboList = セルボタンを常に表示できるようにします c1flexGrid1Cols[Mark]ShowButtons = ShowButtonsEnumAlways

エンドユーザーがセルボタンをクリックしたときに処理します c1flexGrid1CellButtonClick += C1flexGrid1_CellButtonClick

C

Mark列のComboListプロパティを設定してセルボタンを表示するようにしますc1flexGrid1Cols(Mark)ComboList =

VBNET

FlexGrid for WinForms

65 Copyright copy GrapeCity Inc All rights reserved

The ComboList property can also be set using the Combo List dialog at design time To access the Combo List dialog

1 Open the Column Tasks menu for column for which editor is to be set2 Go to the Combo List option and click the ellipsis button on the right hand side of the field3 Combo List dialog opens where you can specify the option values each in a new line4 You can also choose whether you want to display these values as an Ellipsis Button or Textbox amp Ellipsis

Button Note that it also gives you options to create Dropdown List and Dropdown Combo

The example below demonstrates change in back color and fore color of the current row on click of the cell buttonSimilarly you can perform the desired operation in the CellButtonClick event

セルボタンを常に表示できるようにしますc1flexGrid1Cols(Mark)ShowButtons = ShowButtonsEnumAlways

エンドユーザーがセルボタンをクリックしたときに処理しますc1flexGrid1CellButtonClick += C1flexGrid1_CellButtonClick

private void C1flexGrid1_CellButtonClick(object sender RowColEventArgs e) 次のコードは色を変更して現在の行をマークします if (c1flexGrid1Rows[eRow]StyleDisplayBackColor == ColorFromName(Window)) c1flexGrid1Rows[eRow]StyleNewBackColor = ColorGreen c1flexGrid1Rows[eRow]StyleNewForeColor = ColorWhite c1flexGrid1Rows[eRow]StyleNewBackColor = ColorFromName(Window) c1flexGrid1Rows[eRow]StyleNewForeColor = ColorFromName(WindowText)

C

FlexGrid for WinForms

66 Copyright copy GrapeCity Inc All rights reserved

Change Image of Cell ButtonBy default cell button displays an ellipsis However you can change the image of cell button usingthe CellButtonImage property

Set the image of cell button in the WinForms FlexGrid as shown in the code below

Private Sub C1flexGrid1_CellButtonClick(ByVal sender As Object ByVal e As RowColEventArgs) 次のコードは色を変更して現在の行をマークします If c1flexGrid1Rows(eRow)StyleDisplayBackColor Is ColorFromName(Window) Then c1flexGrid1Rows(eRow)StyleNewBackColor = ColorGreen c1flexGrid1Rows(eRow)StyleNewForeColor = ColorWhite End If

If True Then c1flexGrid1Rows(eRow)StyleNewBackColor = ColorFromName(Window) c1flexGrid1Rows(eRow)StyleNewForeColor = ColorFromName(WindowText) End IfEnd Sub

VBNET

CellButtonImageプロパティを設定してセルボタンの画像を定義しますImage imgCellBtn = new Bitmap(ResourcesImagesbuttonpng)c1flexGrid1CellButtonImage = imgCellBtn

C

CellButtonImageプロパティを設定してセルボタンの画像を定義しますDim imgCellBtn As Image = New Bitmap(ResourcesImagesbuttonpng)c1flexGrid1CellButtonImage = imgCellBtn

VBNET

検証

Data validation lets you control the data that a user can enter into a column cell There are various ways in which adata can be validated such as restricting invalid input keys showing the error or warning information or revert thevalue to original on getting an invalid input from the user

FlexGrid for WinForms

67 Copyright copy GrapeCity Inc All rights reserved

To implement validations such as specifying the range of acceptable values or defining the minimum string length ofinput FlexGrid provides EditorValidation property of the Column class The property is oftype ValidationRuleCollection class which consists of pre-defined rules for implementing enhanced data validation inFlexGrid columns For instance the sample code below demonstrates StringLength and Required validation rulesapplied to the Customer column using the EditorValidation property

Refer the code below to know how to add validation rules in WinForms FlexGrid columns

private void SetupGridColumns() var customerNameColumn = _flexCols[CustomerName] customerNameColumnCaption = Customer customerNameColumnEditorValidationAdd(new RequiredRule()) customerNameColumnEditorValidationAdd(new StringLengthRule() MinimumLength = 2 ) var customerIDColumn = _flexCols[CustomerID] customerIDColumnVisible = false var frequencyColumn = _flexCols[Frequency] frequencyColumnFormat = 0 frequencyColumnAllowEditing = false var ageColumn = _flexCols[Age] ageColumnEditorValidationAdd(new RequiredRule()) ageColumnEditorValidationAdd(new RangeRule() Minimum = 10 Maximum = 90 )

C

FlexGrid for WinForms

68 Copyright copy GrapeCity Inc All rights reserved

Another way of applying validation is by capturing the ValidateEdit event and checking the value of EditorTextproperty If value obtained is invalid set the Cancel parameter to true to keep the grid in editing mode until userenters a valid value Such validation can be used in scenarios such as setting the range of valid values validating thecurrent cell value based on another cell value For example the below sample code validates input into a currencycolumn to ensure that values entered are between 1000 and 10000

Use ValidateEdit event to check for valid values during edit mode of the WinForms FlexGrid cell as shown in the codebelow

Private Sub SetupGridColumns() Dim customerNameColumn = _flexCols(CustomerName) customerNameColumnCaption = Customer customerNameColumnEditorValidationAdd(New RequiredRule()) customerNameColumnEditorValidationAdd(New StringLengthRule() With MinimumLength = 2 ) Dim customerIDColumn = _flexCols(CustomerID) customerIDColumnVisible = False Dim frequencyColumn = _flexCols(Frequency) frequencyColumnFormat = 0 frequencyColumnAllowEditing = False Dim ageColumn = _flexCols(Age) ageColumnEditorValidationAdd(New RequiredRule()) ageColumnEditorValidationAdd(New RangeRule() With Minimum = 10 Maximum = 90 )End Sub

VBNET

private void _flex_ValidateEdit( object sender ValidateEditEventArgs e) 金額を検証します if (_flexCols[eCol]DataType == typeof(Decimal)) try Decimal dec = DecimalParse(_flexEditorText) if ( dec lt 1000 || dec gt 10000 ) MessageBoxShow(Value must be between 1000 and 10000) eCancel = true catch MessageBoxShow(Value not recognized as a Currency) eCancel = true

C

Private Sub _flex_ValidateEdit(ByVal sender As Object ByVal e As ValidateEditEventArgs)

VBNET

FlexGrid for WinForms

69 Copyright copy GrapeCity Inc All rights reserved

金額を検証します If _flexCols(eCol)DataType Is GetType(Decimal) Then

Try Dim dec As Decimal = DecimalParse(_flexEditorText)

If dec lt 1000 OrElse dec gt 10000 Then MessageBoxShow(Value must be between 1000 and 10000) eCancel = True End If

Catch MessageBoxShow(Value not recognized as a Currency) eCancel = True End Try End IfEnd Sub

データ注釈

Data annotation means adding meaningful metadata tags to the classes and other objects making it easier to bridgethe gap between models and views by performing data validation and displaying appropriate messages to the endusers For example you may use data annotations to specify how items should be formatted what their captionsshould be whether they should be editable or not

FlexGrid supports multiple data annotation attributes used for customizing data classes displaying data from sourceand setting validation rules To use the attributes in your project you need to add a reference to theSystemComponentModelDataAnnotations assembly and then add the attributes to your data objects in the code

Note The C1FlexGrid supports the annotations defined in NET 4SystemComponentModelDataAnnotations should be version 4000 or higher

Listed below are some of the major annotation attributes that are supported in FlexGrid control Cilck herefor complete list of DataAnnotation attributes

FlexGrid for WinForms

70 Copyright copy GrapeCity Inc All rights reserved

Attribute Name Functionality in FlexGrid

Association Specifies that an entity member represents a data relationship such as a foreignkey relationship

Display Provides a general-purpose attribute that lets you specify localizable strings fortypes and members of entity partial classes

DisplayFormat Specifies how data fields are displayed and formatted by ASPNET Dynamic Data

DisplayColumn Specifies the column that is displayed in the referred table as a foreign-keycolumn

Editable Indicates whether a data field is editable

Key Denotes one or more properties that uniquely identify an entity

Validation

RequiredAttributeStringLengthAttributeRangeAttributeRegularExpressionAttributeMinLengthAttributeMetaDataAttributeMaxLengthAttributeEmailAddressAttributeCompareAttributeDataTypeAttribute

The data annotation validation attributes are used as validation rules in FlexGridoperations

The following code example shows how data annotation feature works in WinForms FlexGrid control

自動生成されたCustomerName列ヘッダに「Customer」と表示されます この列には少なくとも2つの記号の長さが最小の空でない文字列も必要です[Display(Name = Customer)][Required][StringLength(intMaxValue MinimumLength = 2)]

public string CustomerName get set 自動生成されたCustomerID列は非表示になります[Display(AutoGenerateField = false)]public int CustomerID get set

自動生成された「Frequency」列にはパーセンテージで書式設定された値が表示されます また編集を許可しません[DisplayFormat(DataFormatString = 0)][Editable(false)]public double Frequency get set

自動生成された「Age」列は事前定義された範囲の値を許可します[Required][Range(10 90)]public int Age get set サンプルデータを作成しますpublic static BindingListltDatagt GetSampleData(int cnt) var list = new BindingListltDatagt() var rnd = new Random()

C

FlexGrid for WinForms

71 Copyright copy GrapeCity Inc All rights reserved

for (int i = 0 i lt cnt i++) var item = new Data() itemCustomerName = _firstNames[rndNext(0 _firstNamesLength)] + + _lastNames[rndNext(0 _lastNamesLength)] itemCustomerID = i itemFrequency = rndNextDouble() itemAge = rndNext(10 91) listAdd(item) return list

自動生成されたCustomerName列ヘッダに「Customer」と表示されます この列には少なくとも2つの記号の長さが最小の空でない文字列も必要です ltDisplay(Name=Customer)gt ltRequiredgt ltStringLength(IntegerMaxValue MinimumLength=2)gt Public Property CustomerName As String 自動生成されたCustomerID列は非表示になります ltDisplay(AutoGenerateField=False)gt Public Property CustomerID As Integer 自動生成された「Frequency」列にはパーセンテージで書式設定された値が表示されます また編集を許可しません ltDisplayFormat(DataFormatString=0)gt ltEditable(False)gt Public Property Frequency As Double 自動生成された「Age」列は事前定義された範囲の値を許可します ltRequiredgt ltRange(10 90)gt Public Property Age As Integer

サンプルデータを作成します Public Shared Function GetSampleData(ByVal cnt As Integer) As BindingList(Of Data) Dim list = New BindingList(Of Data)() Dim rnd = New Random()

For i As Integer = 0 To cnt - 1 Dim item = New Data() itemCustomerName = _firstNames(rnd[Next](0 _firstNamesLength)) amp + _lastNames(rnd[Next](0 _lastNamesLength)) itemCustomerID = i itemFrequency = rndNextDouble() itemAge = rnd[Next](10 91) listAdd(item) Next

Return list End Function

VBNET

スパークライン

Sparklines are the miniature charts visually representing a series of values to show trends such as periodic fluctuationsor to highlight maximum or minimum values of the data series In grids sparklines are specially useful as they easily fitin a single cell and can help identify the data patterns at a glance

FlexGrid for WinForms

72 Copyright copy GrapeCity Inc All rights reserved

FlexGrid for WinForms lets you display sparklines in columns by setting ShowSparkline property of the Column classto true You can also set the type of sparkline using SparklineType property of the Sparkline class FlexGrid supportsthree types of sparklines which are

Line Similar to line chart line sparkline indicates change in values over a period of time with the help of a lineColumn Similar to column charts column sparkline uses vertical columns to demonstrate pattern acrossdifferent categoriesWinLoss Similar to column sparkline winloss sparkline uses vertical columns to represent values However itdoes not indicate the magnitude and is generally used to indicate the binary data

To display the data markers on sparkline you can set the ShowMarkers property to true The Sparkline class alsoprovides properties to highlight the first last highest lowest or negative data points by displaying them in differentformat You can even style the sparklines using the Styles property

Below code shows how to add sparkline to the WinForms FlexGrid columns

WinLossSparklineを表示するようにプロパティを設定します c1FlexGrid1Cols[2]ShowSparkline = true c1FlexGrid1Cols[2]SparklineSparklineType = SparklineTypeWinLoss c1FlexGrid1Cols[2]SparklineStylesSeriesColor = ColorGreen c1FlexGrid1Cols[2]SparklineShowNegative = true

C

WinLossSparklineを表示するようにプロパティを設定します c1FlexGrid1Cols(2)ShowSparkline = True c1FlexGrid1Cols(2)SparklineSparklineType = SparklineTypeWinLoss c1FlexGrid1Cols(2)SparklineStylesSeriesColor = ColorGreen c1FlexGrid1Cols(2)SparklineShowNegative = True

VBNET

ヘッダとフッタ

Column header refers to the fixed rows on the top of the grid which contains a caption string sort glyph etc

In FlexGrid by default the top row with zero index is allocated for the column header However you can span the header to other rows aswell by specifying them as fixed To set more than one rows as fixed you need to set the Fixed property of RowCollection class to an integergreater than 1

FlexGrid for WinForms

73 Copyright copy GrapeCity Inc All rights reserved

Set Header TextFlexGrid when in bound mode reads the field names from the data source and renders them as column header text However youcan explicitly set Caption property of the Row class to overwrite field name string from the data source In case of unbound grid as well theCaption property specifies the header text Note that this property sets the value of cells in the default header row at zero index To setvalue in the other fixed row cells you need to use the usual value allocation ways of FlexGrid For more information on how to set cellvalues see Set Value in Cell

Specify the header rows and set the header text in WinForms FlexGrid using the code below

Merge Column HeaderFlexGrid provides the AllowMerging property for Row object which specifies whether it is allowed to merge cells in a particular row (in thiscase the header row) or not Once you have allowed merging in the header row set either AllowMerging or AllowMergingFixed propertyof C1FlexGrid class to FixedOnly Availability of these two properties in the FlexGrid control offers you more flexibility to implement multiplelogics related to merging For more information on merging cells see Merge

Use the code below to merge column headers in the WinForms FlexGrid

Wrap Column Header Text

2つの行を列ヘッダ行として設定しますc1FlexGrid1RowsFixed = 2 最初の列のヘッダとサブヘッダを設定しますc1FlexGrid1Cols [1] Caption = Column Header 1c1FlexGrid1 [11] = Column Sub-header 1

C

2つの行を列ヘッダー行として設定します c1FlexGrid1RowsFixed = 2

最初の列のヘッダとサブヘッダを設定します c1FlexGrid1Cols(1)Caption = Column Header 1 c1FlexGrid1(1 1) = Column Sub-header 1

VBNET

ヘッダ行でのマージを許可しますc1FlexGrid1Rows[0]AllowMerging = true

グリッドのAllowMergingまたはAllowMergingFixedプロパティを設定して固定行のみを結合します c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

ヘッダ行でのマージを許可しますc1FlexGrid1Rows(0)AllowMerging = True

グリッドのAllowMergingまたはAllowMergingFixedプロパティを設定して固定行のみを結合します c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

FlexGrid for WinForms

74 Copyright copy GrapeCity Inc All rights reserved

To wrap the text in column header access the CellStyle item Fixed of the CellStyleCollection class and set its WordWrap property totrue Note that to view the wrapped text properly you need to adjust the row height or just call the AutoSizeRow() method to automaticallyresize the row according to the text length

Use the code below to wrap header text of the WinForms FlexGrid columns

Style Column HeaderTo style the column header you can access the CellStyle item Fixed of the CellStyleCollection class and set various styling relatedproperties for same such as Font ForeColor and TextEffect

Customize column header of the WinForms FlexGrid using the code below

Set Column FooterColumn Footer refers to the last row of the grid which displays additional information about the whole column Most common use ofcolumn footer is to show the summary of column data

In FlexGrid you can create the column footer by using Footers property of the C1FlexGrid class FlexGrid lets you choose whether toscroll the footer along with rows or keep it fixed at the bottom of the grid by using Fixed property of the Footers class This class alsoprovides the Descriptions property which accesses the FooterDescription collection to set the additional information such as Caption Todisplay aggregate result in the column footer through various aggregate functions you must access the AggregateDefinition collection

列のキャプションを設定しますc1FlexGrid1Cols[3]Caption = Large Text for Column Header Text Wrapping

行の高さを設定しますc1FlexGrid1Rows[0]Height = 50

固定の行と列のワードラップを設定しますc1FlexGrid1Styles[Fixed]WordWrap = true

C

列のキャプションを設定しますc1FlexGrid1Cols(3)Caption = Large Text for Column Header Text Wrapping

行の高さを設定しますc1FlexGrid1Rows(0)Height = 50

固定の行と列のワードラップを設定しますc1FlexGrid1Styles(Fixed)WordWrap = True

VBNET

ヘッダテキストのフォントを設定しますc1FlexGrid1Styles[Fixed]Font = new Font(Tahoma 10 FontStyleBold) ヘッダテキストの前色を設定しますc1FlexGrid1Styles[Fixed]ForeColor = ColorAqua ヘッダーテキストの背景色を設定しますc1FlexGrid1Styles[Fixed]BackColor = ColorBlue

ヘッダテキストにテキスト効果を適用しますc1FlexGrid1Styles[Fixed]TextEffect = C1WinC1FlexGridTextEffectEnumRaised

C

ヘッダテキストのフォントを設定します c1FlexGrid1Styles(Fixed)Font = New Font(Tahoma 10 FontStyleBold)

ヘッダテキストの前色を設定します c1FlexGrid1Styles(Fixed)ForeColor = ColorAqua

ヘッダーテキストの背景色を設定します c1FlexGrid1Styles(Fixed)BackColor = ColorBlue

ヘッダテキストにテキスト効果を適用します c1FlexGrid1Styles(Fixed)TextEffect = C1WinC1FlexGridTextEffectEnumRaised

VBNET

FlexGrid for WinForms

75 Copyright copy GrapeCity Inc All rights reserved

using Aggregates property of the FooterDescription class Aggregate functions can be specified using the Aggregate property whichaccepts values from AggregateEnum enumeration

Following code shows how to add a column footer in the WinForms FlexGrid

列にフッタを追加しますc1FlexGrid1FootersDescriptionsAdd(new C1WinC1FlexGridFooterDescription() Caption = Total ) フッタに集計を適用しますc1FlexGrid1FootersDescriptions[0]AggregatesAdd(new C1WinC1FlexGridAggregateDefinition() Column = 4 Aggregate = C1WinC1FlexGridAggregateEnumSum )

C

列にフッタを追加しますc1FlexGrid1FootersDescriptionsAdd(New C1WinC1FlexGridFooterDescription() With Caption = Total )

フッタに集計を適用しますc1FlexGrid1FootersDescriptions(0)AggregatesAdd(New C1WinC1FlexGridAggregateDefinition() With Column = 4 Aggregate = C1WinC1FlexGridAggregateEnumSum )

VBNET

サイズ変更

Set Column WidthFlexGrid provides the DefaultSize property of ColumnCollection class to set the column width across the grid You canalso specify the width of a particular column by setting the Width property of the Column class Default value ofWidth property is -1 which indicates that the column is taking width specified by the DefaultSize property The Widthproperty is also available at design time through the C1FlexGrid Column Editor For more information on columneditor see Editors

Use the code below to set the default width of a column of the WinForms FlexGrid

Auto-adjust Column WidthTo adjust the column width according to the text length FlexGrid provides the AutoSizeCol() and AutoSizeCols()methods While AutoSizeCol() method automatically adjusts width of the specified column the AutoSizeCols()method is used for cell ranges

Following code shows how you can auto adjust the column widths according to the text length in the WinFormsFlexGrid

すべての列のデフォルト幅を設定しますc1FlexGrid1ColsDefaultSize = 110最初の列の幅を設定しますc1FlexGrid1Cols [1] Width = 30

C

すべての列のデフォルト幅を設定します c1FlexGrid1ColsDefaultSize = 110最初の列の幅を設定します c1FlexGrid1Cols(1)Width = 30

VBNET

FlexGrid for WinForms

76 Copyright copy GrapeCity Inc All rights reserved

Set MinMax Column WidthFlexGrid allows you to set bounds to the column width by using the MinSize and MaxSize propertiesof ColumnCollection This feature is especially useful in scenarios such as when AllowResizing property is set to trueor while using the AutoSizeCol or AutoSizeCols method

Specify the bounds of column width in the WinForms FlexGrid using the code below

Star SizingStar sizing refers to proportional sizing of grid columns to occupy the available space so that layout of grid remainssame even on resizing For instance consider a grid with 5 columns whose star sizes are specified as 3 2 and In this case first fourth and fifth column always take the same width and grid allocates thrice the width of firstcolumn to the second and twice the width to third column

テキストの長さに応じて最初の列の幅を自動調整しますc1FlexGrid1AutoSizeCol(1) 列の幅を1番目から4番目まで自動調整しますc1FlexGrid1AutoSizeCols(1 4 2)

すべての列の幅を自動調整します c1FlexGrid1AutoSizeCols()

C

テキストの長さに応じて最初の列の幅を自動調整しますc1FlexGrid1AutoSizeCol(1)

列の幅を1番目から4番目まで自動調整しますc1FlexGrid1AutoSizeCols(1 4 2)

すべての列の幅を自動調整します c1FlexGrid1AutoSizeCols()

VBNET

列コレクションの最小幅を設定します c1FlexGrid1ColsMinSize = 20 列コレクションの最大幅を設定します c1FlexGrid1ColsMaxSize = 60

C

列コレクションの最小幅を設定します c1FlexGrid1ColsMinSize = 20

列コレクションの最大幅を設定します c1FlexGrid1ColsMaxSize = 60

VBNET

FlexGrid for WinForms

77 Copyright copy GrapeCity Inc All rights reserved

FlexGrid provides the StarWidth property of Column class to specify the star sizes of columns To restrict the widthsfrom getting too narrow or too wide you can set the MinWidth and MaxWidth properties These properties are alsoavailable through the C1FlexGrid Column Editor For more information on column editor see Editors

Set star sizing or proportional sizing in the WinForms FlexGrid columns using the code below

列のスターサイズを設定しますc1FlexGrid1Cols[1]StarWidth = c1FlexGrid1Cols[2]StarWidth = 3c1FlexGrid1Cols[3]StarWidth = 2c1FlexGrid1Cols[4]StarWidth = c1FlexGrid1Cols[5]StarWidth =

列が狭くなりすぎないようにMinWidthプロパティを設定しますc1FlexGrid1Cols[1]MinWidth = 50

C

列のスターサイズを設定しますc1FlexGrid1Cols(1)StarWidth = c1FlexGrid1Cols(2)StarWidth = 3c1FlexGrid1Cols(3)StarWidth = 2c1FlexGrid1Cols(4)StarWidth = c1FlexGrid1Cols(5)StarWidth =

列が狭くなりすぎないようにMinWidthプロパティを設定しますc1FlexGrid1Cols(1)MinWidth = 50

VBNET

FlexGrid for WinForms

78 Copyright copy GrapeCity Inc All rights reserved

A grid control is a collection of rows and columns Columns generally contain a particular type of information through out while rows are used to recorddifferent types of information about a particular item

In FlexGrid the collection of rows is represented by the RowCollection class which can be accessed through Rows property of the C1FlexGrid class Thissection discusses the various operations that can be performed on rows

Topic Snapshot Content

Basic Operations Discusses about how to perform basic row operations

Set Row CountAdd RowDelete RowInsert RowSet Data TypeSet Fixed RowSet Frozen Row

User Interaction Discusses about operations that can be performed by the end-user at run time

Allow AddingAllow DeletingAllow DraggingAllow FreezingAllow Resizing

Header Discusses about how to set row header and perform other related operations

Set Header TextMerge Row HeaderWrap Row Header TextStyle Row Header

Row Detail Discusses how to display additional information using row detail feature

In-form EditingHierarchical ViewCustom Row Details

Sizing Discusses about various aspects of row sizing

Set Row HeightAuto-adjust Row HeightSet MinMax Row Height

基本操作

This topic discusses various basic operations which can be performed on a row

Set Row CountWhen grid is bound to a data source the number of rows is determined by the number of records available in thedata source However in the case of unbound mode you can set any integer value in Count property ofthe RowCollection class to set the number of rows to be displayed in the grid

Use the code below to set row count in the WinForms FlexGrid

Set row count c1FlexGrid1RowsCount = 15

C

VBNET

FlexGrid for WinForms

79 Copyright copy GrapeCity Inc All rights reserved

Add RowFlexGrid provides various ways to add a new row at runtime You can either use Add method of the RowCollectionclass or AddItem method of the C1FlexGrid class to add a new record In the unbound mode you can also incrementthe value of Count property to add new rows Note that all these ways add rows towards the end of the grid To inserta row at a specific location see Insert Row Also note that an exception is thrown if a new row is added to a boundgrid using Count property

Add a row to WinForms FlexGrid using any of these approaches shown in the code below

Delete RowTo delete a particular row from the grid you can use Remove method of the RowCollection class and specify the rowyou want to delete as its parameter The RowCollection class also provides RemoveRange method which allows you

Set row countc1FlexGrid1RowsCount = 15

Approach1 Use the RowCollectionAdd method to add row C1WinC1FlexGridRow r r = c1FlexGrid1RowsAdd() Set data r[1] = New Row 2

Approach2 Use AddItem method to add row and set data c1FlexGrid1AddItem( + t + New Row 1) Approach3 Use the RowCollectionCount property to add row c1FlexGrid1RowsCount += 1 Set data c1FlexGrid1[c1FlexGrid1RowsCount - 1 1] = New Row 3

C

Approach1 Use the RowCollectionAdd method to add row Dim r As C1WinC1FlexGridRow r = c1FlexGrid1RowsAdd()

Set data r(1) = New Row 2

Approach2 Use AddItem method to add row and set data c1FlexGrid1AddItem( amp vbTab amp New Row 1)

Approach3 Use the RowCollectionCount property to add row c1FlexGrid1RowsCount += 1

Set data c1FlexGrid1(c1FlexGrid1RowsCount - 1 1) = New Row 3

VBNET

FlexGrid for WinForms

80 Copyright copy GrapeCity Inc All rights reserved

to remove a range of rows using a single call Similarly you can also use RemoveItem method of the C1FlexGridclass to remove a specific row In the unbound grid you can reduce the number of rows by changing the value ofCount property

Following code gives different approaches to delete row from the WinForms FlexGrid

Insert RowTo insert a row in FlexGrid at a specific location you can use Insert method of the RowCollection class which lets youspecify the position where rows are to be inserted You can also insert multiple rows in the grid by usingthe InsertRange method

Below code demonstrates how to insert a row at a particular position in the WinForms FlexGrid

Approach1 Remove second row using RowCollectionRemove methodc1FlexGrid1RowsRemove(2)

Approach1 Remove second row using the RemoveItem methodc1FlexGrid1RemoveItem(2)

Approach3 Remove 3 rows starting from second using the RemoveRange methodc1FlexGrid1RowsRemoveRange(2 3) Approach4 Remove last row using the RowCollectionCount property c1FlexGrid1RowsCount -= 1

C

Approach1 Remove second row using RowCollectionRemove method c1FlexGrid1RowsRemove(2)

Approach1 Remove second row using the RemoveItem method c1FlexGrid1RemoveItem(2)

Approach3 Remove 3 rows starting from second using the RemoveRange method c1FlexGrid1RowsRemoveRange(2 3)

Approach4 Remove last row using the RowCollectionCount property c1FlexGrid1RowsCount -= 1

VBNET

C1WinC1FlexGridRow r Approach1 Use the Insert method to insert row at second position r = c1FlexGrid1RowsInsert(2) r[1] = Inserted row Approach2

C

FlexGrid for WinForms

81 Copyright copy GrapeCity Inc All rights reserved

Set Data TypeIn case of a bound FlexGrid data type of each bound column is automatically picked from the data source dependingon the data However in the case of unbound mode you can set the data type of rows or columns by specifyingthe DataType property of Row or Column class respectively Note that when data type is set for both rows andcolumns column settings take preference over row settings

Use the code below to set data type of a WinForms FlexGrid row

Set Fixed RowFixed rows refer to the rows with non-editable cells which are always visible on top of the grid even when user scrollsdown the grid In FlexGrid fixed rows can be set using Fixed property of the RowCollection class This propertyaccepts an integer value that specifies the number of rows to be fixed

Set fixed rows in the WinForms FlexGrid using the code below

Set Frozen RowFrozen rows similar to fixed rows are non-scrollable but can be edited by the user In FlexGrid frozen rows can be set

Use the InsertRange method to add three rows at second position c1FlexGrid1RowsInsertRange(2 3)

Dim r As C1WinC1FlexGridRow Approach1 Use the Insert method to insert row at second position r = c1FlexGrid1RowsInsert(2) r(1) = Inserted row

Approach2 Use the InsertRange method to add three rows at second position c1FlexGrid1RowsInsertRange(2 3)

VBNET

C1WinC1FlexGridRow r r = c1FlexGrid1RowsAdd() rDataType = typeof(int)

C

Dim r As C1WinC1FlexGridRow r = c1FlexGrid1RowsAdd() rDataType = GetType(int)

VBNET

Set three rows as fixed c1FlexGrid1RowsFixed = 3

C

Set three rows as fixedc1FlexGrid1RowsFixed = 3

VBNET

FlexGrid for WinForms

82 Copyright copy GrapeCity Inc All rights reserved

by using Frozen property provided by the RowCollection class

Use the code below to set frozen rows in the WinForms FlexGrid

Set first two rows as frozen c1FlexGrid1RowsFrozen = 2

C

Set first two rows as frozen c1FlexGrid1RowsFrozen = 2

VBNET

ユーザー操作

This topic discusses how you can let end-users interact with the FlexGrid rows

Allow AddingBy default FlexGrid does not allow end-user to add new row to the grid To provide an option to add rows at runtimeyou can set AllowAddNew property of the C1FlexGrid class to true FlexGrid also provides a design-time optionEnable Adding Rows in C1FlexGrid Tasks menu to allow adding new row by the end-user For more information ontask menus see Tasks Menus Moreover you can also set watermark text to be displayed in the new row templatethrough NewRowWatermark property

Use the code below to allow users to add rows in WinForms FlexGrid at run-time

Allow user to add rows c1FlexGrid1AllowAddNew = true Set watermark in the template new row c1FlexGrid1NewRowWatermark = Add new row

C

Allow user to add rows c1FlexGrid1AllowAddNew = True

Set watermark in the template new row

VBNET

FlexGrid for WinForms

83 Copyright copy GrapeCity Inc All rights reserved

Allow DeletingFlexGrid by default does not allow end-user to delete rows from the grid However if your application requires youcan let the end-user delete the selected rows through Delete key by setting AllowDelete property to true You canalso enable row deletion by checking ON the Enable Deleting Rows checkbox on the C1FlexGrid Tasks menu

Following code shows how to allow users to delete rows from WinForms FlexGrid at run-time

Allow DraggingFlexGrid by default does not allow user to rearrange rows by dragging However you can change this behavior inunbound grid by using the FlexGridAllowDragging property and RowAllowDragging property To enable dragging ofgrid rows you can set the FlexGridAllowDragging property to either Rows or Both This property accepts the valuesfrom AllowDraggingEnum You can also disable dragging of a particular row by setting the RowAllowDraggingproperty to false

Note As moving a row is not allowed in bound mode the bound grid throws an exception on dragging arow To implement dragging in bound mode see the blog Drag and Drop Rows in C1Flexgrid

Let users drag the rows in an unbound WinForms FlexGrid at run-time by using the code below

Allow FreezingTo allow end user to freeze the rows at runtime you can use AllowFreezing property of the C1FlexGrid class whichaccepts values from AllowFreezingEnum When this property is set to Rows or Both a lock sign appears when mouseis hovered over the edge of header row End-user can click and drag the lock sign to freeze the rows

Use the code below to allow your users to freeze the WinForms FlexGrid rows at run-time

c1FlexGrid1NewRowWatermark = Add new row

Allow user to delete rowsc1FlexGrid1AllowDelete = true

C

Allow user to delete rowsc1FlexGrid1AllowDelete = True

VBNET

Allow dragging of all rows across the grid c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumRows Disable dragging of a particular row c1FlexGrid1Rows[3]AllowDragging = false

C

Allow dragging of all rows across the grid c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumRows

Disable dragging of a particular row c1FlexGrid1Rows(3)AllowDragging = False

VBNET

FlexGrid for WinForms

84 Copyright copy GrapeCity Inc All rights reserved

Allow ResizingBy default FlexGrid does not give option to resize the rows To change this behavior you can use AllowResizingproperty of the C1FlexGrid class This property accepts values from the AllowResizingEnum enumerationwhich enables end-user to change size of columns rows or both The enumeration also gives you options touniformly resize the rows columns or both that is if you resize one of the columns or rows the grid automaticallyresizes rest of the columns or rows as well FlexGrid also provides RowAllowResizing property which is Boolean typeand lets you enable or disable resizing of a particular row

Following code shows how to allow users to resize the WinForms FlexGrid rows at run-time

Allow freezing of rows at runtimec1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumRows

C

Allow freezing of rows at runtimec1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumRows

VBNET

Allow user to resize rows c1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumRows Stop user from resizing second row c1FlexGrid1Rows[2]AllowResizing = false

C

Allow user to resize rows c1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumRows

Stop user from resizing second row c1FlexGrid1Rows(2)AllowResizing = False

VBNET

ヘッダ

Row header refers to the fixed rows on the left hand side of the grid which may or may not contain the caption string

In FlexGrid by default the left most column with zero index is allocated for the row header However you can span theheader to other columns as well by specifying them as fixed To set more than one column as fixed you need toset the Fixed property of ColumnCollection class to an integer greater than 1

FlexGrid for WinForms

85 Copyright copy GrapeCity Inc All rights reserved

Set Header TextTo set the row header text you can set Caption property of the Row class Note that this property sets the value of cellsin the default header column at zero index To set value in the other fixed column cells you need to use the usual valueallocation ways of FlexGrid For more information on how to set cell values see Set Value in Cell

Specify the header column and set the header text in WinForms FlexGrid using the code below

Merge Row HeaderFlexGrid provides AllowMerging property of the Column class which specifies whether it is allowed to merge cells in aparticular column (in this case the header column) or not Once you have allowed merging in the header columnset either AllowMerging or AllowMergingFixed property of the C1FlexGrid class to FixedOnly Availability of these twoproperties in the FlexGrid control offers you more flexibility to implement multiple logics related to merging For moreinformation on merging cells see Merge

Set header for first rowc1FlexGrid1Rows[1]Caption = Row 1

Set header for all rowsfor (int i = c1FlexGrid1RowsFixed i lt c1FlexGrid1RowsCount i++) c1FlexGrid1[i 0] = Row + iToString()

Set column widthc1FlexGrid1Cols[0]Width = 85

C

Set header for first row c1FlexGrid1Rows(1)Caption = Row 1

Set header for all rows For i As Integer = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 c1FlexGrid1(i 0) = Row amp iToString() Next

Set column width c1FlexGrid1Cols(0)Width = 85

VBNET

FlexGrid for WinForms

86 Copyright copy GrapeCity Inc All rights reserved

Use the code below to merge row headers in the WinForms FlexGrid

Wrap Row Header TextTo wrap the text in row header access the CellStyle item Fixed of the CellStyleCollection class and set its WordWrapproperty to true Note that to view the wrapped text properly you need to adjust height of FlexGrid rows or just callthe AutoSizeRow() method to automatically resize the rows according to the length of text

Use the code below to wrap header text of the WinForms FlexGrid rows

Style Row HeaderTo style the row header you can access the CellStyle item Fixed of the CellStyleCollection class and set variousstyling related properties for same such as Font ForeColor and TextEffect

Allow merging on the header columnc1FlexGrid1Cols[0]AllowMerging = true

Set AllowMerging or AllowMergingFixed property of the grid to merge fixed rowcolumns only c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

Allow merging on the header columnc1FlexGrid1Cols(0)AllowMerging = True

Set AllowMerging or AllowMergingFixed property of the grid to merge fixed rowcolumns only c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

Set row captionc1FlexGrid1Rows[3]Caption = Large text to display text wrapping and mergingc1FlexGrid1Rows[4]Caption = Large text to display text wrapping and merging Set row heightc1FlexGrid1Rows[3]Height = 35c1FlexGrid1Rows[4]Height = 35

Set word wrapping for fixed rows and columnsc1FlexGrid1Styles[Fixed]WordWrap = true

C

Set row captionc1FlexGrid1Rows(3)Caption = Large text to display text wrapping and mergingc1FlexGrid1Rows(4)Caption = Large text to display text wrapping and merging

Set row heightc1FlexGrid1Rows(3)Height = 35c1FlexGrid1Rows(4)Height = 35

Set word wrapping for fixed rows and columnsc1FlexGrid1Styles(Fixed)WordWrap = True

VBNET

FlexGrid for WinForms

87 Copyright copy GrapeCity Inc All rights reserved

Customize row header of the WinForms FlexGrid using the code below

Set font of the header textc1FlexGrid1Styles[Fixed]Font = new Font(Tahoma 10 FontStyleBold) Set forecolor of the header textc1FlexGrid1Styles[Fixed]ForeColor = ColorPaleVioletRed Set backcolor of the header textc1FlexGrid1Styles[Fixed]BackColor = ColorLemonChiffon Apply text effect on the header textc1FlexGrid1Styles[Fixed]TextEffect = C1WinC1FlexGridTextEffectEnumInset

C

Set font of the header text c1FlexGrid1Styles(Fixed)Font = New Font(Tahoma 10 FontStyleBold)

Set forecolor of the header text c1FlexGrid1Styles(Fixed)ForeColor = ColorPaleVioletRed

Set backcolor of the header text c1FlexGrid1Styles(Fixed)BackColor = ColorLemonChiffon

Apply text effect on the header text c1FlexGrid1Styles(Fixed)TextEffect = C1WinC1FlexGridTextEffectEnumInset

VBNET

行の詳細

Row detail is a feature to provide additional information related to a row or record in the form of another expandablelayer In such case row which is the first layer contains the basic information while the second layer contains the detailedinformation This feature is specially useful when the additional information is too large to be displayed in the availablescreen space or it is not consistent for every record

FlexGrid for WinForms

88 Copyright copy GrapeCity Inc All rights reserved

FlexGrid provides the row detail feature using IC1FlexGridRowDetail interface which is implemented by the detail controls tobe hosted on detail row In addition FlexGrid also provides a separate assembly C1WinC1FlexGridRowDetails452dllto provide template user controls InputPanel and FlexGrid ready to be used in detail row You can add details section toany row in FlexGrid which enables you to group data in a template which is visible optionally This allows users to viewadditional data related to a row by simply selecting the row The grid also provides built-in expand or collapse buttons tocontrol the visibility of data within the expandable row

Some common use case scenarios of row detail feature are

1 In-form editing where an InputPanel control is hosted to get input from the user to fill information in a record2 Hierarchical grid which contains a master grid and a detail grid to show additional information about the record3 Custom row details where any control can be used to create row detail template

Detailed implementation of these scenarios is given in their respective sections below

In-form EditingFlexGrid supports in-form editing by hosting InputPanel control in detail row The InputPanel control contains data fieldswhere user can enter or edit the values like a form Once user finishes editing fields those values get reflected in theselected row

FlexGrid for WinForms

89 Copyright copy GrapeCity Inc All rights reserved

In FlexGrid you can implement in-form editing by adding reference to C1WinC1FlexGridRowDetails452dll and usingthe C1InputPanelRowDetail class which already implements the IC1FlexGridRowDetail interface The instance of this classis then assigned to RowDetailProvider property of the C1FlexGrid class which adds the InputPanel control to detail rowand enables the in-form editing

Hierarchical ViewHierarchical view refers to master-detail model where top level grid is the master grid and nested grid is the detail gridwhich displays additional information about expanded row of the master grid For instance example below demonstratesthe master-detail structure using Customer and Order tables respectively with CustomerID as common data element todefine a relation

flexGridRowDetailProvider = (g r) =gt new C1InputPanelRowDetail()flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected

C

flexGridRowDetailProvider = Function(g r) New C1InputPanelRowDetail()flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected

VBNET

FlexGrid for WinForms

90 Copyright copy GrapeCity Inc All rights reserved

In FlexGrid you can implement hierarchical grid by adding reference to C1WinC1FlexGridRowDetails452dll and usingthe C1FlexGridRowDetail class which already implements the IC1FlexGridRowDetail interface The instance of this class isthen assigned to RowDetailProvider property of the C1FlexGrid class to nest another grid in the detail row which enablesthe hierarchical grid interface

private void FlexGrid_Load(object sender EventArgs e) string conn = UtilGetConnectionString() var ds = new DataSet() string[] tables = Customers OrdersSplit() foreach (string tableName in tables) UtilFillTable(ds tableName conn) Defining relation between master and detail grid dsRelationsAdd(Customers_Orders dsTables[Customers]Columns[CustomerID] dsTables[Orders]Columns[CustomerID]) flexGridDataSource = ds flexGridDataMember = Customers flexGridRowDetailProvider = (g r) =gt new C1FlexGridRowDetail() flexGridAreRowDetailsFrozen = false

C

Private Sub FlexGrid_Load(ByVal sender As Object ByVal e As EventArgs) Dim conn As String = UtilGetConnectionString() Dim ds = New DataSet() Dim tables As String() = Customers OrdersSplit(c)

For Each tableName As String In tables UtilFillTable(ds tableName conn) Next Defining relation between master and detail grid dsRelationsAdd(Customers_Orders dsTables(Customers)Columns(CustomerID) dsTables(Orders)Columns(CustomerID))

VBNET

FlexGrid for WinForms

91 Copyright copy GrapeCity Inc All rights reserved

Custom Row DetailsIn addition to the InputPanel and FlexGrid control you can also host a custom control in the detail row of a grid Forinstance in the example below a text label control is attached to the row to enlist the additional information withoutaffecting the dimensions of the grid

To implement the custom row details in FlexGrid you need to create a user control which implementsthe IC1FlexGridRowDetail interface For instance here we have created a class named CustomRowDetail which representsthe text label control to be hosted in the detail row You then need to assign an object of this class to RowDetailProviderproperty of the C1FlexGrid class to enable the custom control to display additional information in the detail row

flexGridDataSource = ds flexGridDataMember = Customers flexGridRowDetailProvider = Function(g r) New C1FlexGridRowDetail() flexGridAreRowDetailsFrozen = False End Sub

private void CustomSample_Load(object sender EventArgs e) flexGridDataSource = DemoDataSource(Employees) flexGridRowDetailProvider = (g r) =gt new CustomRowDetail() flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected flexGridCols[Notes]Visible = false

Custom row detail class which shows label with notes about employee public class CustomRowDetail C1Label IC1FlexGridRowDetail Used to setup control before showing the FlexGrid detail control void IC1FlexGridRowDetailSetup(C1FlexGrid parentGrid int rowIndex) var bs = new BindingSource(parentGridDataSource parentGridDataMember) bsPosition = parentGridRows[rowIndex]DataIndex DataField = Notes DataSource = bs

C

FlexGrid for WinForms

92 Copyright copy GrapeCity Inc All rights reserved

Used to update size of the FlexGrid detail control void IC1FlexGridRowDetailUpdateSize(C1FlexGrid parentGrid int rowIndex Size proposedSize) var srSz = parentGridScrollableRectangleSize var sz = TextRendererMeasureText(Text Font srSz TextFormatFlagsWordBreak) szWidth = MathMax(szWidth srSzWidth) Size = sz

Private Sub CustomSample_Load(ByVal sender As Object ByVal e As EventArgs) flexGridDataSource = DemoDataSource(Employees) flexGridRowDetailProvider = Function(g r) New CustomRowDetail() flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected flexGridCols(Notes)Visible = False End Sub

Custom row detail class which shows label with notes about employee Public Class CustomRowDetail Inherits C1Label Implements IC1FlexGridRowDetail

Used to setup control before showing the FlexGrid detail control Private Sub Setup(ByVal parentGrid As C1FlexGrid ByVal rowIndex As Integer) Dim bs = New BindingSource(parentGridDataSource parentGridDataMember) bsPosition = parentGridRows(rowIndex)DataIndex DataField = Notes DataSource = bs End Sub

Used to update size of the FlexGrid detail control Private Sub UpdateSize(ByVal parentGrid As C1FlexGrid ByVal rowIndex As Integer ByVal proposedSize As Size) Dim srSz = parentGridScrollableRectangleSize Dim sz = TextRendererMeasureText(Text Font srSz TextFormatFlagsWordBreak) szWidth = MathMax(szWidth srSzWidth) Size = sz End Sub End Class

VBNET

サイズ変更

Set Row HeightFlexGrid provides DefaultSize property of the RowCollection class to set row height across the grid You can alsospecify the height of a particular row by setting Height property of the Row class Default value of the Heightproperty is -1 which indicates that the row is taking height specified by the DefaultSize property

Use the code below to set the default height of a row of the WinForms FlexGrid

Set the default size of all rowsc1FlexGrid1RowsDefaultSize = 50

C

FlexGrid for WinForms

93 Copyright copy GrapeCity Inc All rights reserved

Auto-adjust Row HeightTo adjust the row height according to text length and word wrapping options FlexGrid provides the AutoSizeRow()and AutoSizeRows() methods While AutoSizeRow() method automatically adjusts height of the specified row theAutoSizeRows() method is used for cell ranges

Following code shows how you can auto adjust the row height according to the text length in the WinForms FlexGrid

Set MinMax Row HeightFlexGrid allows you to set bounds to the row height by using the MinSize and MaxSize propertiesof the RowCollection class This feature is especially useful in scenarios such as when AllowResizing property is set totrue or while using the AutoSizeRow() or AutoSizeRows() method

Specify the bounds of row height in the WinForms FlexGrid using the code below

Set the height of a particular rowc1FlexGrid1Rows[1]Height = 55

Set the default size of all rowsc1FlexGrid1RowsDefaultSize = 50

Set the height of a particular rowc1FlexGrid1Rows(1)Height = 55

VBNET

Adjust the height of fourth row automaticallyc1FlexGrid1AutoSizeRow(4) Adjust the height of all rows automatically c1FlexGrid1AutoSizeRows() Adjust the height of cell range automaticallyc1FlexGrid1AutoSizeRows(2 4 5 6 10 C1WinC1FlexGridAutoSizeFlagsNone)

C

Adjust the height of fourth row automatically c1FlexGrid1AutoSizeRow(4)

Adjust the height of all rows automatically c1FlexGrid1AutoSizeRows()

Adjust the height of cell range automatically c1FlexGrid1AutoSizeRows(2 4 5 6 10 C1WinC1FlexGridAutoSizeFlagsNone)

VBNET

Set the maximum height of rowc1FlexGrid1RowsMaxSize = 50 Set the minimum height of rowc1FlexGrid1RowsMinSize = 20

C

FlexGrid for WinForms

94 Copyright copy GrapeCity Inc All rights reserved

Set the maximum height of rowc1FlexGrid1RowsMaxSize = 50

Set the minimum height of row c1FlexGrid1RowsMinSize = 20

VBNET

FlexGrid for WinForms

95 Copyright copy GrapeCity Inc All rights reserved

セル

Cell is the smallest unit of a grid Although in most common scenarios we prefer working on row or column levelthere are some operations which are required to be carried out on the cell level Getting setting or removing data arefew to name

Topic Snapshot Content

Basic Operations Discusses how to perform basic operations related to a cell

Set Value in CellSet Values in Cell RangeClear Value from Cell (Range)Set Image in CellDisplay Tooltip in CellRetrieve Cell Values

Cell Format Discusses how to format cell or cell data in various scenarios

Cell ContentCell AppearanceConditional FormattingOwner Drawn Cell

基本操作

Set Value in CellFlexGrid provides two ways to set values in cell You can either use Item property (indexer) or SetData method of the C1FlexGrid class

Use the code below to set a value in the WinForms FlexGrid cell

Set Values in Cell RangeTo set values in a cell range you can either use Data property of the CellRange class or SetData method of the C1FlexGrid class

Following code shows how to set values in a cell range in WinForms FlexGrid

インデックスを使用してデータを設定しますc1FlexGrid1[2 3] = 2nd col 3rd row SetDataメソッドを使用してデータを設定しますc1FlexGrid1SetData(2 4 2nd col 4th row)

C

インデックスを使用してデータを設定します c1FlexGrid1(2 3) = 2nd col 3rd row

SetDataメソッドを使用してデータを設定します c1FlexGrid1SetData(2 4 2nd col 4th row)

VBNET

セル範囲を取得しますC1WinC1FlexGridCellRange cr = c1FlexGrid1GetCellRange(2 3 5 6) 方法1dataプロパティを使用してセル範囲にデータを設定しますcrData = Cell Range

C

FlexGrid for WinForms

96 Copyright copy GrapeCity Inc All rights reserved

Clear Value from Cell (Range)There are two ways by which contents of cell or cell range can be cleared You can either chose to do it programmatically by setting thecontent of cell to an empty string using indexer or SetData method Or you can set the AutoClipboard property to true so that user candelete the values by pressing the Delete key

Below code demonstrates how to allow keyboard operations so that user can clear values from WinForms FlexGrid cells

Set Image in CellTo set image in a cell you can use SetCellImage method of the C1FlexGrid class You can also set an image in a cell range by using Imageproperty of the CellRange class By default text and image both are displayed in the cell However you can choose to display only image bysetting the ImageAndText property to false

Use the code below to set image in a WinForms FlexGrid cell

方法2SetDataメソッドを使用してセル範囲にデータを設定します c1FlexGrid1SetData(cr Cell Range)

セル範囲を取得します Dim cr As C1WinC1FlexGridCellRange = c1FlexGrid1GetCellRange(2 3 5 6)

方法1dataプロパティを使用してセル範囲にデータを設定します crData = Cell Range

方法2SetDataメソッドを使用してセル範囲にデータを設定します c1FlexGrid1SetData(cr Cell Range)

VBNET

ユーザーがDeleteキーを押してセルの内容をクリアするなどのキーボード操作を実行できるようにしますc1FlexGrid1AutoClipboard = true

コードを介して特定のセルのデータをクリアしますc1FlexGrid1SetData(3 4 )

C

ユーザーがDeleteキーを押してセルの内容をクリアするなどのキーボード操作を実行できるようにします c1FlexGrid1AutoClipboard = True

コードを介して特定のセルのデータをクリアします c1FlexGrid1SetData(3 4 )

VBNET

セル(36)に画像を設定しますc1FlexGrid1SetCellImage(3 6 ImageFromFile(masterpng))

C

FlexGrid for WinForms

97 Copyright copy GrapeCity Inc All rights reserved

Display Tooltip in CellTo display partially hidden content of cells as tooltip FlexGrid provides ShowCellLabels property of the C1FlexGrid class You can also showadditional information in the form of a tooltip by using the MouseEnterCell and MouseLeaveCell event

Below code shows how to display a tooltip on a WinForms FlexGrid cell

セル範囲(126)から(146)に画像を設定しますC1WinC1FlexGridCellRange crcr = c1FlexGrid1GetCellRange(12 6 14 6)crImage = ImageFromFile(amexjpg)

テキストなしで画像を表示しますc1FlexGrid1Rows[3]ImageAndText = false

セル(36)に画像を設定します c1FlexGrid1SetCellImage(3 6 ImageFromFile(masterpng))

セル範囲(126)から(146)に画像を設定します Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1GetCellRange(12 6 14 6) crImage = ImageFromFile(amexjpg)

テキストなしで画像を表示します c1FlexGrid1Rows(3)ImageAndText = False

VBNET

private void Form1_Load(object sender EventArgs e) このコードはデータを「c1NWindDataSetEmployees」テーブルにロードします 必要に応じて移動または削除できます thisemployeesTableAdapterFill(thisc1NWindDataSetEmployees) for (int i = c1FlexGrid1RowsFixed i lt c1FlexGrid1RowsCount i++) c1FlexGrid1Rows[i]UserData = Employee + c1FlexGrid1[i 2] + + c1FlexGrid1[i 3] private void C1FlexGrid1_MouseEnterCell(object sender C1WinC1FlexGridRowColEventArgs e) if (eRow gt= c1FlexGrid1RowsFixed) string tip tip = c1FlexGrid1Rows[eRow]UserDataToString() ツールチップを表示します toolTip1SetToolTip(c1FlexGrid1 tip)

private void C1FlexGrid1_MouseLeaveCell(object sender C1WinC1FlexGridRowColEventArgs e) ツールチップを非表示にします toolTip1SetToolTip(c1FlexGrid1 )

C

FlexGrid for WinForms

98 Copyright copy GrapeCity Inc All rights reserved

Retrieve Cell ValuesThere are numerous ways using which you can fetch the value of FlexGrid cells depending on your requirement Below tablediscusses several scenarios such as fetching the raw data or formatted data from a single cell or a cell range

Requirement MethodProperty Usage

Get the raw data Item property (indexer) ExampleCode

var data = c1FlexGrid1[1 1] SystemDiagnosticsDebugWriteLine($Cell data data)

GetData() method ExampleCode

var data1 = c1FlexGrid1GetData(1 1) SystemDiagnosticsDebugWriteLine($Cell data data1)

Get the formatted data GetDataDisplay() method ExampleCode

var data2 = c1FlexGrid1GetDataDisplay(1 1) SystemDiagnosticsDebugWriteLine($Display data data2)

Get values of a cell range Clip property ExampleCode

var data3 = c1FlexGrid1Clip SystemDiagnosticsDebugWriteLine($Clip data data3)

GetCellRange method ExampleCode

var data4 = c1FlexGrid1GetCellRange(1 1) SystemDiagnosticsDebugWriteLine($Cell Range data data4Clip)

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) このコードはデータを「c1NWindDataSetEmployees」テーブルにロードします 必要に応じて移動または削除できます MeemployeesTableAdapterFill(Mec1NWindDataSetEmployees)

For i As Integer = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 c1FlexGrid1Rows(i)UserData = Employee amp c1FlexGrid1(i 2) amp + c1FlexGrid1(i 3) Next End Sub

Private Sub C1FlexGrid1_MouseEnterCell(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) If eRow gt= c1FlexGrid1RowsFixed Then Dim tip As String tip = c1FlexGrid1Rows(eRow)UserDataToString() ツールチップを表示します toolTip1SetToolTip(c1FlexGrid1 tip) End If End Sub

Private Sub C1FlexGrid1_MouseLeaveCell(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) ツールチップを非表示にします toolTip1SetToolTip(c1FlexGrid1 ) End Sub

VBNET

FlexGrid for WinForms

99 Copyright copy GrapeCity Inc All rights reserved

セルの書式設定

Cell ContentTo control how content of the cells is formatted and displayed set the Format property of Row or Column object toformat string similar to the ones that are used with StringFormat property in the NET framework For instance thesample code below formats the third column as Date and fourth column as Currency

FlexGrid also provides design time option to set the Format property through the Format String dialog You canaccess the Format String dialog by clicking Ellipsis button against the Format String field in Column Tasks menu Oryou can also use the Format property in C1FlexGrid Column Editor

短い日付形式を設定しますc1FlexGrid1Cols[3]Format = D 通貨形式を設定しますc1FlexGrid1Cols[4]Format = c

C

短い日付形式を設定しますc1FlexGrid1Cols(3)Format = D

通貨形式を設定しますc1FlexGrid1Cols(4)Format = c

VBNET

FlexGrid for WinForms

100 Copyright copy GrapeCity Inc All rights reserved

Note that Format String dialog is specific to column and changes the Format property of the selected column only

Cell AppearanceFlexGrid provides CellStyle objects to handle the appearance aspects of cells such as alignment font colors bordersand so on The grid has Styles property that holds the collection of styles used to format the grid This collection hassome built-in members that define the appearance of grid elements such as fixed and scrollable cells selection focuscell and so on You can change these styles to modify the appearance of grid

Although changing the built-in styles is the simplest way to change appearance of the grid you can also create yourown custom styles and assign them to cells rows or columns

Use the code below to change appearance of the WinForms FlexGrid cells

組み込みのスタイルをカスタマイズしますCellStyle cs = c1FlexGrid1StylesFocus

C

FlexGrid for WinForms

101 Copyright copy GrapeCity Inc All rights reserved

Conditional FormattingTo format a cell according to its content you need to create a new style and apply it to the cells satisfying a particularcondition using SetCellStyle() method For instance to highlight the values greater than a specified value you canformat the cells containing them using different style

Following code shows how to apply conditional formatting on WinForms FlexGrid cells

csFont = new Font(c1FlexGrid1Font FontStyleBold)csForeColor = ColorGreencsBackColor = ColorRed

カスタムスタイルを作成します CellStyle cs1 = c1FlexGrid1StylesAdd(NewStyle)cs1BackColor = ColorAquacs1ForeColor = ColorBlue

カスタムスタイルを割り当てますc1FlexGrid1Cols[3]Style = cs1

Dim cs As CellStyle = c1FlexGrid1StylesFocus csFont = New Font(c1FlexGrid1Font FontStyleBold) csForeColor = ColorGreen csBackColor = ColorRed

Dim cs1 As CellStyle = c1FlexGrid1StylesAdd(NewStyle) cs1BackColor = ColorAqua cs1ForeColor = ColorBlue

c1FlexGrid1Cols(3)Style = cs1

VBNET

CellStyle cs 大きな値のカスタムスタイルを作成しますcs = c1FlexGrid1StylesAdd(LargeValue)csFont = new Font(Font FontStyleItalic)

C

FlexGrid for WinForms

102 Copyright copy GrapeCity Inc All rights reserved

Owner Drawn CellThe above sections explain how you can customize FlexGrid cells to change the appearance of grid using CellStyleobjects However for further customization of grid cells such as rendering gradient background custom graphics etcyou can use DrawMode property and OwnerDrawCell event of the C1FlexGrid class

The DrawMode property determines whether or not the OwnerDrawCell event is fired The event allows you tooverride every visual aspect of the cell You can change the text and image to be displayed in the cell by setting theeText and eImage parameters in the event handler You can also change the style that is used to display the cell bysetting the eStyle property

Note that you should not modify properties of the Style parameter as it might affect other cells Instead assign a newCellStyle object to the Style parameter For example instead of setting eStyleForeColor = ColorRed assign a wholenew style to the parameter using eStyle = c1FlexGrid1Styles[RedStyle]

You can also use your own drawing code to draw into the cell and even combine your custom code with calls to theeDrawCell method For example you can paint the cell background using GDI calls and then call eDrawCell todisplay the cell borders and content

In the example below WinForms FlexGrid uses a gradient brush to paint the background of the selected cell rangeFirst the sample code sets the DrawMode property to OwnerDraw and then declares a LinearGradientBrushobject

csBackColor = ColorGold

for (int row = 1 row lt c1FlexGrid1RowsCount row++)if (ConvertToDouble(c1FlexGrid1[row 4]) gt 80000)c1FlexGrid1SetCellStyle(row 4 cs)

Dim cs As CellStyle

cs = c1FlexGrid1StylesAdd(LargeValue) csFont = New Font(Font FontStyleItalic) csBackColor = ColorGold

For row As Integer = 1 To c1FlexGrid1RowsCount - 1

If ConvertToDouble(c1FlexGrid1(row 4)) gt 80000 Then c1FlexGrid1SetCellStyle(row 4 cs) End If Next

VBNET

SystemDrawingDrawing2DLinearGradientBrush m_GradientBrushprivate void Form1_Load(object sender EventArgs e)

C

FlexGrid for WinForms

103 Copyright copy GrapeCity Inc All rights reserved

所有者描画セルで使用するブラシ m_GradientBrush = new SystemDrawingDrawing2DLinearGradientBrush(ClientRectangle ColorSteelBlue ColorWhite 45)

グラデーションを追加するにはowner-drawを使用します c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw

private void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) グラデーションブラシを使用して選択したセルの背景を描画します if (c1FlexGrid1SelectionContains(eRow eCol)) 背景を描きますeGraphicsFillRectangle(m_GradientBrush eBounds)

グリッドにコンテンツを描画させますeDrawCell(C1WinC1FlexGridDrawCellFlagsContent)

このセルの描画は完了ですeHandled = true

Private m_GradientBrush As DrawingDrawing2DLinearGradientBrush

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) 所有者描画セルで使用するブラシ m_GradientBrush = New DrawingDrawing2DLinearGradientBrush(ClientRectangle ColorSteelBlue ColorWhite 45)

グラデーションを追加するにはowner-drawを使用します c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDrawEnd Sub

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) グラデーションブラシを使用して選択したセルの背景を描画します If c1FlexGrid1SelectionContains(eRow eCol) Then 背景を描きます eGraphicsFillRectangle(m_GradientBrush eBounds)

グリッドにコンテンツを描画させます eDrawCell(C1WinC1FlexGridDrawCellFlagsContent)

このセルの描画は完了です eHandled = True End IfEnd SubEnd IfEnd Sub

VBNET

FlexGrid for WinForms

104 Copyright copy GrapeCity Inc All rights reserved

グリッド

This section discusses about various operations that can be performed on the grid

Topic Snapshot Content

Basic Operations Discusses about basic operations that can be performed on the grid

Transpose Data in GridDisplay Context Menu

Keyboard Navigation Discusses about supperted keys and their operations in

Non-edit ModeEdit Mode

Improve Performance Provides tips and tricks to get best out of your grid by improving its performance

Use Data VirtualizationUse BeginUpdate and EndUpdate MethodsKeep AutoResize Property to False (default)Assign Styles DynamicallyAvoid Modifying Styles in the OwnerDrawCell EventShow Ellipses in a Single ColumnShow Multi-line Text in a CellRetrieve Data Sorting When Bound to a Data TableSpecify Character Limit for Column

基本操作

This topic discusses about various operations that require handling at the grid level

Transpose Data in GridTransposing data refers to swapping column data and row data In WinForms FlexGrid this can be achieved usingTranspose() method of the C1FlexGrid class as shown in the code below

Note that data can be transposed only in the case of unbound grid Also if grid has sorting applied on a column theTranspose() method removes sorting before transposing the data

Display Context MenuContext menus can be helpful to user as they provide shortcuts for actions that are frequently used In FlexGrid therecan be two scenarios to display a context menu

Display context menu in non-edit modeDisplay context menu in edit mode

Display Context Menu in Non-edit Mode

To display context menu when grid is in non-edit mode you need to create an instance of ContextMenuStrip controladd the menu items and assign the instance to ContextMenuStrip property of the Control class

c1FlexGrid1Transpose()

C

C1FlexGrid1Transpose()

VBNET

FlexGrid for WinForms

105 Copyright copy GrapeCity Inc All rights reserved

Refer to the code below to see how to display a context menu in WinForms FlexGrid in non-edit mode

Display Context Menu in Edit Mode

To display context menu in edit mode you need to display the context menu on editor by using StartEdit event ofthe C1FlexGrid class In the StartEdit event instantiate the editor and the ContextMenuStrip add menu items andthen assign it to ContextMenuStrip property of the editor

Create an instance of ContextMenuStrip controlContextMenuStrip cm = new ContextMenuStrip()

Add menu items to the context menucmItemsAdd(Add Above)cmItemsAdd(Add Below)cmItemsAdd(Add Left)cmItemsAdd(Add Right)

Assign the instance to ContextMenuStrip property c1FlexGrid1ContextMenuStrip = cm

C

Create an instance of ContextMenuStrip controlDim cm As ContextMenuStrip = New ContextMenuStrip()

Add menu items to the context menucmItemsAdd(Add Above)cmItemsAdd(Add Below)cmItemsAdd(Add Left)cmItemsAdd(Add Right)

Assign the instance to ContextMenuStrip property c1FlexGrid1ContextMenuStrip = cm

VBNET

FlexGrid for WinForms

106 Copyright copy GrapeCity Inc All rights reserved

Use the code below to display context menu in WinForms FlexGrid in edit mode

private void C1FlexGrid1_StartEdit(object sender C1WinC1FlexGridRowColEventArgs e) TextBox tb = (TextBox)c1FlexGrid1Editor

Create context menu ContextMenuStrip cm2 = new ContextMenuStrip() cm2ItemsAdd(Cut) cm2ItemsAdd(Copy) cm2ItemsAdd(Paste) Set context menu tbContextMenuStrip = cm2

C

Private Sub C1FlexGrid1_StartEdit(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) Dim tb As TextBox = CType(c1FlexGrid1Editor TextBox)

Create context menu Dim cm2 As ContextMenuStrip = New ContextMenuStrip() cm2ItemsAdd(Cut) cm2ItemsAdd(Copy) cm2ItemsAdd(Paste)

Set context menu tbContextMenuStrip = cm2End Sub

VBNET

キーボードによる移動

With built-in keyboard support FlexGrid lets you perform the basic navigation operations such as moving the focusentering or exiting the edit mode etc with a perfect ease just by using keys Below tables list the supported keys andtheir corresponding operations in non-edit as well as in edit mode of the cell

Non-edit Mode

Key Sequence Key Action

FlexGrid for WinForms

107 Copyright copy GrapeCity Inc All rights reserved

uarr

larr rarr

darr

Moves focus to the adjacent cell in direction indicated by the arrow key

Shift + ArrowSelects adjacent cells in direction indicated by the arrow key

F2Grid is editable Toggles the cell to edit mode If a value exists in the cell it getsselected Else the grid simply displays a cursor in the cell

Grid is not editable No action

EnterGrid is editable Toggles the cell to edit mode If a value exists in the cell it getsselected Else the grid simply displays a cursor in the cell

Grid is not editable Moves the selection down to the next visible row

You can also change default behavior of Enter key press by using the KeyActionEnterproperty

HomeMoves focus to the first cell of row

EndMoves focus to the last cell of row

Ctrl + HomeMoves focus to the first cell of column

Ctrl + EndMoves focus to the last cell of column

TabBy default grid ignores the Tab key press and lets it cycle through the controls on theform However you can define the action to be performed on Tab key press by usingthe KeyActionTab property

Ctrl + C

Ctrl + X

Ctrl + V

Performs usual clipboard operations that is copy(Ctrl+C) cut(Ctrl+X) and paste(Ctrl+V)when AutoClipboard property is set to true (Default value is false)

Edit Mode

Key Sequence Key Action

uarr

darr

Moves focus to the adjacent cell in the direction indicated by arrow key

FlexGrid for WinForms

108 Copyright copy GrapeCity Inc All rights reserved

larr rarrMoves cursor by one character in the direction indicated by arrow key When cursor is onthe first or last character moves focus to the adjacent cell in the direction of arrow key

EnterToggles the cell to non-edit mode and moves focus to the cell below You can also changedefault behavior of Enter key press by using the KeyActionEnter property

EscCancels editing and exits the edit mode

TabBy default grid ignores the Tab key press and lets it cycle through the controls on theform However you can define the action to be performed on Tab key press by usingthe KeyActionTab property

パフォーマンスの向上

Use Data VirtualizationTo efficiently render large data sets FlexGrid supports data vitualization in which data is fetched in pages as the user scrolls down The gridknows the total number of rows but only loads and displays those that are visible to the user For instance you can use C1DataCollectionpackage to implement virtualizable data source Create a class inherited from the C1VirtualDataCollection and implement GetPageAsyncmethod which returns one page of data from data source you have assigned The following GIF shows how FlexGrid appears in the virtualscrolling mode

public class VirtualModeCollectionView C1VirtualDataCollectionltCustomergt public int TotalCount get set = 1_000 protected override async TaskltTupleltint IReadOnlyListltCustomergtgtgt GetPageAsync(int pageIndex int startingIndex int count IReadOnlyListltSortDescriptiongt sortDescriptions = null FilterExpression filterExpression = null CancellationToken cancellationToken = default(CancellationToken)) await TaskDelay(500 cancellationToken)Simulates network traffic return new Tupleltint IReadOnlyListltCustomergtgt(TotalCount EnumerableRange(startingIndex count)Select(i =gt new Customer(i))ToList())

C

Public Class VirtualModeCollectionView

VBNET

FlexGrid for WinForms

109 Copyright copy GrapeCity Inc All rights reserved

Use BeginUpdate and EndUpdate MethodsThe BeginUpdate and EndUpdate methods are used to optimize the performance of the grid Call BeginUpdate before making extensivechanges and call EndUpdate when done to suspend repainting This reduces flicker and increases performance This optimization is especiallyeffective when adding large number of rows to the grid because it needs to recalculate ranges and update scrollbars each time a row is added

The code below shows how to add a large number of rows to the WinForms FlexGrid efficiently Note how the EndUpdate method is calledinside a finally block to ensure repainting is properly restored

Keep AutoResize Property to False (default)In case of bound grid if AutoResize property is set to true the control automatically resizes its columns to fit the widest entry every time newdata is read from the data source If the data source contains a large number of rows and columns the automatic resizing may take a relativelylong time In such cases you should consider setting AutoResize to false and setting the column widths directly in code

Assign Styles DynamicallyFlexGrid allows you to create cell styles and assign them to rows columns and arbitrary cell ranges You can use this feature to format the gridcells conditionally Usually you do this by using the SetCellStyle() method However in that case you have to update the style whenever the cellvalue changes Also if the grid is bound to a data source styles are lost whenever data source is reset after operations such as sorting andfiltering A better alternative in these cases is to use the OwnerDraw feature and select styles dynamically based on the cell values For example

Inherits C1VirtualDataCollection(Of Customer)

Public Property TotalCount As Integer = 1_000

Protected Overrides Async Function GetPageAsync(ByVal pageIndex As Integer ByVal startingIndex As Integer ByVal count As Integer ByVal Optional sortDescriptions As IReadOnlyList(Of SortDescription) = Nothing ByVal Optional filterExpression As FilterExpression = Nothing ByVal Optional cancellationToken As CancellationToken = DirectCast(Nothing CancellationToken)) As Task(Of Tuple(Of Integer IReadOnlyList(Of Customer))) Await TaskDelay(500 cancellationToken) Simulates network traffic Return New Tuple(Of Integer IReadOnlyList(Of Customer))(TotalCount EnumerableRange(CInt(startingIndex) CInt(count))[Select](Function(i) New Customer(i))ToList()) End FunctionEnd Class

void UpdateGrid(C1FlexGrid c1FlexGrid1) try c1FlexGrid1BeginUpdate() suspend painting to avoid flicker c1FlexGrid1RowsCount = 1 for (int i = 1 i lt 10000 i++) c1FlexGrid1AddItem(Row + iToString()) finally c1FlexGrid1EndUpdate() always restore painting

C

Private Sub UpdateGrid(ByVal c1FlexGrid1 As C1FlexGrid) Try c1FlexGrid1BeginUpdate() suspend painting to avoid flicker c1FlexGrid1RowsCount = 1

For i As Integer = 1 To 10000 - 1 c1FlexGrid1AddItem(Row amp iToString()) Next

Finally c1FlexGrid1EndUpdate() always restore painting End TryEnd Sub

VBNET

FlexGrid for WinForms

110 Copyright copy GrapeCity Inc All rights reserved

the sample code shows how to display negative values in red color and values above 1000 in green color in the WinForms FlexGrid

Avoid Modifying Styles in the OwnerDrawCell EventAnother way to improve performance is not to modify the CellStyle object passed as a parameter in the OwnerDrawCell event Instead assign anew value to the eStyle parameter This is important because the CellStyle passed to the event handler is often used by other cells Forexample you could unintentionally change a normal style of the WinForms FlexGrid which would affect other similar cells as well in the grid

private void Form1_Load(object sender EventArgs e) Fill a column with random values c1FlexGrid1Cols[1]DataType = typeof(int) Random rnd = new Random() for (int r = 1 r lt c1FlexGrid1RowsCount r++) c1FlexGrid1[r 1] = rndNext(-10000 10000) Create style used to show negative values c1FlexGrid1StylesAdd(Red)ForeColor = ColorRed Enable OwnerDraw by setting the DrawMode property c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw c1FlexGrid1OwnerDrawCell += new C1WinC1FlexGridOwnerDrawCellEventHandler(C1FlexGrid1_OwnerDrawCell)

private void C1FlexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if(eMeasuring) Check that the row and column contain integer data if (eRow gt 0 ampamp c1FlexGrid1Cols[eCol]DataType == typeof(int)) Apply the style Red eStyle = c1FlexGrid1Styles[Red]

C

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) Fill a column with random values c1FlexGrid1Cols(1)DataType = GetType(Integer) Dim rnd As Random = New Random()

For r As Integer = 1 To c1FlexGrid1RowsCount - 1 c1FlexGrid1(r 1) = rnd[Next](-10000 10000) Next

Create style used to show negative values c1FlexGrid1StylesAdd(Red)ForeColor = ColorRed

Enable OwnerDraw by setting the DrawMode property c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw c1FlexGrid1OwnerDrawCell += New C1WinC1FlexGridOwnerDrawCellEventHandler(AddressOf C1FlexGrid1_OwnerDrawCell) End Sub

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If Not eMeasuring Then

Check that the row and column contain integer data If eRow gt 0 AndAlso c1FlexGrid1Cols(eCol)DataType Is GetType(Integer) Then Apply the style Red eStyle = c1FlexGrid1Styles(Red) End If End If End Sub

VBNET

FlexGrid for WinForms

111 Copyright copy GrapeCity Inc All rights reserved

Show Ellipses in a Single ColumnThe Trimming property should be used to show ellipses in a single column of the grid To determine how long strings are trimmed to fit the cellthe Trimming property can be set to either None Character Word EllipsisCharacter EllipsisWord or EllipsisPath For more information ontrimming see Display Trimmed Text

The following code sets the Trimming property to show ellipses at the end of the second WinForms Flexgrid column with the text trimmed tothe nearest character

Show Multi-line Text in a CellWhen showing multiple lines of text in a cell use the WordWrap and Height properties The WordWrap property determines whether the gridshould automatically break long strings that contain spaces and display them in multiple lines Strings that contain hard line breaks (vbCrLf ornr) are always displayed in multiple lines Multiple line text can be displayed in both fixed and scrollable cells For more information on wordwrapping see Wrap Text

Refer to code below to see how a multi-line text should be effectively displayed in the WinForms FlexGrid

CORRECT APPROACHprivate void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) Select style to use when painting this cell eStyle = MyStyleSelector(eRow eCol) WRONG APPROACHprivate void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) Select style to use when painting this cell This is wrong because changing any CellStyle objects invalidates the grid which would cause this event handler to be called over and over again eStyleColor = MyColorSelector(eRow eCol)

C

CORRECT APPROACHPrivate Sub C1FlexGrid1_OwnerDrawCellMethod(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) Select style to use when painting this celleStyle = MyStyleSelector(eRow eCol)End Sub

WRONG APPROACHPrivate Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) Select style to use when painting this cell This is wrong because changing any CellStyle objects invalidates the grid which would cause this event handler to be called over and over againeStyleColor = MyColorSelector(eRow eCol)End Sub

VBNET

c1FlexGrid1Cols[1]StyleNewTrimming =StringTrimmingEllipsisCharacter

C

c1FlexGrid1Cols(1)StyleNewTrimming = StringTrimmingEllipsisCharacter

VBNET

Set the WordWrap property

C

FlexGrid for WinForms

112 Copyright copy GrapeCity Inc All rights reserved

Retrieve Data Sorting When Bound to a Data TableTo maintain the way the grid is sorted when data is refreshed you can use the default views Sort property and a sort expression The Sortproperty uses a string containing the column name followed by ASC(default) or DESC to sort the column in ascending or descending orderrespectively Multiple columns can be sorted by specifying each column name separated by a comma A sort expression can include names ofgrid columns or a calculation Setting the sort expression at run time immediately reflects the changes in the data view

Below code shows how to use the sort expression with Sort property in the WinForms FlexGrid

Specify Character Limit for ColumnTo set the maximum number of characters a user can enter for any given column use the SetupEditor event You must declare an externaleditor such as C1TextBox in the StartEdit event of the C1FlexGrid class Then in the SetupEditor event you can set the maximum number ofcharacters that are allowed in a column cell

Use the code below to set the character limit for a WinForms FlexGrid column

c1FlexGrid1Styles[Normal]WordWrap = true Set the row heightc1FlexGrid1Rows[1]Height = 2 fgRowsDefaultSize Add text to the cellc1FlexGrid1[1 2] = This is the first line rn This is the second line

Set the WordWrap property c1FlexGrid1Styles(Normal)WordWrap = True

Set the row height c1FlexGrid1Rows(1)Height = 2 fgRowsDefaultSize

Add text to the cell c1FlexGrid1(1 2) = This is the first line amp vbCrLf amp This is the second line

VBNET

Sort the data by the UnitsInStock column then by the ProductID column thisproductsBindingSourceSort = UnitsInStock ASC ProductID ASC

C

Sort the data by the UnitsInStock column then by the ProductID columnMeproductsBindingSourceSort = UnitsInStock ASC ProductID ASC

VBNET

private void C1FlexGrid1_StartEdit(object sender C1WinC1FlexGridRowColEventArgs e) c1FlexGrid1Editor = c1TextBox private void C1FlexGrid1_SetupEditor(object sender RowColEventArgs e) Set the 3rd column to allow 20 characters and the rest only 10 if (eCol == 2) c1TextBoxMaxLength = 20 else c1TextBoxMaxLength = 10

C

Private Sub C1FlexGrid1_StartEdit(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs)

VBNET

FlexGrid for WinForms

113 Copyright copy GrapeCity Inc All rights reserved

c1FlexGrid1Editor = c1TextBox End Sub

Private Sub C1FlexGrid1_SetupEditor(ByVal sender As Object ByVal e As RowColEventArgs)

Set the 3rd column to allow 20 characters and the rest only 10 If eCol = 2 Then c1TextBoxMaxLength = 20 Else c1TextBoxMaxLength = 10 End If End Sub

FlexGrid for WinForms

114 Copyright copy GrapeCity Inc All rights reserved

スクロールバー

Display or Hide the Scroll BarIn FlexGrid you can manage the display of scroll bars using the ScrollBars property which lets you choose whether todisplay horizontal vertical both or no scroll bar through the ScrollBars enumeration

Below code shows how to always display both the scrollbars in the WinForms FlexGrid

Set Scroll PositionTo scroll FlexGrid to a specified location you can set TopRow and LeftCol property of the C1FlexGrid class TopRowproperty scrolls the grid vertically while LeftCol sets the horizontal scroll position of the grid The maximum value ofthese properties depends on the total number of rows or columns and the count that can be displayed in the gridThis feature is really useful in scenarios like synchronized scrolling of multiple grids

Use the code below to set scroll position of the WinForms FlexGrid

水平および垂直スクロールバーを表示しますc1FlexGrid1ScrollBars = ScrollBarsBoth 常にスクロールバーを表示しますc1FlexGrid1ScrollOptions = ScrollFlagsAlwaysVisible

C

水平および垂直スクロールバーを表示しますc1FlexGrid1ScrollBars = ScrollBarsBoth

常にスクロールバーを表示しますc1FlexGrid1ScrollOptions = ScrollFlagsAlwaysVisible

VBNET

スクロール位置を設定しますc1FlexGrid1TopRow = 3c1FlexGrid1LeftCol = 2

C

スクロール位置を設定しますc1FlexGrid1TopRow = 3

VBNET

FlexGrid for WinForms

115 Copyright copy GrapeCity Inc All rights reserved

Other Scroll OptionsFlexGrid also provides more options to handle various aspects of displaying a scroll bar through ScrollOptionsproperty This property accepts the values from ScrollFlags enumeration which lets you customize the scroll baroptions as described in the table below

Value Scroll Operation

AlwaysVisible Displays the scroll bar even when they are disable or there is no scrollable area

DelayedScroll Scrolls the content only after user has released the scrollbar thumb

KeepMergedRangePosition Can not set scroll position to the first cell of a merged range

None Uses the default scrolling behavior

ScrollByRowColumn Scrolls the content in units of rows or columns instead of scrolling by pixels

ShowScrollTips Fires the ShowScrollTip event and displays a tooltip next to the vertical scrollbarwhile scrolling vertically

Following code shows how to scroll the WinForms FlexGrid by rows or columns only

c1FlexGrid1LeftCol = 2

行や列単位でスクロールします c1FlexGrid1ScrollOptions = ScrollFlagsScrollByRowColumn

C

行や列単位でスクロールしますc1FlexGrid1ScrollOptions = ScrollFlagsScrollByRowColumn

VBNET

FlexGrid for WinForms

116 Copyright copy GrapeCity Inc All rights reserved

選択

Selection ModesFlexGrid by default allows to select a continuous batch of cells using mouse or keyboard and entire row or column by clicking thecorresponding header However the default behavior can be changed to allow selection in units of cell row column etc byusing SelectionMode property of the C1FlexGrid class The property accepts values from the SelectionModeEnumenumeration Below table gives a quick snapshot of how selection looks like in each of these modes

Value Description Snapshot

Default Allows selection of continuous batch of cells using mouse orkeyboard Also lets the user select entire row or column onclicking the respective header

Cell Allows selection of single cell at a time

CellRange Allows selection of continuous batch of cells using mouse orkeyboard

Column Allows selection of single column at a time

ColumnRange Allows selection of multiple contiguous columns at a time

ListBox Allows selection of multiple non-contiguous rows using the Ctrlkey

FlexGrid for WinForms

117 Copyright copy GrapeCity Inc All rights reserved

Row Allows selection of single row at a time

RowRange Allows selection of multiple contiguous rows at a time

Set SelectionFlexGrid provides various ways to set the selection through code You can use any of these methods depending on the requirementsuch as selecting the single cell cell range or rows

Selection MethodProperty Sample code

Single cell Set the Row and Col property Default value of both of theseproperties is 1 Hence by default selection is set to the firstscrollable cell on top left of the grid

Example Title

c1FlexGrid1Row = 2c1FlexGrid1Col = 1

Call the Select(rowIndex colIndex) method to select a singlecell

Example Title

c1FlexGrid1Select(2 1)

Cell range Set the RowSel and ColSel property These properties set theselection starting from value set in Row and Col property tothe specified row and column Note that to specify a blockselection you must set Row and before setting RowSel andColSel

Example Title

c1FlexGrid1Row = 2c1FlexGrid1Col = 1c1FlexGrid1RowSel = 4c1FlexGrid1ColSel = 3

Call the Select(CellRange Boolean) method to select a cellrange in a single call

Example Title

CellRange cellRange = new CellRange()cellRanger1 = 2cellRanger2 = 4cellRangec1 = 1cellRangec2 = 3c1FlexGrid1Select(cellRange)

Rows

(If SelectionModes =

SelectionModesEnum

ListBox)

Set the RowSelected property to true for individual rowobjects to select the non-continuous rows

Example Title

c1FlexGrid1SelectionMode = SelectionModeEnumListBoxc1FlexGrid1Rows[1]Selected = truec1FlexGrid1Rows[4]Selected =

Value Description Snapshot

FlexGrid for WinForms

118 Copyright copy GrapeCity Inc All rights reserved

true

Get Selection To get selected range of the WinForms FlexGrid you can use Selection property of the C1FlexGrid class

Select Text on Double ClickBy default double click on a grid cell changes the cell state to edit mode and shows the cursor at position of the mouse pointerHowever you can change this behavior and select the cell value on double click of a cell This can be done by detecting anddisabling the double click in BeforeDoubleClick event Then call the StartEditing method to enter the edit mode change theeditor to a TextBox and call the SelectAll method to select the cell value

Following code shows how you can select text of the WinForms FlexGrid cell on a double click

private void Button1_Click(object sender EventArgs e) C1WinC1FlexGridCellRange cr cr = c1FlexGrid1Selection MessageBoxShow(Selected rangen + crr1 + + crc1 + to + crr2 + + crc2)

C

Private Sub Button1_Click(ByVal sender As Object ByVal e As EventArgs) Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1Selection MessageBoxShow(Selected range amp vbLf amp crr1 amp + crc1 amp to + crr2 amp + crc2)End Sub

VBNET

private void C1FlexGrid1_BeforeDoubleClick(object sender BeforeMouseDownEventArgs e) デフォルトのダブルクリックを無効にします eCancel = true 編集モードに入ります c1FlexGrid1StartEditing() TextBoxクラスに変換しSelectAllメソッドを使用して選択します TextBox tb = (TextBox)c1FlexGrid1Editor tbSelectAll()

C

Private Sub C1FlexGrid1_BeforeDoubleClick(ByVal sender As Object ByVal e As BeforeMouseDownEventArgs) デフォルトのダブルクリックを無効にします eCancel = True 編集モードに入ります c1FlexGrid1StartEditing() TextBoxクラスに変換しSelectAllメソッドを使用して選択します Dim tb As TextBox = CType(c1FlexGrid1Editor TextBox) tbSelectAll()End Sub

VBNET

Selection MethodProperty Sample code

FlexGrid for WinForms

119 Copyright copy GrapeCity Inc All rights reserved

編集

This topic discusses about various events and methods which are related to editing and also about how to disableediting

Topic Content

Edit Mode Discusses various events and methods related to editing

Disable Editing Discusses how to disable editing in grid at various levels

Disable Grid EditingDisable Row or Column EditingDisable Cell Editing

編集モード

In FlexGrid edit mode can be invoked at runtime using mouse click or even keyboard To determineprogrammatically whether the grid is in edit mode you can read the value of Editor property If the grid is in editmode the property returns a reference to the control that is being used as editor such as TextBox or ComboBoxHowever if the grid is not in edit mode the property returns null

To put the grid in edit mode programmatically you can use the StartEditing method and to finish editing you can callthe FinishEditing method You can also retain the state of edit mode in grid while navigating through the cells byusing the PreserveEditMode property

In addition FlexGrid fires various events to facilitate better control on the editing process Below table lists thesequence of events which are fired by the grid during the editing process

Event Name Description

BeforeEdit The event fires whenever an editable cell is selected It allows you to prevent the cell from beingedited by setting the events Cancel parameter to true You can also modify the ComboList propertyso the appropriate drop-down button gets painted in the cell Note that the user might not actuallystart editing after this he could simply move the selection to a different cell or control

StartEdit The event is similar to BeforeEdit except the user has actually typed a key or clicked the dropdownbutton in the cell and really is about to start editing You can still cancel the editing at this point Notethat the Editor property is still null at this point because the control hasnt yet determined the typeof editor that should be used You can assign custom editors to the Editor property at this point

ChangeEdit The event is a wrapper of editorTextChanged event The event fires when the contents of the editorchange You can use this event to keep track of the current content in editor

SetupEditor The event fires after the editor control has been created and configured to edit the cell but before itis displayed You can change the editor properties at this point (for example set the maximum lengthor password character to be used in a TextBox editor) You can also attach your own event handlers tothe editor

ValidateEdit The event fires when the user is done editing before the editor value gets copied back into the gridYou can examine the original value by retrieving it from the grid (the event provides the coordinatesof the cell) You can examine the new value about to be assigned to the grid through the Editorproperties (for example EditorText) If the new value is not valid for the cell set the Cancel parameterto true and the grid remains in edit mode If instead of keeping the cell in edit mode you wouldrather restore the original value and leave edit mode set Cancel parameter to true and then call theFinishEditing method

LeaveEdit This event fires after the grid control leaves edit mode You can use this event to approve or deny the

FlexGrid for WinForms

120 Copyright copy GrapeCity Inc All rights reserved

new cell content or to change the editor content about to be committed

AfterEdit This event fires after the new value has been applied to the cell and the editor has been deactivatedYou can use this event to update anything that depends on the cell value (for example subtotals orsorting)

Also there are few events which are related to keyboard operations and are fired when a key is pressed They aresimilar to their counterparts from SystemWindowsFormsControl class apart from the fact that they occur when thegrid is in edit mode

Event Description

KeyDownEdit This event fires when grid is in edit mode and a key is pressed You can use this event toperform an action once or even multiple times while the key is held down such as movinga cursor

KeyPressEdit This event fires when grid is in edit mode and a character key is pressed You can use thisevent to perform any operation related to typing such as handling input in the cell editor

KeyUpEdit This event fires when grid is in edit mode and key is released You can use this event toplace a logic that executes after KeypressEdit logic has taken effect

Event Name Description

編集の無効化

FlexGrid by default allows end-user to edit the cell values at runtime However with FlexGrid you can easily managehow much control you want to give to the end-users using various properties provided by the FlexGrid

Disable Grid EditingTo disable editing of the whole WinForms FlexGrid you need to set AllowEditing property of the C1FlexGrid class tofalse as shown in the code below

Disable Row or Column EditingTo disable the editing of a particular row or column of the WinForms FlexGrid you can set the AllowEditing propertyof Row or Column object to false as shown in the code below

グリッドで編集を無効にします c1FlexGrid1AllowEditing = false

C

グリッドで編集を無効にしますc1FlexGrid1AllowEditing = False

VBNET

3行目の編集を無効にしますc1FlexGrid1Rows[3]AllowEditing = false 3列目の編集を無効にしますc1FlexGrid1Cols[3]AllowEditing = false

C

FlexGrid for WinForms

121 Copyright copy GrapeCity Inc All rights reserved

Disable Cell EditingTo disable editing of a particular cell you can use the BeforeEdit event and set the Cancel parameter for thatparticular cell to true

3行目の編集を無効にしますc1FlexGrid1Rows(3)AllowEditing = False

3列目の編集を無効にしますc1FlexGrid1Cols(3)AllowEditing = False

VBNET

セル編集を無効にしますprivate void C1FlexGrid1_BeforeEdit(object sender RowColEventArgs e) if ((eCol == 4) ampamp (eRow == 2)) eCancel = true

C

セル編集を無効にしますPrivate Sub C1FlexGrid1_BeforeEdit(ByVal sender As Object ByVal e As RowColEventArgs) If eCol = 4 AndAlso eRow = 2 Then eCancel = True End IfEnd Sub

VBNET

FlexGrid for WinForms

122 Copyright copy GrapeCity Inc All rights reserved

並べ替え

Sorting is one of the basic features a grid must have and FlexGrid provides you complete control on how data can besorted in ascending or descending order for easier data analysis This topic discusses about sorting in FlexGrid andother related operations

Topic Snapshot Content

Sort Operations Discusses various operations related to sorting

Sorting through CodeSort Multiple ColumnsRevertUndo SortingDisable Sort on a Particular ColumnSort OrderCustom Sorting

Sort Indicator Discusses how to hide position and customize sort indicator

HideDisplay Sort IndicatorPosition Sort IndicatorCustomize Sort Indicator

並べ替えの操作

FlexGrid by default allows end-users to apply sorting on a single column by clicking the column header in ascending ordescending order However the grid also provides you flexibility so that you can sort your data according to yourrequirement Below sections take you through the ways to perform various operations related to sorting

Sorting through CodeYou can apply sorting through code by calling Sort method of the C1FlexGrid class The method takes SortFlagsenumeration as its parameter which lets you provide the various sort options such as setting the sort order and ignorecasing The method has various overloads which gives you flexibility to apply sorting either on a column or a range ofcells rows or columns

Use the code below to sort columns and apply sorting options through code in the WinForms FlexGrid

FlexGrid for WinForms

123 Copyright copy GrapeCity Inc All rights reserved

Sort Multiple ColumnsTo apply sorting on multiple columns through code you can use the Sort property of Column class and then call theSort() method with SortFlags set to UseColSort The Sort property accepts values from SortFlags enumeration

Following code shows how to sort multiple columns of the WinForms FlexGrid through code

To allow user to sort multiple columns at runtime set AllowSorting property of the C1FlexGrid class to MultiColumn Theproperty accepts values from the AllowSortingEnum enumeration

Following code shows how to let user sort multiple columns of the WinForms FlexGrid at run-time

方法1 2番目の列を降順で並べ替えますc1FlexGrid1Sort(C1WinC1FlexGridSortFlagsDescending 2) 方法 2SortFlagを使用して複数の並べ替えオプションを指定しますC1WinC1FlexGridSortFlags order = C1WinC1FlexGridSortFlagsAscending | C1WinC1FlexGridSortFlagsIgnoreCase Sortメソッドを呼び出しますc1FlexGrid1Sort(order 2)

C

方法1 2番目の列を降順で並べ替えますc1FlexGrid1Sort(C1WinC1FlexGridSortFlagsDescending 2)

方法2 SortFlagを使用して複数の並べ替えオプションを指定しますDim order As C1WinC1FlexGridSortFlags = C1WinC1FlexGridSortFlagsAscending Or C1WinC1FlexGridSortFlagsIgnoreCase

Sortメソッドを呼び出しますc1FlexGrid1Sort(order 2)

VBNET

複数列を並べ替えますc1FlexGrid1Cols[2]Sort = SortFlagsAscendingc1FlexGrid1Cols[3]Sort = SortFlagsDescending Sortメソッドを呼び出しますc1FlexGrid1Sort(SortFlagsUseColSort 2 3)

C

複数列を並べ替えますc1FlexGrid1Cols(2)Sort = SortFlagsAscendingc1FlexGrid1Cols(3)Sort = SortFlagsDescending

Sortメソッドを呼び出しますc1FlexGrid1Sort(SortFlagsUseColSort 2 3)

VBNET

グリッドの複数の列での並べ替えを許可します c1FlexGrid1AllowSorting = AllowSortingEnumMultiColumn

C

FlexGrid for WinForms

124 Copyright copy GrapeCity Inc All rights reserved

RevertUndo SortingTo remove sorting from the grid you can set SortDefinition property of the C1FlexGrid class to an empty string

Below code how to remove sorting from the WinForms FlexGrid

Disable Sort on a Particular ColumnTo disable sorting on a particular column you need to set the AllowSorting property of that Column object to false

Use the code below to disable sorting on a particular column of the WinForms FlexGrid

Sort OrderOrder of sorting usually varies in case of bound and unbound mode When a column header is clicked in case of boundmode sorting is done same as DefaultViewSort property of the data table However in case of unbound mode columnis sorted either according to StringCompare method or by differentiating the lower and upper case according to theculture

Refer to the code below to specify sorting order of a WinForms FlexGrid column

グリッドの複数の列での並べ替えを許可しますc1FlexGrid1AllowSorting = AllowSortingEnumMultiColumn

VBNET

並べ替えを削除します c1FlexGrid1SortDefinition = stringEmpty

C

並べ替えを削除しますc1FlexGrid1SortDefinition = StringEmpty

VBNET

グリッドの特定の列での並べ替えを無効にしますc1FlexGrid1Cols[2]AllowSorting = false

C

グリッドの特定の列での並べ替えを無効にしますc1FlexGrid1Cols(2)AllowSorting = False

VBNET

C1WinC1FlexGridSortFlags order = C1WinC1FlexGridSortFlagsAscending | C1WinC1FlexGridSortFlagsIgnoreCase c1FlexGrid1Sort(order 2)

C

Dim order As C1WinC1FlexGridSortFlags = C1WinC1FlexGridSortFlagsAscending Or C1WinC1FlexGridSortFlagsIgnoreCasec1FlexGrid1Sort(order 2)

VBNET

FlexGrid for WinForms

125 Copyright copy GrapeCity Inc All rights reserved

Custom SortingFlexGrid provides several sorting options which are required for most commonly used scenarios such as ignore case usethe display value etc However if you need to have more flexibility and control over sort operation you can even writeyour own custom logic using the IComparer class For instance the example below sorts the Name column by fileextensions In the sample code custom logic to sort by file extension is implemented in the FileNameComparer class whichis then passed as parameter to Sort() method of the C1FlexGrid class

The code below demonstrates how to apply custom sorting on the WinForms FlexGrid columns

c1FlexGrid1Sort(new FileNameComparer(c1FlexGrid1 eOrder)) class FileNameComparer IComparer C1FlexGrid c1FlexGrid1 bool _desc

ctor public FileNameComparer(C1FlexGrid flex SortFlags order) c1FlexGrid1 = flex _desc = ((order amp SortFlagsDescending) = 0) IComparer public int Compare(object r1 object r2) ファイル名を取得します string s1 = (string)c1FlexGrid1[((Row)r1)Index Name] string s2 = (string)c1FlexGrid1[((Row)r2)Index Name]

拡張機能を比較します int icmp = stringCompare(PathGetExtension(s1) PathGetExtension(s2) true)

並べ替え順(昇順または降順)を返します return (_desc) -icmp icmp

C

C1FlexGrid1Sort(New FileNameComparer(C1FlexGrid1 SortFlagsAscending))

Public Class FileNameComparer Implements IComparer

Private c1FlexGrid1 As C1FlexGrid Private _desc As Boolean

Public Sub New(ByVal flex As C1FlexGrid ByVal order As SortFlags) c1FlexGrid1 = flex _desc = ((order And SortFlagsDescending) ltgt 0) End Sub

Public Function Compare(r1 As Object r2 As Object) As Integer Implements IComparerCompare Dim s1 As String = CStr(c1FlexGrid1((CType(r1 Row))Index Name)) Dim s2 As String = CStr(c1FlexGrid1((CType(r2 Row))Index Name)) Dim icmp As Integer = StringCompare(PathGetExtension(s1) PathGetExtension(s2) True) Return If((_desc) -icmp icmp) End Function

VBNET

FlexGrid for WinForms

126 Copyright copy GrapeCity Inc All rights reserved

For detailed implementation of custom sorting see the product sample named Custom Sort

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing WinFormsEdition using ComponentOneControlPanelexe

並べ替えのインジケータ

FlexGrid displays sort indicator a small triangular arrow sign to indicate the direction of sorting The grid alsoprovides flexibility to hide display position or customize the indicator

Hide or Display Sort IndicatorFlexGrid by default displays the sort indicator when a column header is clicked to sort the columns However you canhide the indicator by setting the ShowSortPosition property to None The property accepts valuesfrom ShowSortPositionEnum enumeration

Use the code below to hide the sort indicator displayed on the sorted WinForms FlexGrid column

Position Sort IndicatorSort indicator by default gets displayed towards the right side of the header cell However when the filtering isapplied on a column the sort indicator displays on top of the header cell to give place to the filtering icon You can fixthe position of sort indicator by setting value of ShowSortPosition property to Top or Right

Customize the position of column sort indicator in WinForms FlexGrid using the code below

Customize Sort IndicatorFlexGrid provides the GlyphEnum enumeration which lets you specify the image to be used for sort indicator Formore information on the GlyphEnum and glyph customization see Custom Glyphs

並べ替えインジケータを非表示にしますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumNone

C

並べ替えインジケータを非表示にしますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumNone

VBNET

並べ替えインジケータの位置を上に変更しますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumTop

C

並べ替えインジケータの位置を上に変更しますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumTop

VBNET

FlexGrid for WinForms

127 Copyright copy GrapeCity Inc All rights reserved

フィルタ

Grid filtering lets you narrow down display records according to a specified condition applied on a column It is especially useful in case of large data sets asit lets you easily analyze data by displaying a specific type of records only

This section discusses about the process types and customization of filters

Topic Snapshot Content

Filter Operations Discusses about how to enable or apply filtering and other related operations

Allow FilteringFiltering through CodeCustom FilteringRemove FilteringTypes of Filters

Filter UI Discusses about filtering icon its customization and how to set the filter language

Show Filter IconUse Custom IconsChange Filter Language

フィルタの操作

Data filtering in a grid can be performed in two ways

Header-based Filter

In header-based filtering an icon is displayed in the header cell of column which gives you options to specify the filter in a drop-down and alsoindicates if the filter is applied on a particular column In FlexGrid this behavior can be achieved by simply using AllowFiltering property of the gridIn this case filter does not require any extra real estate on the screen This approach also gives you flexibility to customize and create better filtereditors More details about same is given in the sections below

Filter Row

Filter row is a row dedicated for displaying the filtering criteria and appears just below the column header So in this case user can always see thefiltered columns and their current filtering criteria But this added advantage comes at the cost of extra screen real estate that a filter row needs InFlexGrid you can easily achieve filter row using the custom implementation For implementation see the product sample named Filter Row

Note The Filter Row sample is located at DocumentsComponentOne SamplesWinFormsv452C1FlexGridCS on your system if you haveinstalled the samples while installing WinForms Edition using ComponentOneControlPanelexe

Allow FilteringIn FlexGrid filtering can be enabled by setting the C1FlexGridAllowFiltering property to true This enables the default ColumnFilter on allcolumns of the grid The ColumnFilter lets the users choose from ValueFilter and ConditionFilter at runtime

FlexGrid for WinForms

128 Copyright copy GrapeCity Inc All rights reserved

You can also specify the filter types for each column by setting the AllowFiltering property of each Column object AllowFiltering property ofcolumn lets you choose from any of the following values

Value Description

Default Enables the ColumnFilter which is a combination of ValueFilter and ConditionFilter and gives user a runtime option to choose eitherof them

ByValue Enables ValueFilter which contains a checkbox list of values present in that column User can check off the values that should not bedisplayed in the filtered output

ByCondition Enables ConditionFilter which lets you specify combination of two conditions such as equals greater than contains etc Youcan combine the specified conditions using And and Or operator

Custom Lets you instantiate a custom filter and explicitly assign it to Filter property of the column

None Disables filtering for that column

Use the following code snippet to enable a condition filter on first column of the WinForms FlexGrid

For more details regarding abovementioned filter types see Types of Filters

Filtering through CodeAlthough AllowFiltering property of grid enables grid filtering and can be used in most common scenarios there may be cases where you need tofurther fine tune the filter options This can be achieved by modifying AllowFiltering and Filter properties of individual columns For example thecode below enables filtering in the WinForms FlexGrid but restricts the filtering to columns of type string

You can also customize the filtering process further by creating filters and assigning them to columns or by retrieving existing filters and modifyingtheir properties For example the code below creates a ConditionFilter in the WinForms FlexGrid configures it to select all items that are equal toGermany and then assigns the new filter to the ShipCountry column

グリッドでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = true 列1に対してフィルタを指定しますc1FlexGrid1Cols[1]AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

C

グリッドでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = True

列1に対してフィルタを指定しますc1FlexGrid1Cols(1)AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

VBNET

文字列型の列にフィルタリングを制限します foreach (Column c in c1FlexGrid1Cols) cAllowFiltering = cDataType == typeof(string) AllowFilteringDefault AllowFilteringNone

C

文字列型の列にフィルタリングを制限しますFor Each c As Column In c1FlexGrid1Cols cAllowFiltering = If(cDataType Is GetType(String) AllowFilteringDefault AllowFilteringNone)Next

VBNET

グリッドでフィルタリングを有効にします c1FlexGrid1AllowFiltering = true 新しいConditionFilterを作成します C1WinC1FlexGridConditionFilter Filter Filter = new C1WinC1FlexGridConditionFilter()

C

FlexGrid for WinForms

129 Copyright copy GrapeCity Inc All rights reserved

Custom FilteringWhen filtering is applied to FlexGrid it hides the rows that do not qualify the filtering criteria by setting their Visible property to false However insome cases you may want to customize this behavior For such scenarios you can use the BeforeFilter and AfterFilter events fired by FlexGridThe below example customizes the filtering behavior of WinForms FlexGrid by applying a different style to non-qualifying rows instead of hidingthem

Germanyのアイテムを絞り込むためのフィルタを作成します FilterCondition1Operator = C1WinC1FlexGridConditionOperatorEquals FilterCondition1Parameter = Germany 「ShipCountry」列に新しいフィルタを割り当てます c1FlexGrid1Cols[ShipCountry]Filter = Filter フィルタを適用します c1FlexGrid1ApplyFilters()

グリッドでフィルタリングを有効にしますc1FlexGrid1AllowFiltering = True

新しいConditionFilterを作成しますDim Filter As C1WinC1FlexGridConditionFilterFilter = New C1WinC1FlexGridConditionFilter()

Germanyのアイテムを絞り込むためのフィルタを作成しますFilterCondition1[Operator] = C1WinC1FlexGridConditionOperatorEqualsFilterCondition1Parameter = Germany

「ShipCountry」列に新しいフィルタを割り当てますc1FlexGrid1Cols(ShipCountry)Filter = Filter

フィルタを適用しますc1FlexGrid1ApplyFilters()

VBNET

private void c1FlexGrid1_BeforeFilter(object sender CancelEventArgs e) c1FlexGrid1BeginUpdate()

private void c1FlexGrid1_AfterFilter(object sender EventArgs e) フィルタリングされた行を表示するために使用されるスタイルを取得します var cs = c1FlexGrid1Styles[filteredOut]

すべての行にスタイルを適用します

C

FlexGrid for WinForms

130 Copyright copy GrapeCity Inc All rights reserved

The above code uses a custom style named filteredout which can be defined as shown in the code below

Remove FilteringUser can remove column filtering at runtime by using Clear option given in the filter UI of each column You can also remove filtering of the wholegrid programmatically by passing the empty string in FilterDefinition property of FlexGrid

Below code demonstrates how to clear all the filters from the WinForms FlexGrid

for (int r = c1FlexGrid1RowsFixed r lt c1FlexGrid1RowsCount r++) var row = c1FlexGrid1Rows[r] if (rowVisible) 通常の行スタイルをリセットします rowStyle = null else フィルタリングされた行 見えるようにしスタイルを適用します rowVisible = true rowStyle = cs

更新を再開します c1FlexGrid1EndUpdate()

Private Sub c1FlexGrid1_BeforeFilter(ByVal sender As Object ByVal e As CancelEventArgs) c1FlexGrid1BeginUpdate()End Sub

Private Sub c1FlexGrid1_AfterFilter(ByVal sender As Object ByVal e As EventArgs) フィルタリングされた行を表示するために使用されるスタイルを取得します Dim cs = c1FlexGrid1Styles(filteredOut)

すべての行にスタイルを適用します For r = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 Dim row = c1FlexGrid1Rows(r)

If rowVisible Then 通常の行スタイルをリセットします rowStyle = Nothing Else フィルタリングされた行 見えるようにしスタイルを適用します rowVisible = True rowStyle = cs End If Next

更新を再開します c1FlexGrid1EndUpdate()End Sub

VBNET

フィルタによって除外された行のスタイルを作成しますvar cs = c1FlexGrid1StylesAdd(filteredOut)csBackColor = ColorLightGraycsForeColor = ColorDarkGray

C

フィルタによって除外された行のスタイルを作成しますDim cs = c1FlexGrid1StylesAdd(filteredOut)csBackColor = ColorLightGraycsForeColor = ColorDarkGray

VBNET

フィルタ定義を空の文字列に設定してフィルタリングを削除しますc1FlexGrid1FilterDefinition = stringEmpty

C

FlexGrid for WinForms

131 Copyright copy GrapeCity Inc All rights reserved

フィルタ定義を空の文字列に設定してフィルタリングを削除しますc1FlexGrid1FilterDefinition = StringEmpty

VBNET

フィルタの種類

FlexGrid not only provides built-in filters such as Column filter Value filter and Condition Filter but also lets youcreate your own custom filter The built-in filters are provided through AllowFiltering property of Column class whichlets you set the type of filter to be applied on a particular column On the other hand the custom filters make use ofthe IC1ColumnFilter interface and the IC1ColumnFilterEditor interface This topic discusses the implementation ofbuilt-in and custom filters in detail

Column FilterColumn filter is the default filter that is applied to all the columns automatically when AllowFiltering property of thegrid is set to true The ColumnFilter is a combination of ValueFilter and ConditionFilter (discussed below) and givesuser an option to choose either of them at runtime While working with code you can use its ValueFilterand ConditionFilter properties to access the two types of filters The filter also provides Apply method to apply filterto a value and Reset method to reset the filter and hence making it inactive

Use the below code to apply column filter on ProductName column of the WinForms FlexGrid

列フィルタ(ProductNameが「C」で始まる製品をフィルター処理します)ColumnFilter colFilter = new ColumnFilter()colFilterConditionFilterCondition1Parameter = CcolFilterConditionFilterCondition1Operator = ConditionOperatorBeginsWithc1FlexGrid1Cols[ProductName]Filter = colFilter

C

列フィルタ(ProductNameが「C」で始まる製品をフィルター処理します) Dim colFilter As ColumnFilter = New ColumnFilter()

VBNET

FlexGrid for WinForms

132 Copyright copy GrapeCity Inc All rights reserved

Value FilterValue filter refers to the value based filter which gets enabled on setting the AllowFiltering property of column toByValue The ValueFilter provides the dropdown list of all values with checkbox which lets the user select the valueswhich are to be displayed in the output These values can be get or set through the ShowValues property You canalso set a limit on number of values to be displayed in the dropdown list by setting the ValuesLimit property Just likecolumn filter value filter also provides Apply method to apply filter to a value and Reset method to reset the filter

Below code shows how to apply ValueFilter on a column of the WinForms FlexGrid

Condition FilterCondition filter refers to a filter based on one or two logical conditions which can be enabled by setting theAllowFiltering property to ByCondition The ConditionFilter gives user an option to set the conditionsthrough Condition1 and Condition2 properties which can be combined using ANDOR operator by settingthe AndConditions property to filter the records Similar to other filters this class also provides Apply and Resetmethod

colFilterConditionFilterCondition1Parameter = C colFilterConditionFilterCondition1[Operator] = ConditionOperatorBeginsWith c1FlexGrid1Cols(ProductName)Filter = colFilter

値フィルタ(CategoryIdが12358である製品をフィルタ処理します)ValueFilter valueFilter = new ValueFilter()valueFilterShowValues = new object[] 1 2 3 5 8 c1FlexGrid1Cols[CategoryId]Filter = valueFilter

C

値フィルタ(CategoryIdが12358である製品をフィルタ処理します) Dim valueFilter As ValueFilter = New ValueFilter() valueFilterShowValues = New Object() 1 2 3 5 8 c1FlexGrid1Cols(CategoryId)Filter = valueFilter

VBNET

FlexGrid for WinForms

133 Copyright copy GrapeCity Inc All rights reserved

Below code demonstrates how to apply a ConditionFilter on a WinForms FlexGrid column

Custom FilterThe abovementioned filters provide you enough flexibility to implement most common filtering scenarios efficientlyIn addition custom filter option also lets you create your own filter to meet any other specialized requirements ofyour application To create a custom filter you need to create a filter class that implements the IC1ColumnFilterinterface and an editor class that implements the IC1ColumnFilterEditor interface Below example shows theimplementation of a custom string filter which lets you filter based on ranges

条件フィルタ(UnitPricegt = 50およびlt= 100の製品をフィルタ処理します)ConditionFilter conditionFilter = new ConditionFilter()conditionFilterCondition1Parameter = 50conditionFilterCondition1Operator = ConditionOperatorGreaterThanOrEqualToconditionFilterCondition2Parameter = 100conditionFilterCondition2Operator = ConditionOperatorLessThanOrEqualToconditionFilterAndConditions = truec1FlexGrid1Cols[UnitPrice]Filter = conditionFilter

C

条件フィルタ(UnitPricegt = 50およびlt= 100の製品をフィルタ処理します) Dim conditionFilter As ConditionFilter = New ConditionFilter() conditionFilterCondition1Parameter = 50 conditionFilterCondition1[Operator] = ConditionOperatorGreaterThanOrEqualTo conditionFilterCondition2Parameter = 100 conditionFilterCondition2[Operator] = ConditionOperatorLessThanOrEqualTo conditionFilterAndConditions = True c1FlexGrid1Cols(UnitPrice)Filter = conditionFilter

VBNET

FlexGrid for WinForms

134 Copyright copy GrapeCity Inc All rights reserved

Following is the code of a custom filter created for the WinForms FlexGrid Note that the class implementsIC1CustomFilter interface

StringFiltercs

class StringFilter C1WinC1FlexGridIC1ColumnFilter

ListltPointgt _ranges = new ListltPointgt()

ltsummarygt このフィッタが受け入れる文字列を定義するポイントのリストを取得します ltsummarygt public ListltPointgt Ranges get return _ranges

範囲リストが空でない場合フィルタはアクティブです public bool IsActive get return _rangesCount gt 0

フィルタをリセットします public void Reset() _rangesClear()

指定された日付にフィルタを適用します public bool Apply(object value) if (value = null)

C

FlexGrid for WinForms

135 Copyright copy GrapeCity Inc All rights reserved

var s = valueToString() if (sLength gt 0) int c = charToUpperInvariant(s[0]) foreach (var cr in _ranges) if (c gt= charToUpperInvariant((char)crX) ampamp c lt= charToUpperInvariant((char)crY)) return true return false

このフィルタのエディタコントロールを返します public C1WinC1FlexGridIC1ColumnFilterEditor GetEditor() return new StringFilterEditor()

Friend Class StringFilter Implements C1WinC1FlexGridIC1ColumnFilter Private _ranges As List(Of Point) = New List(Of Point)()

ltsummarygt このフィッタが受け入れる文字列を定義するポイントのリストを取得します ltsummarygt Public ReadOnly Property Ranges As List(Of Point) Get Return _ranges End Get End Property

範囲リストが空でない場合フィルタはアクティブです Public ReadOnly Property IsActive As Boolean Implements C1WinC1FlexGridIC1ColumnFilterIsActive Get Return _rangesCount gt 0 End Get End Property

フィルタをリセットします Public Sub Reset() Implements C1WinC1FlexGridIC1ColumnFilterReset _rangesClear() End Sub

指定された日付にフィルタを適用します Public Function Apply(ByVal value As Object) As Boolean Implements C1WinC1FlexGridIC1ColumnFilterApply If value IsNot Nothing Then Dim s = valueToString()

If sLength gt 0 Then Dim c As Integer = AscW(CharToUpperInvariant(s(0)))

VBNET

FlexGrid for WinForms

136 Copyright copy GrapeCity Inc All rights reserved

Following is the code of a custom class that implements IC1CustomFilterEditor interface

StringFilterEditorcs

For Each cr In _ranges

If c gt= AscW(CharToUpperInvariant(MicrosoftVisualBasicChrW(crX))) AndAlso c lt= AscW(CharToUpperInvariant(MicrosoftVisualBasicChrW(crY))) Then Return True End If Next End If End If

Return False End Function

このフィルタのエディタコントロールを返します Public Function GetEditor() As C1WinC1FlexGridIC1ColumnFilterEditor Implements C1WinC1FlexGridIC1ColumnFilterGetEditor Return New StringFilterEditor() End Function

End Class

public partial class StringFilterEditor UserControl C1WinC1FlexGridIC1ColumnFilterEditor StringFilter _filter

public StringFilterEditor() InitializeComponent()

public void Initialize(C1WinC1FlexGridC1FlexGridBase grid int columnIndex C1WinC1FlexGridIC1ColumnFilter filter) _filter = (StringFilter)filter

チェックボックスの値を初期化します foreach (var pt in _filterRanges) switch ((char)ptX) case A _chkAEChecked = true break case F _chkFJChecked = true break case K _chkKOChecked = true break case P _chkPTChecked = true

C

FlexGrid for WinForms

137 Copyright copy GrapeCity Inc All rights reserved

break case U _chkUZChecked = true break public void ApplyChanges() フィルタをリセットします _filterRangesClear()

選択した範囲を追加します foreach (Control ctl in thisControls) var cb = ctl as CheckBox if (cb = null ampamp cbChecked) var pt = new Point((int)cbText[0] (int)cbText[cbTextLength - 1]) _filterRangesAdd(pt) public bool KeepFormOpen get return false void _chkAE_CheckedChanged(object sender EventArgs e) var cb = sender as CheckBox cbFont = new Font(Font cbChecked FontStyleBold FontStyleRegular)

Public Partial Class StringFilterEditor Inherits UserControl Implements C1WinC1FlexGridIC1ColumnFilterEditor

Private _filter As StringFilter Public Sub New() InitializeComponent() End Sub

Public Sub Initialize(ByVal grid As C1WinC1FlexGridC1FlexGridBase ByVal columnIndex As Integer ByVal filter As C1WinC1FlexGridIC1ColumnFilter) Implements C1WinC1FlexGridIC1ColumnFilterEditorInitialize _filter = CType(filter StringFilter)

チェックボックスの値を初期化します For Each pt In _filterRanges

Select Case MicrosoftVisualBasicChrW(ptX) Case Ac _chkAEChecked = True Case Fc _chkFJChecked = True Case Kc _chkKOChecked = True Case Pc

VBNET

FlexGrid for WinForms

138 Copyright copy GrapeCity Inc All rights reserved

_chkPTChecked = True Case Uc _chkUZChecked = True End Select Next End Sub

Public Sub ApplyChanges() Implements C1WinC1FlexGridIC1ColumnFilterEditorApplyChanges フィルタをリセットします _filterRangesClear()

選択した範囲を追加します For Each ctl As Control In Controls Dim cb = TryCast(ctl CheckBox)

If cb IsNot Nothing AndAlso cbChecked Then Dim pt = New Point(MicrosoftVisualBasicAscW(cbText(0)) MicrosoftVisualBasicAscW(cbText(cbTextLength - 1))) _filterRangesAdd(pt) End If Next End Sub

Public ReadOnly Property KeepFormOpen As Boolean Implements C1WinC1FlexGridIC1ColumnFilterEditorKeepFormOpen Get Return False End Get End Property

Private Sub _chkAE_CheckedChanged(ByVal sender As Object ByVal e As EventArgs) Dim cb = TryCast(sender CheckBox) cbFont = New Font(MyBaseFont If(cbChecked FontStyleBold FontStyleRegular)) End Sub

End Class

フィルタUI

FlexGrid provides several options to flexibly customize the filtering UI and lets you create your own unique filter for yourapplication The control allows you to show hide and customize the filtering icon You can even change the language displaying infilter to meet your localization requirements

Show Filter Icon

FlexGrid by default shows the filtering icon( ) when mouse hovers over the filterable column header However you can chooseto display the filtering icon always by setting ShowFilterIcon property of the C1FlexGrid class to Always The property accepts thevalues from FilterIconVisibility enumeration

FlexGrid for WinForms

139 Copyright copy GrapeCity Inc All rights reserved

Use the code below to always display the filter icon on filtered columns of the WinForms FlexGrid

Use Custom IconsFlexGrid also lets you customize the filtering icon by using Glyphs property of the C1FlexGrid class which accepts an imagethrough GlyphEnum enumeration You can also change icon displayed on the current filtered column using the same enumerationFor more information about custom glyphs see Custom Glyphs

常にフィルタのアイコンを表示しますc1FlexGrid1ShowFilterIcon = C1WinC1FlexGridFilterIconVisibilityAlways

C

常にフィルタのアイコンを表示しますc1FlexGrid1ShowFilterIcon = C1WinC1FlexGridFilterIconVisibilityAlways

VBNET

FlexGrid for WinForms

140 Copyright copy GrapeCity Inc All rights reserved

Following code displays how to apply custom icons on filtered columns of the WinForms FlexGrid

Change Filter LanguageBy default FlexGrid localizes the column filter editor to use language specified by the CurrentUICulture setting However you canuse the Language property to override the default and specify the language to be used when grid displays the column filter editor

Use the below code to change the display language of filter in the WinForms FlexGrid

フィルタのアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilterEditor] = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilteredColumn] = ImageFromFile(filterico)

C

フィルタのアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilterEditor) = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilteredColumn) = ImageFromFile(filterico)

VBNET

フィルタ言語を日本語に設定しますc1FlexGrid1Language = C1UtilLocalizationLanguageJapanese

C

フィルタ言語を日本語に設定しますc1FlexGrid1Language = C1UtilLocalizationLanguageJapanese

VBNET

FlexGrid for WinForms

141 Copyright copy GrapeCity Inc All rights reserved

検索

With FlexGrid you can easily perform search either on the entire grid or just a specific column This topic discusseshow you can enable search in FlexGrid

Search in Entire GridTo search the entire FlexGrid you need to add the C1FlexGridSearchPanel control to the form and associate it with thegrid to be searched using SetC1FlexGridSearchPanel method The C1FlexGridSearchPanel control highlights thesearch results and filters the records having search results automatically However you can choose not to highlight theresults by setting the HighlightSearchResults to false It also provides a SearchMode property to set whether tostart the search automatically or on hitting the Search button or Enter key You can also set the watermark in searchbox as well as a time delay in search

Use the code below to search the entire WinForms FlexGrid using SearchPanel

検索パネルを検索対象のFlexGridに関連付けますc1FlexGridSearchPanel1SetC1FlexGridSearchPanel(c1FlexGrid1 c1FlexGridSearchPanel1)

検索を構成しますc1FlexGridSearchPanel1HighlightSearchResults = truec1FlexGridSearchPanel1SearchMode = C1WinC1FlexGridSearchModeAlways c1FlexGridSearchPanel1Watermark = Search productsc1FlexGridSearchPanel1SearchDelay = 2

C

検索パネルを検索対象のFlexGridに関連付けます

VBNET

FlexGrid for WinForms

142 Copyright copy GrapeCity Inc All rights reserved

Search in ColumnTo enable column-wise search FlexGrid provides AutoSearch property of the C1FlexGrid class which accepts valuesfrom AutoSearchEnum enumeration The enumeration lets you start downward column search from the first scrollablerow or from the current cursor position To search a value in a particular column you need to keep the cursor in thatcolumn and type the value to be searched and grid automatically jumps to the search result in that column You canalso set delay in search by setting the AutoSearchDelay property

Following code enables column-wise search in the WinForms FlexGrid

c1FlexGridSearchPanel1SetC1FlexGridSearchPanel(c1FlexGrid1 c1FlexGridSearchPanel1)

検索を構成しますc1FlexGridSearchPanel1HighlightSearchResults = Truec1FlexGridSearchPanel1SearchMode = C1WinC1FlexGridSearchModeAlwaysc1FlexGridSearchPanel1Watermark = Search productsc1FlexGridSearchPanel1SearchDelay = 2

一番上の行からの列単位の検索を有効にしますc1FlexGrid1AutoSearch = C1WinC1FlexGridAutoSearchEnumFromTopc1FlexGrid1AutoSearchDelay = 2

C

一番上の行からの列単位の検索を有効にしますc1FlexGrid1AutoSearch = C1WinC1FlexGridAutoSearchEnumFromTopc1FlexGrid1AutoSearchDelay = 2

VBNET

FlexGrid for WinForms

143 Copyright copy GrapeCity Inc All rights reserved

マージ

FlexGrid allows you to merge cells with same values making them span multiple rows or columns This capability is useful for enhancing appearance andclarity of data displayed in the grid The effect of these settings is similar to the HTML ltROWSPANgt and ltCOLSPANgt tags

Cell merging has several possible uses For example you can use it to create merged table headers merged data views or grids where the text spills intoadjacent columns This section discusses these scenarios in the topics below

Topic Snapshot Content

Auto-merge Discusses about how to enable automatic merging in grid

Free auto-mergeRestricted auto-mergeMerge table headers

Handle Spilling Text Discusses how to display long texts in normal and node rows

Handle Spill in Normal CellsHandle Text in Node Rows

Custom Merge Discusses about ways to customize the default merging behavior

Method 1 Use IComparer interfaceMethod 2 Override the GetMergedRange method

自動マージ

FlexGrid lets you enable automatic cell merging in the grid by setting the AllowMerging property to a value other than None Inaddition you need to set the AllowMerging property of each target row or column to true Merging occurs only if adjacent cellscontain the same non-empty string There is no method to force a pair of cells to merge The merging is done automaticallybased on the cell contents This feature makes it easy to provide merged views of sorted data where values in adjacent rowspresent repeated data

Free Auto-mergeFree auto-merge refers to merging of cells with just one pre-condition of having same values in adjacent cells To automaticallymerge the cells in a row or a column you simply need to set AllowMerging property of the C1FlexGrid class to Free and setAllowMerging property of the target row or column object to true

FlexGrid for WinForms

144 Copyright copy GrapeCity Inc All rights reserved

Below code shows how to apply free merging on a WinForms FlexGrid column

Restricted Auto-mergeIn most of the scenarios you would want the grid to merge the grid cells with same values only if cells above or in left directionare also merged This behavior is called restricted auto-merge and can be achieved by setting the C1FlexGridAllowMergingproperty to RestrictAll RestrictRows or RestrictCols This is required in addition to setting the AllowMerging property oftarget row or column to true

Use the code below to allow restricted auto-merging on a WinForms FlexGrid column

Merge Table HeadersMerging the header cells specially in case of multi-row header is another very common scenario used in grids and tables Tomerge the header cells you must set the C1FlexGridAllowMerging property to FixedOnly You must also set theAllowMerging property of designated row and columns to true In this case headers cells with same value merge together togive a simplified appearance

許可される結合の種類を指定しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFree 結合を許可する列を指定しますc1FlexGrid1Cols[2]AllowMerging = true

C

許可される結合の種類を指定しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFree

結合を許可する列を指定しますc1FlexGrid1Cols(2)AllowMerging = True

VBNET

結合を許可する列を指定しますc1FlexGrid1Cols[3]AllowMerging = true 左側のセルが結合されている場合にのみ列を結合しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumRestrictCols

C

結合を許可する列を指定しますc1FlexGrid1Cols(3)AllowMerging = True

左側のセルが結合されている場合にのみ列を結合しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumRestrictCols

VBNET

FlexGrid for WinForms

145 Copyright copy GrapeCity Inc All rights reserved

Following code demonstrates how to apply merging only on table headers of the WinForms FlexGrid

Custom Auto-mergeFlexGrid also provides a Custom option through AllowMerging enumeration In this case auto-merge is performed on cellrange collection provided using MergedRanges property of the C1FlexGrid class The custom auto-merge is performedindependent of cell content For instance below image shows the merging of two specified cell ranges despite of the differentcell values

固定の行と列の結合を許可しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

固定の行と列の結合を許可しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

FlexGrid for WinForms

146 Copyright copy GrapeCity Inc All rights reserved

Use the following code snippet to apply custom merge on the WinForms FlexGrid

結合のモードをアクティブにしますthisc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumCustom

いくつかのマージされた範囲を定義します 2つのセルは幅が広く1つのセルは高いですthisc1FlexGrid1MergedRangesAdd(2 2 2 3)

3つのセルは幅が広く3つのセルは高さですthisc1FlexGrid1MergedRangesAdd(5 2 7 4)

C

結合のモードをアクティブにしますMec1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumCustom

いくつかのマージされた範囲を定義します 2つのセルは幅が広く1つのセルは高いですMec1FlexGrid1MergedRangesAdd(2 2 2 3)

3つのセルは幅が広く3つのセルは高さですMec1FlexGrid1MergedRangesAdd(5 2 7 4)

VBNET

はみ出して表示されるセルの処理

In FlexGrid you can create the same behavior as excel for handling long text entries by spilling them into emptyadjacent cells This behavior not only helps you in handling long text entries of usual cells but also in displayingoutline nodes which are different from data rows This topic discusses these two scenarios in the following sectionsThese settings work on the grid level and does not need you to set AllowMerging property of specific row or column

Handle Spill in Normal CellsThis FlexGrid setting causes text that is too long to fit in a cell to spill into empty adjacent cells If you have a longentry in a cell and the adjacent cell is empty the entry spills onto the adjacent cells to occupy as much room as

FlexGrid for WinForms

147 Copyright copy GrapeCity Inc All rights reserved

needed This behavior can be achieved by setting the AllowMerging property to Spill For instance in the imagebelow long data strings from TestGroup column cells spill to the empty Flag column cells giving a better visibility ofdata while using the available space on the grid

Following code enables spilling of long text to adjacent empty cell in the WinForms FlexGrid

Handle Text in Node RowsThe Nodes setting is similar to Spill but only applies to outline nodes This setting is useful when data is organizedinto groups and the node rows contain information in a format different from the data rows For this you must setthe C1FlexGridAllowMerging property to Nodes

長いテキストを隣接する空のセルにこぼしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumSpill

C

長いテキストを隣接する空のセルにこぼしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumSpill

VBNET

FlexGrid for WinForms

148 Copyright copy GrapeCity Inc All rights reserved

Following code shows how to handle long text in node rows of the WinForms FlexGrid

ノード行の長いテキストを隣接する空のセルにスピルします c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumNodes

C

ノード行の長いテキストを隣接する空のセルにスピルしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumNodes

VBNET

カスタムのマージ

FlexGrid by default gives you enough options to merge in most common scenarios using AllowMerging propertyHowever there may be instances where you want to customize the merging options to get more out of your grid Youcan customize the default merging behavior in two ways

Method 1 Use IComparer InterfaceBy default the grid merges adjacent cells containing same non-null value In default scenario string comparisons arecase-sensitive and blanks are included However you can also merge cells using a case-insensitive comparison andtrimming blanks by writing a custom class that implements IComparer interface and assign it to CustomComparerproperty of the C1FlexGrid class

Method 2 Override the GetMergedRange MethodAnother way is to create a new class that derives from the C1FlexGrid class and overrides the GetMergedRangeand GetData methods to provide your own custom merging logic It merges the cells based on contextual

FlexGrid for WinForms

149 Copyright copy GrapeCity Inc All rights reserved

understanding of data in FlexGrid which is implemented through the overridden methods in the sample The belowexample demonstrates custom merging in timetable of each lecturer using the WinForms FlexGrid

public override CellRange GetMergedRange(int row int col bool clip) 結合のロジックで使用するID列のインデックスを保存します _colIndex = ColsIndexOf(LecturerID)

結合する時にカスタムデータを使用するようにフラグを設定します _doingMerge = true

基本クラスの結合のロジックを呼び出します(GetDataメソッドを使用してデータを取得します) CellRange cellRange = baseGetMergedRange(row col clip)

GetDataが通常どおりに動作するようにフラグをリセットします _doingMerge = false

結合された範囲を返します return cellRange

public override Object GetData(int row int col) 結合範囲を決定するためのデータを取得します ID列のコンテンツを追加して異なるIDの行のセルがマージされないようにします if (_doingMerge ampamp _colIndex gt -1 ampamp col = _colIndex) SystemDiagnosticsDebugWriteLine($rowcol) return baseGetDataDisplay(row col) + baseGetDataDisplay(row _colIndex)

C

FlexGrid for WinForms

150 Copyright copy GrapeCity Inc All rights reserved

For detailed implementation of more scenarios of custom merging see the product Projects named CustomMergeCustomMerge2 CustomMerge3 CustomMerge4

Note The abovementioned product samples are located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installingWinForms Edition using ComponentOneControlPanelexe

表示測定編集などするデータを取得します 基本クラスに通常どおり処理させます return baseGetData(row col)

Public Overrides Function GetMergedRange(ByVal row As Integer ByVal col As Integer ByVal clip As Boolean) As CellRange 結合のロジックで使用するID列のインデックスを保存します _colIndex = ColsIndexOf(LecturerID)

結合する時にカスタムデータを使用するようにフラグを設定します _doingMerge = True

基本クラスの結合のロジックを呼び出します(GetDataメソッドを使用してデータを取得します) Dim cellRange As CellRange = MyBaseGetMergedRange(row col clip)

GetDataが通常どおりに動作するようにフラグをリセットします _doingMerge = False

結合された範囲を返します Return cellRangeEnd Function

Public Overrides Function GetData(ByVal row As Integer ByVal col As Integer) As Object 結合範囲を決定するためのデータを取得します ID列のコンテンツを追加して異なるIDの行のセルがマージされないようにします If _doingMerge AndAlso _colIndex gt -1 AndAlso col ltgt _colIndex Then DebugWriteLine($rowcol) Return MyBaseGetDataDisplay(row col) + MyBaseGetDataDisplay(row _colIndex) End If

表示測定編集などするデータを取得します 基本クラスに通常どおり処理させます Return MyBaseGetData(row col)End Function

VBNET

FlexGrid for WinForms

151 Copyright copy GrapeCity Inc All rights reserved

グループ

Grouping refers to organizing the grid data into a hierarchical structure where rows with common column value aredisplayed as a group The feature also lets you expand or collapse the groups to facilitate easier analysis of grid data

In FlexGrid grouping can be achieved through code as well as through user interaction via column context menuand FlexGridGroupPanel control This topic discusses these ways and additional operations related to grouping

Grouping through CodeFlexGrid provides GroupDescriptions property to describe how data source items are grouped in the grid Thisproperty accepts the instance of any collection which implements IList interface (eg List) as its value The items of thecollection describe grouping using a property name as the criterion

Following code shows how to apply grouping in the WinForms FlexGrid through code

Grouping through Group Panel

CustomerIDでデータをグループ化しますc1FlexGrid1GroupDescriptions = new ListltGroupDescriptiongt() new GroupDescription(CustomerID)

C

CustomerIDでデータをグループ化しますc1FlexGrid1GroupDescriptions = New List(Of GroupDescription)() From New GroupDescription(CustomerID)

VBNET

FlexGrid for WinForms

152 Copyright copy GrapeCity Inc All rights reserved

FlexGrid also lets you create groups at runtime using an extension control named C1FlexGridGroupPanel which isprovided by the C1WinC1FlexGridGroupPanel assembly

To achieve grouping in FlexGrid at runtime add the C1FlexGridGroupPanel control to the form and bind it with thegrid to be bound using FlexGrid property of the C1FlexGridGroupPanel class Once a grid is bound to the grouppanel control you can drag and drop the columns to panel in order to group the grid by that column To create anested hierarchy of dragged columns you can drag multiple columns in the desired order You can also set themaximum number of groups allowed within FlexGrid using MaxGroups property of the C1FlexGridGroupPanel classBy default all the created groups appear in the expanded state To change this setting and display the groups incollapsed state by default you can set the AutoExpandAllGroups property to false The group panel control alsoprovides the Text property to display a string when no columns are dropped on the panel

Use the code below to apply grouping in WinForms FlexGrid through the FlexGridGroupPanel control

C1FlexGridGroupPanel c1FlexGridGroupPanel = new C1FlexGridGroupPanel()c1FlexGridGroupPanelBounds = new SystemDrawingRectangle(00 650 150)thisControlsAdd(c1FlexGridGroupPanel) C1FlexGridGroupPanelの一般プロパティを設定しますc1FlexGridGroupPanelFlexGrid = c1FlexGrid1c1FlexGridGroupPanelText = Drag the columns herec1FlexGridGroupPanelMaxGroups = 5c1FlexGridGroupPanelAutoExpandAllGroups = true

C

Dim c1FlexGridGroupPanel As C1FlexGridGroupPanel = New C1FlexGridGroupPanel() c1FlexGridGroupPanelBounds = New DrawingRectangle(0 0 650 150) MeControlsAdd(c1FlexGridGroupPanel)

VBNET

FlexGrid for WinForms

153 Copyright copy GrapeCity Inc All rights reserved

Grouping through Context MenuFlexGrid provides support for column context menu at run-time to facilitate quick actions related to columnoperations One of these context menu options is Group By This Column You can use this context menu option togroup the grid data by any of the columns at run-time Once grouping is applied you also get the Ungroup option toremove grouping To enable the column context menu you need to set ColumnContextMenuEnabled propertyprovided by the C1FlexGrid class to true By default this property is set to false

Grouping and MoreApart from the default features grouping in FlexGrid comes with many other options to give you ample flexibility tomeet your requirements

Use the SubtotalPosition property to change the position of group row which gets displayed above the groupby defaultSet the HideGroupedColumns property to true to hide the columns by which grid is groupedChange the format of group header by using the GroupHeaderFormat property By default the group row

C1FlexGridGroupPanelの一般プロパティを設定します c1FlexGridGroupPanelFlexGrid = c1FlexGrid1 c1FlexGridGroupPanelText = Drag the columns here c1FlexGridGroupPanelMaxGroups = 5 c1FlexGridGroupPanelAutoExpandAllGroups = True

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = true

C

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = True

VBNET

FlexGrid for WinForms

154 Copyright copy GrapeCity Inc All rights reserved

displays a string of namevalue formatSet the C1FlexGridAllowMerging property to AllowMergingEnumNodes to spill the long group headercontent into the adjacent empty cells For more information see Handle Text in Node RowsDisplay aggregate value of columns in group header by using Aggregate property of the Column classUse AllowSorting property to sort the groups based on their valuesUse the GridTreeStyle property to customize the appearance of outline tree that shows the grouping inFlexGrid For more information see Style the Tree Grid

FlexGrid for WinForms

155 Copyright copy GrapeCity Inc All rights reserved

集計

Summarizing data is one of the most important features of the grid where you can easily group the similar data andcalculate various types of aggregates such as Sum Average Count Max Min and more

In FlexGrid you can easily summarize data by using SubTotal method of the C1FlexGrid class It adds subtotal rows thatcontain aggregate data for the regular (non-subtotal) rows and also supports the hierarchical aggregates The method hasvarious overloads which gives you enough flexibility to deal with multiple summarizing related scenarios All theseoverloads have one parameter in common that is AggregateEnum which lets you set the type of aggregate you want toimplement Other parameters in various overloads let you set the outline level start and end column and column thatcontains values to be aggregated

Create SubtotalsBelow example demonstrates the use of SubTotal method in the WinForms FlexGrid for calculation of average aggregatebased on Score column

Style SubtotalsWhen the Subtotal method adds the rows with the aggregate information it automatically assigns in-built subtotal styles

グリッドに存在する既存の小計をすべてクリアしますc1FlexGrid1Subtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加しますc1FlexGrid1Subtotal(AggregateEnumAverage 1 3 3 4 Average for 0)

C

グリッドに存在する既存の小計をすべてクリアしますc1FlexGrid1Subtotal(AggregateEnumClear)

レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加しますc1FlexGrid1Subtotal(AggregateEnumAverage 1 3 3 4 Average for 0)

VBNET

FlexGrid for WinForms

156 Copyright copy GrapeCity Inc All rights reserved

to the new rows You can customize the appearance of the subtotal rows by changing the properties of the outline stylesin the designer with the Style Editor or using the code Below example demonstrates styling of subtotals at three levels inthe WinForms FlexGrid

Customize SubtotalsFlexGrid in addition to built-in aggregate options lets you create custom expressions in bound mode and use them assubtotals in groups along with aggregates You can specify the custom expressions for a column using GroupExpressionproperty of the Column class Below example demonstrates how to create a custom expression as a subtotal for Qualifiedcolumn of the WinForms FlexGrid

小計をレベル0でスタイル設定しますCellStyle s = c1FlexGrid1Styles[CellStyleEnumSubtotal0]sBackColor = ColorBlacksForeColor = ColorWhitesFont = new Font(c1FlexGrid1Font FontStyleBold) 小計をレベル1でスタイル設定しますs = c1FlexGrid1Styles[CellStyleEnumSubtotal1]sBackColor = ColorDarkBluesForeColor = ColorWhite

小計をレベル2でスタイル設定しますs = c1FlexGrid1Styles[CellStyleEnumSubtotal2]sBackColor = ColorDarkRedsForeColor = ColorWhitec1FlexGrid1AutoSizeCols()

C

Dim s As CellStyle = c1FlexGrid1Styles(CellStyleEnumSubtotal0) sBackColor = ColorBlack sForeColor = ColorWhite sFont = New Font(c1FlexGrid1Font FontStyleBold)

s = c1FlexGrid1Styles(CellStyleEnumSubtotal1) sBackColor = ColorDarkBlue sForeColor = ColorWhite

s = c1FlexGrid1Styles(CellStyleEnumSubtotal2) sBackColor = ColorDarkRed sForeColor = ColorWhite c1FlexGrid1AutoSizeCols()

VBNET

FlexGrid for WinForms

157 Copyright copy GrapeCity Inc All rights reserved

public void CustomizeSubTotal(C1FlexGrid c1FlexGrid1) ListltGroupDescriptiongt grps = new ListltGroupDescriptiongt() 列「Course」のグループを作成します GroupDescription grp = new GroupDescription(Course ListSortDirectionDescending true) grpsAdd(grp) 上記のグループに従ってFlexGridをグループ化します c1FlexGrid1GroupDescriptions = grps カスタムの計算式を使用してFlexGridに新しい列を追加します var column = c1FlexGrid1ColsAdd() columnName = Qualified columnDataType = typeof(object) columnCaption = Qualified(gt5000) columnAllowEditing = false columnExpression = [Attendance] [Score] GroupExpression の実装 c1FlexGrid1Cols[Score]GroupExpression = =Average([Score]) c1FlexGrid1Cols[Attendance]GroupExpression = =Average([Attendance]) c1FlexGrid1Cols[Qualified]GroupExpression = =iif(Average([Score][Attendance])lt5000falsetrue) c1FlexGrid1AutoSizeCols()

C

Public Sub CustomizeSubTotal(ByVal c1FlexGrid1 As C1FlexGrid) Dim grps As List(Of GroupDescription) = New List(Of GroupDescription)() 列「Course」のグループを作成します Dim grp As GroupDescription = New GroupDescription(Course ListSortDirectionDescending True) grpsAdd(grp)

上記のグループに従ってFlexGridをグループ化します c1FlexGrid1GroupDescriptions = grps

カスタムの計算式を使用してFlexGridに新しい列を追加します Dim column = c1FlexGrid1ColsAdd()

VBNET

FlexGrid for WinForms

158 Copyright copy GrapeCity Inc All rights reserved

columnName = Qualified columnDataType = GetType(Object) columnCaption = Qualified(gt5000) columnAllowEditing = False columnExpression = [Attendance] [Score]

GroupExpression の実装 c1FlexGrid1Cols(Score)GroupExpression = =Average([Score]) c1FlexGrid1Cols(Attendance)GroupExpression = =Average([Attendance]) c1FlexGrid1Cols(Qualified)GroupExpression = =iif(Average([Score][Attendance])lt5000falsetrue) c1FlexGrid1AutoSizeCols()End Sub

FlexGrid for WinForms

159 Copyright copy GrapeCity Inc All rights reserved

ツリーグリッド

OverviewOne of the unique and popular features of the FlexGrid control is the ability to add hierarchical grouping to regulardata grid and display it in a tree like structure called Tree Grid The Tree Grid control is very similar to the one you seein a TreeView control It shows an indented structure with collapse or expand icon next to each node row so the usercan expand and collapse the outline to see the desired level of detail by clicking on the nodes

Although you can create simple outline trees using FlexGrid grouping Tree Grid helps you implement more advanceduse cases such as displaying customer and order details In a usual grid showing such data it is difficult to see thedetails of each customer and order In such case you can create a Tree Grid to group the data in a hierarchicalstructure for better view and accessibility of information

Quick BindingLoading data in a Tree Grid is exactly the same as loading in a regular grid If the data source is available at designtime you can use the Visual Studio Property Window to set the grids DataSource property of the C1FlexGrid class andbind the grid to the data without writing even a single line of code For detailed steps see Bound Mode

You can also set the DataSource property through code Following code shows how to use the DataSource propertyto populate data in the WinForms Tree Grid

private void Bound_Node_Load(object sender EventArgs e) FlexGridを連結します BindGrid(_gridBound)

public void BindGrid(C1FlexGrid grid) DataTable _dt = new DataTable() データを取得します var fields = Country City SalesPerson Quantity ExtendedPrice var sql = stringFormat(SELECT 0 FROM Invoices ORDER BY 0 fields)

C

FlexGrid for WinForms

160 Copyright copy GrapeCity Inc All rights reserved

The code uses an OleDbDataAdapter to fill a DataTable with data then assigns datatable to DataSource property ofthe grid To turn this regular grid in a Tree grid you need to insert the node rows which is discussed in the sectionbelow

Create Nodes (Bound and Unbound Mode)To create a Tree Grid FlexGrid introduces a concept of Node rows These rows do not contain regular data and aresimply header rows under which similar data is grouped just like nodes in a usual TreeView control You can alsodefine the hierarchy of these nodes by setting the Level property These nodes can be collapsed and expanded to hideor show the data they contain The Tree Grid can be displayed in any column defined by the GridTreeColumnproperty By default this property is set to -1 which causes the tree not to be displayed at all

Bound Mode (Using InsertNode Method)

You can create node rows using InsertNode method of the RowCollection class which inserts a new node row at a

var da = new OleDbDataAdapter(sql GetConnectionString()) daFill(_dt) グリッドにデータを連結します gridDataSource = _dt ExtendedPrice 列を書式設定します gridCols[ExtendedPrice]Format = n2

static string GetConnectionString() string path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) + ComponentOne SamplesCommon string conn = provider=microsoftjetoledb40data source=0c1nwindmdb return stringFormat(conn path)

Private Sub Bound_Node_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを連結します BindGrid(_gridBound) End Sub

Public Sub BindGrid(ByVal grid As C1FlexGrid) Dim _dt As DataTable = New DataTable() データを取得します Dim fields = Country City SalesPerson Quantity ExtendedPrice Dim sql = StringFormat(SELECT 0 FROM Invoices ORDER BY 0 fields) Dim da = New OleDbDataAdapter(sql GetConnectionString()) daFill(_dt) グリッドにデータを連結します gridDataSource = _dt ExtendedPrice 列を書式設定します gridCols(ExtendedPrice)Format = n2 End Sub

Private Shared Function GetConnectionString() As String Dim path As String = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) amp ComponentOne SamplesCommon Dim conn As String = provider=microsoftjetoledb40data source=0c1nwindmdb Return StringFormat(conn path) End Function

VBNET

FlexGrid for WinForms

161 Copyright copy GrapeCity Inc All rights reserved

specified index This is the low-level way of inserting totals and building outlines

The GroupBy method used here inserts node rows by grouping identical values To obtain a Node object you caneither use return value of the InsertNode method or retrieve the node for an existing row using the IsNode property

Use the following code to create nodes using InsertNode method in the bound WinForms Tree Grid

private void Bound_Node_Load(object sender EventArgs e) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) GroupBy(_gridBound Country 0) GroupBy(_gridBound City 1) public void CreateTree(C1FlexGrid grid) gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)

void GroupBy(C1FlexGrid grid string columnName int level) レベル0でグループのスタイル設定します CellStyle s0 = gridStylesAdd(Group0) s0BackColor = ColorGray s0ForeColor = ColorWhite s0Font = new Font(gridFont FontStyleBold) レベル1でグループのスタイル設定します CellStyle s1 = gridStylesAdd(Group1) s1BackColor = ColorLightGray s1ForeColor = ColorBlack object current = null for (int r = gridRowsFixed r lt gridRowsCount r++)

C

FlexGrid for WinForms

162 Copyright copy GrapeCity Inc All rights reserved

if (gridRows[r]IsNode) var value = grid[r columnName] if (objectEquals(value current)) 値が変更されました ノードを挿入します gridRowsInsertNode(r level) if (level == 0) gridRows[r]Style = s0 else if (level == 1) gridRows[r]Style = s1 最初のスクロール可能な列にグループ名を表示します grid[r gridColsFixed] = value 現在の値を更新します current = value gridAutoSizeCols()

Private Sub Bound_Node_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) GroupBy(_gridBound Country 0) GroupBy(_gridBound City 1)End Sub

Public Sub CreateTree(ByVal grid As C1FlexGrid) gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)End Sub

Private Sub GroupBy(ByVal grid As C1FlexGrid ByVal columnName As String ByVal level As Integer) レベル0でグループのスタイル設定します Dim s0 As CellStyle = gridStylesAdd(Group0) s0BackColor = ColorGray s0ForeColor = ColorWhite s0Font = New Font(gridFont FontStyleBold) レベル1でグループのスタイル設定します Dim s1 As CellStyle = gridStylesAdd(Group1) s1BackColor = ColorLightGray s1ForeColor = ColorBlack Dim current As Object = Nothing Dim r As Integer = gridRowsFixed

While r And lt gridRowsCount End While

r += 1

If True Then

If Not gridRows(r)IsNode Then Dim value = grid(r columnName)

VBNET

FlexGrid for WinForms

163 Copyright copy GrapeCity Inc All rights reserved

The code also calls the AutoSizeCols method to ensure that the column is wide enough to accommodate the TreeGrid Finally it calls the GridTreeShow method to display the nodes

Also the Node class provides following methods and properties based on TreeView object model which can be usedto manage the Tree Grid

Checked Gets or sets the check state of cell defined by NodeRow and GridTreeColumnCollapsedExpanded Gets or sets collapsed or expanded state of the nodeData Gets or sets value in the cell defined by NodeRow and GridTreeColumnImage Gets or sets image in the cell defined by NodeRow and GridTreeColumnLevel Gets or sets node level in the Tree Grid

You can also explore the outline structure using the following properties and methods

Children Gets number of child nodes under this nodeGetCellRange Gets the CellRange object that described range of rows that belong to this nodeGetNode Gets the node that has a given relationship to this node (parent first child next sibling and so on)Nodes Gets a node array containing child nodes of this node

Bound Mode (Using Subtotal Method)

In bound mode another way to create nodes is using the Subtotal method To make the Tree Grid really useful thenode rows must include summary information for the data they contain

If you create Tree Grid using the Subtotal method the subtotals are added automatically The method scans theentire grid and automatically inserts node rows with optional subtotals at locations where the grid data changes

This is the high-level way of inserting totals and building outlines

If Not ObjectEquals(value current) Then 値が変更されました ノードを挿入します gridRowsInsertNode(r level)

If level = 0 Then gridRows(r)Style = s0 ElseIf level = 1 Then gridRows(r)Style = s1 End If

最初のスクロール可能な列にグループ名を表示します grid(r gridColsFixed) = value 現在の値を更新します current = value End If End IfEnd If gridAutoSizeCols()End Sub

FlexGrid for WinForms

164 Copyright copy GrapeCity Inc All rights reserved

The first parameter of the Subtotal method is AggregateEnum enumeration which calculates various types ofaggregates like Sum Average Count Max Min and others In the code below Subtotal method of the C1FlexGridclass is used for creating nodes in a bound WinForms Tree Grid

private void SubtotalNode_Bound_Load(object sender EventArgs e) FlexGridを取得します BindGrid(_gridBound) shows Tree in Bound FlexGrid CreateTree(_gridBound) 連結されたFlexGridに小計を作成します CreateSubTotal(_gridBound)public void BindGrid(C1FlexGrid grid) DataTable dt = new DataTable() dtColumnsAdd(ID typeof(int)) dtColumnsAdd(Name typeof(string)) dtColumnsAdd(Course typeof(string)) dtColumnsAdd(Score typeof(int)) dtColumnsAdd(Attendance typeof(int)) dtColumnsAdd(Country typeof(string)) サンプルデータ dtRowsAdd(1 Helen Bennett ComputerScience 79 84 Spain) dtRowsAdd(2 Ana Trujillo Biology 78 87 Mexico) dtRowsAdd(3 Antonio Moreno Aeronautics 71 70 Spain) dtRowsAdd(4 Paolo Accorti Biology 74 63 Spain) dtRowsAdd(5 Elizabeth Brown ComputerScience 80 93 Mexico) dtRowsAdd(6 Jaime Yorres Biology 61 48 Spain) dtRowsAdd(7 Yvonne Moncada Aeronautics 85 78 Mexico) dtRowsAdd(8 Martine Ranceacute Aeronautics 67 81 Spain) dtRowsAdd(9 Sergio Gutieacuterrezy ComputerScience 62 58 Mexico) dtRowsAdd(10 Thomas Hardy Aeronautics 94 92 Mexico) dtRowsAdd(11 Patricio Simpson Aeronautics 46 52 Spain) dtRowsAdd(12 Maria Anders ComputerScience 85 73 Spain) gridDataSource = dt gridAutoSizeCols() (gridDataSource as DataTable)DefaultViewSort = Course

C

FlexGrid for WinForms

165 Copyright copy GrapeCity Inc All rights reserved

FlexGridでツリーを作成しますpublic void CreateTree(C1FlexGrid grid) gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1) gridAutoSizeCols()public void CreateSubTotal(C1FlexGrid grid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加します gridSubtotal(AggregateEnumAverage 1 3 3 4 Average for 0) gridAutoSizeCols()

Private Sub SubtotalNode_Bound_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) Creates Subtotal(s) in Bound FlexGrid CreateSubTotal(_gridBound)End Sub

Public Sub BindGrid(ByVal grid As C1FlexGrid) Dim dt As DataTable = New DataTable() dtColumnsAdd(ID GetType(Integer)) dtColumnsAdd(Name GetType(String)) dtColumnsAdd(Course GetType(String)) dtColumnsAdd(Score GetType(Integer)) dtColumnsAdd(Attendance GetType(Integer)) dtColumnsAdd(Country GetType(String))

サンプルデータ dtRowsAdd(1 Helen Bennett ComputerScience 79 84 Spain) dtRowsAdd(2 Ana Trujillo Biology 78 87 Mexico) dtRowsAdd(3 Antonio Moreno Aeronautics 71 70 Spain) dtRowsAdd(4 Paolo Accorti Biology 74 63 Spain) dtRowsAdd(5 Elizabeth Brown ComputerScience 80 93 Mexico) dtRowsAdd(6 Jaime Yorres Biology 61 48 Spain) dtRowsAdd(7 Yvonne Moncada Aeronautics 85 78 Mexico) dtRowsAdd(8 Martine Ranceacute Aeronautics 67 81 Spain) dtRowsAdd(9 Sergio Gutieacuterrezy ComputerScience 62 58 Mexico) dtRowsAdd(10 Thomas Hardy Aeronautics 94 92 Mexico) dtRowsAdd(11 Patricio Simpson Aeronautics 46 52 Spain) dtRowsAdd(12 Maria Anders ComputerScience 85 73 Spain) gridDataSource = dt gridAutoSizeCols() TryCast(gridDataSource DataTable)DefaultViewSort = CourseEnd Sub

FlexGridでツリーを作成しますPublic Sub CreateTree(ByVal grid As C1FlexGrid) gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)

VBNET

FlexGrid for WinForms

166 Copyright copy GrapeCity Inc All rights reserved

Unbound Mode (Using Subtotal Method)

The Subtotal method is a very convenient and flexible way to create a tree grid It has a number of overloads thatallow you to specify which columns are to be grouped on and totaled on by index or by name whether to include acaption in the node rows that it inserts how to perform the grouping and so on

In the code below Subtotal method of the C1FlexGrid class is used for creating nodes in an unbound WinForms TreeGrid

gridAutoSizeCols()End Sub

Public Sub CreateSubTotal(ByVal grid As C1FlexGrid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加します gridSubtotal(AggregateEnumAverage 1 3 3 4 Average for 0) gridAutoSizeCols()End Sub

private void Unbound_Subtotal_Load(object sender EventArgs e) 連結されていないFlexGridにデータを追加します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) 連結されていないFlexGridに小計を作成します CreateSubTotal(_gridUnbound) public void PopulateGrid(C1FlexGrid grid) グリッドにデータを入力します Random rnd = new Random() gridRowsCount = 14 grid[0 1] = Direction grid[0 2] = Region CellRange rg = gridGetCellRange(0 3 0 gridColsCount - 1) rgData = Rnd

C

FlexGrid for WinForms

167 Copyright copy GrapeCity Inc All rights reserved

for (int r = 1 r lt gridRowsCount r++) grid[r 0] = r grid[r 1] = (r lt 7) Inbound Outbound grid[r 2] = (r lt 3) North (r lt 7) South (r lt 10) East West for (int c = 3 c lt gridColsCount c++) grid[r c] = rndNext(1000) gridCols[c]Format = gridAutoSizeCols()

FlexGridでツリーを作成しますprivate void ShowTreeNode(C1FlexGrid grid) ツリーを作成します gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols()

Creates Subtotal in FlexGridpublic void CreateSubTotal(C1FlexGrid grid) Clears any existing subtotal(s) present in grid gridSubtotal(AggregateEnumClear) for (int c = 3 c lt gridColsCount c++) Adds subtotals in grid gridSubtotal(AggregateEnumSum 0 -1 c Grand Total) gridSubtotal(AggregateEnumSum 2 2 c Total for 0) gridAutoSizeCols()

Private Sub Unbound_Subtotal_Load(ByVal sender As Object ByVal e As EventArgs) 連結されていないFlexGridにデータを追加します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) 連結されていないFlexGridに小計を作成します CreateSubTotal(_gridUnbound) End Sub

Public Sub PopulateGrid(ByVal grid As C1FlexGrid) グリッドにデータを入力します Dim rnd As Random = New Random() gridRowsCount = 14 grid(0 1) = Direction grid(0 2) = Region Dim rg As CellRange = gridGetCellRange(0 3 0 gridColsCount - 1) rgData = Rnd Dim r As Integer = 1

While r And lt gridRowsCount End While

VBNET

FlexGrid for WinForms

168 Copyright copy GrapeCity Inc All rights reserved

r += 1

If True Then grid(r 0) = r grid(r 1) = r And lt 7 Inbound Outbound grid(r 2) = r And lt 3 North r And lt 7 South r And lt 10 East West Dim c As Integer = 3

While c And lt gridColsCount End While

c += 1

If True Then grid(r c) = rnd[Next](1000) gridCols(c)Format = End If End If

gridAutoSizeCols() End Sub

FlexGridでツリーを作成します Private Sub ShowTreeNode(ByVal grid As C1FlexGrid) ツリーを作成しますFlexGridでツリーを作成します gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols() End Sub

FlexGridで小計を作成します Public Sub CreateSubTotal(ByVal grid As C1FlexGrid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) Dim c As Integer = 3

While c And lt gridColsCount End While

c += 1

If True Then グリッドに小計を追加します gridSubtotal(AggregateEnumSum 0 -1 c Grand Total) gridSubtotal(AggregateEnumSum 2 2 c Total for 0) End If

gridAutoSizeCols() End Sub

FlexGrid for WinForms

169 Copyright copy GrapeCity Inc All rights reserved

Unbound Mode(Using IsNode Property)

In an unbound grid you can turn regular rows into node rows by simply setting the IsNode property to true If youtry to turn a regular data bound row into a node it causes the grid to throw an exception

Use the following code to create nodes using IsNode property in an unbound WinForms Tree Grid

private void Unbound_Row_Load(object sender EventArgs e) 連結されていないFlexGridにデータを入力します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound)

private void PopulateGrid(C1FlexGrid grid) FlexGridをリセットします gridRowsCount = 0 gridColsCount = 2 string fileName = testxml xmlドキュメントをロードします XmlDocument xdoc = new XmlDocument() xdocLoad(fileName) XMLドキュメントを読み取りFlexGridのノードとして表示します ShowNode(_gridUnbound xdocChildNodes[1] 0) gridAutoSizeCols() FlexGridでツリーを作成しますprivate void ShowTreeNode(C1FlexGrid grid) ツリーを作成します gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols()

FlexGridにxmlノードを追加しますprivate void ShowNode(C1FlexGrid grid XmlNode node int level)

C

FlexGrid for WinForms

170 Copyright copy GrapeCity Inc All rights reserved

コメントノードをスキップします if (nodeNodeType == XmlNodeTypeComment) return 読み取りxmlノードの新しい行を追加します int row = gridRowsCount gridRowsAdd() グリッドのセルにxmlノードデータを割り当てます grid[row 0] = nodeName xmlノードに子が1つしかないかどうかを確認します if (nodeChildNodesCount == 1) グリッドのセルにノード値を設定します grid[row 1] = nodeInnerText 新しい行をノードにします gridRows[row]IsNode = true gridRows[row]NodeLevel = level ノードに子がある場合はそれらも取得します if (nodeChildNodesCount gt 1) 子を取得するために再帰します foreach (XmlNode child in nodeChildNodes) ShowNode(_gridUnbound child level + 1)

Private Sub Unbound_Row_Load(ByVal sender As Object ByVal e As EventArgs) 連結されていないFlexGridにデータを入力します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) End Sub

Private Sub PopulateGrid(ByVal grid As C1FlexGrid) FlexGridをリセットします gridRowsCount = 0 gridColsCount = 2 Dim fileName As String = testxml xmlドキュメントをロードします Dim xdoc As XmlDocument = New XmlDocument() xdocLoad(fileName) XMLドキュメントを読み取りFlexGridのノードとして表示します ShowNode(_gridUnbound xdocChildNodes(1) 0) gridAutoSizeCols() End Sub

FlexGridでツリーを作成します Private Sub ShowTreeNode(ByVal grid As C1FlexGrid) ツリーを作成します gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols() End Sub

FlexGridにxmlノードを追加します Private Sub ShowNode(ByVal grid As C1FlexGrid ByVal node As XmlNode ByVal level As Integer) コメントノードをスキップします If nodeNodeType Is XmlNodeTypeComment Then Return

VBNET

FlexGrid for WinForms

171 Copyright copy GrapeCity Inc All rights reserved

読み取りxmlノードの新しい行を追加します Dim row As Integer = gridRowsCount gridRowsAdd() グリッドのセルにxmlノードデータを割り当てます grid(row 0) = nodeName

xmlノードに子が1つしかないかどうかを確認します If nodeChildNodesCount = 1 Then グリッドのセルにノード値を設定します grid(row 1) = nodeInnerText End If

新しい行をノードにします gridRows(row)IsNode = True gridRows(row)NodeLevel = level

ノードに子がある場合はそれらも取得します If nodeChildNodesCount And gt Then End If

1

If True Then

子を取得するために再帰します For Each child As XmlNode In nodeChildNodes ShowNode(_gridUnbound child level + 1) Next End If End Sub

ノードの操作

Tree Grid not only allows you to present the data in a structured form but it also supports performing variousoperations with the nodes You can add delete move and fetch nodes by using various methods provided bythe Node class

FlexGrid for WinForms

172 Copyright copy GrapeCity Inc All rights reserved

Add NodeYou can add a node at a specific position in the Tree Grid using AddNode method of the Node class This appends anew node row to the collection The method takes NodeTypeEnum enumeration as its argument which lets youspecify a node with respect to another given node

The code below shows how to add a node in the WinForms Tree Grid at a specific location

private void cmbAdd_SelectionChangeCommitted(object sender SystemEventArgs e) 現在の行ノードを取得します Node nd = flexRows[flexRow]Node ユーザーの要求に応じて相対を追加します (could be a child or a sibling) ndAddNode((NodeTypeEnum)(cmbAddSelectedIndex + 2) cmbAddText) flexFocus()

C

Private Sub cmbAdd_SelectionChangeCommitted(ByVal sender As Object ByVal e As EventArgs) 現在の行ノードを取得します Dim nd As Node = flexRows(flexRow)Node ユーザーの要求に応じて相対を追加します (could be a child or a sibling) ndAddNode(CType(cmbAddSelectedIndex + 2 NodeTypeEnum) cmbAddText)

VBNET

FlexGrid for WinForms

173 Copyright copy GrapeCity Inc All rights reserved

Delete NodeYou can delete a selected node from the Tree Grid using RemoveNode method of the Node class

Following code demonstrates how to delete a node from the WinForms Tree Grid

Move NodeThe Tree Grid allows you to move the node rows to a new position using Move method of the Node class Themethod takes NodeMoveEnum enumeration as an argument which lets you specify the direction in which node hasto be moved

Use the code below to move a node of the WinForms Tree Grid to a new position

flexFocus()End Sub

private void btnDelete_Click(object sender SystemEventArgs e) 現在のノードを取得します Node nd = null if ( flexRowsCount gt 0 ampamp flexRow gt= 0 ampamp flexRow lt flexRowsCount) nd = flexRows[flexRow]Node if (nd = null) FlexGridからノードを削除します ndRemoveNode() flexFocus()

C

Private Sub btnDelete_Click(ByVal sender As Object ByVal e As EventArgs) 現在のノードを取得します Dim nd As Node = Nothing

If flexRowsCount gt 0 AndAlso flexRow gt= 0 AndAlso flexRow lt flexRowsCount Then nd = flexRows(flexRow)Node End If

If nd IsNot Nothing Then FlexGridからノードを削除します ndRemoveNode() flexFocus() End IfEnd Sub

VBNET

private void btnMove_Click(object sender SystemEventArgs e) 現在の行のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択した動きを適用します

C

FlexGrid for WinForms

174 Copyright copy GrapeCity Inc All rights reserved

Select NodesIn Tree Grid you can select the nodes to perform different operations using GetNode method of the Node class Themethod takes a parameter called NodeTypeEnum enumeration which specifies a node with respect to another givennode

The code below specifies how to fetch a specific node of the WinForms Tree Grid and show it in selected state

(これにより選択したノードが移動します) if (sender == btnMoveOut) ndMove(NodeMoveEnumOut) else if (sender == btnMoveIn) ndMove(NodeMoveEnumIn) else if (sender == btnMoveUp) ndMove(NodeMoveEnumUp) else if (sender == btnMoveDown) ndMove(NodeMoveEnumDown) else if (sender == btnMoveFirst) ndMove(NodeMoveEnumFirst) else if (sender == btnMoveLast) ndMove(NodeMoveEnumLast) ノードがまだ表示されていることを確認します ndEnsureVisible() flexFocus()

Private Sub btnMove_Click(ByVal sender As Object ByVal e As EventArgs) 現在の行のノードを取得します Dim nd As Node = flexRows(flexRow)Node

ユーザーが選択した動きを適用します (これにより選択したノードが移動します) If sender Is btnMoveOut Then ndMove(NodeMoveEnumOut) ElseIf sender Is btnMoveIn Then ndMove(NodeMoveEnum[In]) ElseIf sender Is btnMoveUp Then ndMove(NodeMoveEnumUp) ElseIf sender Is btnMoveDown Then ndMove(NodeMoveEnumDown) ElseIf sender Is btnMoveFirst Then ndMove(NodeMoveEnumFirst) ElseIf sender Is btnMoveLast Then ndMove(NodeMoveEnumLast) End If

ノードがまだ表示されていることを確認します ndEnsureVisible() flexFocus()End Sub

VBNET

private void cmbSelect_SelectionChangeCommitted(object sender SystemEventArgs e) 現在の行のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択したノードを取得します nd = ndGetNode((NodeTypeEnum)cmbSelectSelectedIndex) 失敗した場合はメッセージを表示します if (nd == null) MessageBoxShow(Cant find + cmbSelectText + for this node) return ノードを選択しそれが表示されていることを確認します(スクロールして表示します)

C

FlexGrid for WinForms

175 Copyright copy GrapeCity Inc All rights reserved

Expand and Collapse NodesYou can expand and collapse all nodes in your Tree Grid application using the Collapsed property of Node class asshown in the code below This feature makes it convenient to navigate through node headers as a group whenrequired

Following code shows how to expand and collapse nodes of the WinForms Tree Grid

ndSelect() ndEnsureVisible() flexFocus()

Private Sub cmbSelect_SelectionChangeCommitted(ByVal sender As Object ByVal e As EventArgs) 現在の行のノードを取得します Dim nd As Node = flexRows(flexRow)Node ユーザーが選択したノードを取得します nd = ndGetNode(CType(cmbSelectSelectedIndex NodeTypeEnum))

失敗した場合はメッセージを表示します If nd Is Nothing Then MessageBoxShow(Cant find amp cmbSelectText amp for this node) Return End If

ノードを選択しそれが表示されていることを確認します(スクロールして表示します) nd[Select]() ndEnsureVisible() flexFocus()End Sub

VBNET

foreach (Row row in flexRowsCastltRowgt()Where(rw =gt rwIsNode == true)) Node node = rowNode nodeCollapsed = false

foreach (Row row in flexRowsCastltRowgt()Where(rw =gt rwIsNode == true)) Node node = rowNode nodeCollapsed = true

C

For Each row As Row In flexRowsCast(Of Row)()Where(Function(rw) rwIsNode = True) Dim node As Node = rowNode nodeCollapsed = False Next

For Each row As Row In flexRowsCast(Of Row)()Where(Function(rw) rwIsNode = True) Dim node As Node = rowNode nodeCollapsed = True Next

VBNET

FlexGrid for WinForms

176 Copyright copy GrapeCity Inc All rights reserved

Drag and Drop NodesIn Tree Grid you can drag and drop a selected node to a specific position by handling the MouseUp MouseDownand MouseMove events

The code below lets the user drag and drop nodes of the WinForms Tree Grid

private void flex_MouseDown(object sender MouseEventArgs e) m_DragInfocheckDrag = false 左ボタンを押すと移動しません ドラッグするマウスの追跡を開始します if (eButton = MouseButtonsLeft) return if (chkDragChecked || m_DragInfodragging) return if (flexMouseRow lt flexRowsFixed || flexMouseCol = 0) return 現在の行とマウスの位置を保存します m_DragInforow = flexRow m_DragInfomouseDown = new Point(eX eY) チェックを開始します m_DragInfocheckDrag = true

private void flex_MouseMove(object sender MouseEventArgs e) チェックしてユーザーが許容範囲を超えた場合はドラッグを開始します if (m_DragInfocheckDrag || eButton = MouseButtonsLeft) return if (MathAbs(eX - m_DragInfomouseDownX) + MathAbs(eY - m_DragInfomouseDownY) lt= DRAGTOL) return フラグを更新します m_DragInfodragging = true Sets cursor and highlight node CellStyle cs = flexStyles[SourceNode] flexCursor = CursorsNoMove2D flexSetCellStyle(m_DragInforow 0 cs) ここにドロップできるかどうかを確認します Cursor c = (NoDropHere()) CursorsNo CursorsNoMove2D if (c = flexCursor) flexCursor = c private bool NoDropHere() カーソルの下の行は無効です if (flexMouseRow lt flexRowsFixed) return true カーソルの下の列が無効です if (flexMouseCol lt flexColsFixed) return true if (flexGetDataDisplay(flexRow 0) == SKU) return true return false private void flex_MouseUp(object sender MouseEventArgs e) マウスが再び下がるまでチェックしないでください m_DragInfocheckDrag = false Not dragging were done if (m_DragInfodragging) return ドラッグを停止します m_DragInfodragging = false flexSetCellStyle(m_DragInforow 0 (CellStyle)null) flexCursor = CursorsDefault ドロップが許可されているかどうかをテストします

C

FlexGrid for WinForms

177 Copyright copy GrapeCity Inc All rights reserved

if (NoDropHere()) return ノードを新しい親ノードに移動します Node ndSrc = flexRows[m_DragInforow]Node Node ndDst = flexRows[flexRow]Node ndSrcMove(NodeMoveEnumChildOf ndDst) ndSrcSelect()

internal struct DRAGINFO public bool dragging 現在ドラッグ中 public bool checkDrag 現在マウスをチェックしてドラッグを開始しています public int row ドラッグされている行のインデックス public Point mouseDown マウスダウンの位置

Private Sub flex_MouseDown(ByVal sender As Object ByVal e As MouseEventArgs) m_DragInfocheckDrag = False 左ボタンを押すと移動しません ドラッグするマウスの追跡を開始します If eButton IsNot MouseButtonsLeft Then Return If Not chkDragChecked OrElse m_DragInfodragging Then Return If flexMouseRow lt flexRowsFixed OrElse flexMouseCol ltgt 0 Then Return 現在の行とマウスの位置を保存します m_DragInforow = flexRow m_DragInfomouseDown = New Point(eX eY) チェックを開始します m_DragInfocheckDrag = True End Sub

Private Sub flex_MouseMove(ByVal sender As Object ByVal e As MouseEventArgs) チェックしてユーザーが許容範囲を超えた場合はドラッグを開始します If Not m_DragInfocheckDrag OrElse eButton IsNot MouseButtonsLeft Then Return If MathAbs(eX - m_DragInfomouseDownX) + MathAbs(eY - m_DragInfomouseDownY) lt= DRAGTOL Then Return フラグを更新します m_DragInfodragging = True カーソルを設定しノードを強調表示します Dim cs As CellStyle = flexStyles(SourceNode) flexCursor = CursorsNoMove2D flexSetCellStyle(m_DragInforow 0 cs) ここにドロップできるかどうかを確認します Dim c As Cursor = If((NoDropHere()) CursorsNo CursorsNoMove2D) If c IsNot flexCursor Then flexCursor = c End Sub

Private Function NoDropHere() As Boolean カーソルの下の行は無効です If flexMouseRow lt flexRowsFixed Then Return True カーソルの下の列が無効です If flexMouseCol lt flexColsFixed Then Return True If flexGetDataDisplay(flexRow 0) Is SKU Then Return True Return False End Function

Private Sub flex_MouseUp(ByVal sender As Object ByVal e As MouseEventArgs) マウスが再び下がるまでチェックしないでください m_DragInfocheckDrag = False If Not m_DragInfodragging Then Return ドラッグを停止します m_DragInfodragging = False

VBNET

FlexGrid for WinForms

178 Copyright copy GrapeCity Inc All rights reserved

flexSetCellStyle(m_DragInforow 0 CType(Nothing CellStyle)) flexCursor = Cursors[Default] ドロップが許可されているかどうかをテストします If NoDropHere() Then Return ノードを新しい親ノードに移動します Dim ndSrc As Node = flexRows(m_DragInforow)Node Dim ndDst As Node = flexRows(flexRow)Node ndSrcMove(NodeMoveEnumChildOf ndDst) ndSrc[Select]() End Sub

Friend Structure DRAGINFO Public dragging As Boolean 現在ドラッグ中 Public checkDrag As Boolean 現在マウスをチェックしてドラッグを開始しています Public row As Integer ドラッグされている行のインデックス Public mouseDown As Point マウスダウンの位置 End Structure

データの操作

In Tree Grid just like a usual grid you can also perform various operations at data level such as sorting and retainingthe changes

SortingTo apply sorting in Tree Grid you can select the parent node and sort the child nodes using Sort Method of the NodeClass You can specify the sorting order by using the SortFlags enumeration

Following code applies sorting on the WinForms Tree Grid

FlexGrid for WinForms

179 Copyright copy GrapeCity Inc All rights reserved

Retain the ChangesSo far we have discussed how to create trees and totals using the high-level Subtotal method as well as lower-level InsertNode and Aggregate methods

At this point it is important to remember that the Tree Grid is created based on the data but is not bound to it in anyway and is not automatically maintained when there are changes to the grid or to the data

For example if the user modifies a value in the column the subtotals will not be automatically updated If the usersorts the grid it refreshes the data and the subtotals disappear

There are two common ways to maintain the Tree Grid

1 Prevent the user from making any changes that would invalidate the tree This is the easiest option You can setthe grids AllowEditing AllowDragging and AllowSorting properties to false and prevent any changes thatwould affect the tree

2 Update the tree when there are changes to the data or to the grid You can attach handlers to thegrids AfterDataRefresh AfterSort and AfterEdit events and re-generate the outline appropriately

The second option is usually more interesting as it provides a quick and simple tool for dynamic data analysis Thisapproach is illustrated by a product sample Analyze shipped with the FlexGrid control The sample creates an initialoutline and allows users to reorder the columns When the column order changes the sample automatically re-sortsthe data and re-creates the outline

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing

private void btnSort_Click(object sender SystemEventArgs e) 現在のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択した並べ替えを適用します (これにより選択したノードの子が並べ替えられます) if (sender == btnSortAscending) ndSort(SortFlagsAscending) else ndSort(SortFlagsDescending) 完了 flexFocus()

C

Private Sub btnSort_Click(ByVal sender As Object ByVal e As EventArgs) 現在のノードを取得します Dim nd As Node = flexRows(flexRow)Node

ユーザーが選択した並べ替えを適用します (これにより選択したノードの子が並べ替えられます) If sender Is btnSortAscending Then ndSort(SortFlagsAscending) Else ndSort(SortFlagsDescending) End If

完了 flexFocus()End Sub

VBNET

FlexGrid for WinForms

180 Copyright copy GrapeCity Inc All rights reserved

WinForms Edition using ComponentOneControlPanelexe

In Create Nodes section we also learnt about implementing GroupBy method that inserts node rows groupingidentical values on a given column The code scans all the columns skipping existing node rows so it can be called toadd several levels of nodes and keeps track of the current value for the column being grouped on When the currentvalue changes a node row is inserted showing the new group name in the first scrollable column

However there are some challenges to maintain the grouping like the method assumes that data is sorted accordingto the outline structure Also the GroupBy method may insert rows which would cause the grid to flicker To avoidthis you would normally set the Redraw property to false before making the updates and set it back to true whendone

The DeferRefresh class is a simple utility that sets the grids Redraw property to false and restores its original valuewhen it is disposed This ensures that Redraw is properly restored even when exceptions happen during the updatesThe BindGrid method ensures that the grid is sorted in the order required by our outline structure

ツリーグリッドのカスタマイズ

FlexGrid allows you to customize Tree Grid by styling as well as by using various elements like checkboxes toexpandcollapse nodes or images as node icons A customized Tree Grid can make the outline tree nodes look moredistinctive and structured making it visually appealing and more understandable

Style Tree GridStyling a Tree Grid is similar to styling the FlexGrid control The Tree property returns a reference to a GridTree objectthat exposes several methods and properties used to customize the Tree Grid Following is the list of some commonlyused properties

Column Gets or sets the index of the column that contains the outline tree Setting this property to -1 causesthe outline tree to be hidden from the usersIndent Gets or sets the indent in pixels between adjacent node levels Higher indent levels cause the tree tobecome widerStyle Gets or sets the type of outline tree to display Use this property to determine whether the tree shouldinclude a button bar at the top to allow users to collapseexpand the entire tree whether lines andor symbolsshould be displayed and whether lines should be displayed connecting the tree to data rows as well as noderowsLineColor Gets or sets the color of the connecting linesLineStyle Gets or sets the style of the connecting lines

For more information on styling the tree grid see Styling and Appearance topic in FlexGrid documentation

Display Tree with CheckBoxesTo create a custom Tree Grid with checkbox and images you need to first initialize FlexGrid for creating Tree Grid andthen add nodes to the tree by using AddNode method of the RowCollection class

Now to implement checkboxes in Tree Grid you need to maintain the checkboxes in parent and child nodes Thismethod uses Checked property of the Node class which defines whether to show a checkbox for the node or not

FlexGrid for WinForms

181 Copyright copy GrapeCity Inc All rights reserved

The code below shows how to display checkboxes on tree nodes of the WinForms Tree Grid

void c1FlexGrid1_CellChecked(object sender C1WinC1FlexGridRowColEventArgs e) すべての子にチェック値を適用します var node = thisc1FlexGrid1Rows[eRow]Node UpdateCheckChildren(node) 親にチェック値を適用します UpdateCheckParent(node)

void UpdateCheckChildren(C1WinC1FlexGridNode node) var checkState = nodeChecked foreach (C1WinC1FlexGridNode child in nodeNodes) childChecked = checkState UpdateCheckChildren(child)

void UpdateCheckParent(C1WinC1FlexGridNode node) このノードの親を取得します var parent = nodeParent if (parent = null)

C

FlexGrid for WinForms

182 Copyright copy GrapeCity Inc All rights reserved

チェックされたチェックされていない子をカウントします int cntChecked = 0 int cntUnchecked = 0 int cntGrayed = 0 foreach (C1WinC1FlexGridNode child in parentNodes) switch (childChecked) case C1WinC1FlexGridCheckEnumChecked cntChecked++ break case C1WinC1FlexGridCheckEnumUnchecked cntUnchecked++ break case C1WinC1FlexGridCheckEnumGrayed cntGrayed++ break 親のチェック状態を更新します if (cntGrayed gt 0 || (cntChecked gt 0 ampamp cntUnchecked gt 0)) parentChecked = C1WinC1FlexGridCheckEnumGrayed else if (cntChecked gt 0 ampamp cntUnchecked == 0) parentChecked = C1WinC1FlexGridCheckEnumChecked else if (cntUnchecked gt 0 ampamp cntChecked == 0) parentChecked = C1WinC1FlexGridCheckEnumUnchecked 祖父も更新します UpdateCheckParent(parent)

Private Sub c1FlexGrid1_CellChecked(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) すべての子にチェック値を適用します Dim node = Mec1FlexGrid1Rows(eRow)Node UpdateCheckChildren(node) 親にチェック値を適用します UpdateCheckParent(node) End Sub

Private Sub UpdateCheckChildren(ByVal node As C1WinC1FlexGridNode) Dim checkState = nodeChecked

For Each child As C1WinC1FlexGridNode In nodeNodes childChecked = checkState MeUpdateCheckChildren(child) Next End Sub

Private Sub UpdateCheckParent(ByVal node As C1WinC1FlexGridNode) このノードの親を取得します Dim parent = nodeParent

If parent IsNot Nothing Then チェックされたチェックされていない子をカウントします

VBNET

FlexGrid for WinForms

183 Copyright copy GrapeCity Inc All rights reserved

Display Tree with ImagesTo add the images as your Tree Grid node icons you can use the AddImageFolder method for creating nodes relatedto files and assigning images to the nodes

Dim cntChecked As Integer = 0 Dim cntUnchecked As Integer = 0 Dim cntGrayed As Integer = 0

For Each child As C1WinC1FlexGridNode In parentNodes

Select Case childChecked Case C1WinC1FlexGridCheckEnumChecked cntChecked += 1 Case C1WinC1FlexGridCheckEnumUnchecked cntUnchecked += 1 Case C1WinC1FlexGridCheckEnumGrayed cntGrayed += 1 End Select Next

親のチェック状態を更新します If cntGrayed gt 0 OrElse cntChecked gt 0 AndAlso cntUnchecked gt 0 Then parentChecked = C1WinC1FlexGridCheckEnumGrayed ElseIf cntChecked gt 0 AndAlso cntUnchecked = 0 Then parentChecked = C1WinC1FlexGridCheckEnumChecked ElseIf cntUnchecked gt 0 AndAlso cntChecked = 0 Then parentChecked = C1WinC1FlexGridCheckEnumUnchecked End If

祖父も更新します UpdateCheckParent(parent) End If End Sub

FlexGrid for WinForms

184 Copyright copy GrapeCity Inc All rights reserved

Use the code below to display images or icons along with nodes of the WinForms Tree Grid

void AddImageFolder(string path int level) int cnt = 0 try ディレクトリ内のすべてのファイルをループします foreach (string file in DirectoryGetFiles(path)) ファイルごとにノードを作成しFlexGridに追加します var node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(file) 画像をノードに割り当てるためのコード ShowImage(node file) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt++ if (cnt gt 20) break catch try パスのすべてのサブディレクトリをループします foreach (string subPath in DirectoryGetDirectories(path))

C

FlexGrid for WinForms

185 Copyright copy GrapeCity Inc All rights reserved

ファイルごとにノードを作成しFlexGridに追加します var node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(subPath) 画像をノードに割り当てるためのコード ShowImage(node subPath) 現在のディレクトリのサブディレクトリファイルをトラバースします AddImageFolder(subPath level + 1) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt++ if (cnt gt 20) break catch

Private Sub AddImageFolder(ByVal path As String ByVal level As Integer) Dim cnt As Integer = 0

Try

ディレクトリ内のすべてのファイルをループします For Each file As String In DirectoryGetFiles(path) ファイルごとにノードを作成しFlexGridに追加します Dim node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(file)

画像をノードに割り当てるためのコード ShowImage(node file) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt += 1 If cnt gt 20 Then Exit For Next

Catch End Try

Try

パスのすべてのサブディレクトリをループします For Each subPath As String In DirectoryGetDirectories(path) ファイルごとにノードを作成しFlexGridに追加します Dim node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(subPath) 画像をノードに割り当てるためのコード ShowImage(node subPath) 現在のディレクトリのサブディレクトリファイルをトラバースします AddImageFolder(subPath level + 1) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt += 1 If cnt gt 20 Then Exit For Next

Catch End TryEnd Sub

VBNET

FlexGrid for WinForms

186 Copyright copy GrapeCity Inc All rights reserved

The above code uses a custom method called ShowImage to set the image for nodes based on its file extensions

public void ShowImage(C1WinC1FlexGridNode node string path) パスからファイル拡張子を取得します string extension = PathGetExtension(path) パスがファイルに属している場合 if (extension = ) ファイル拡張子に基づいてノードの画像を設定します switch (extension) case txt nodeImage = PropertiesResourcesTxt break case resx nodeImage = PropertiesResourcesTxt break case licx nodeImage = PropertiesResourcesTxt break case cs nodeImage = PropertiesResourcesTxt break case vb nodeImage = PropertiesResourcesTxt break case exe nodeImage = PropertiesResourcesExe break case dll nodeImage = PropertiesResourcesDll break case sln nodeImage = PropertiesResourcesVS break case csproj nodeImage = PropertiesResourcesVS break case bmp nodeImage = PropertiesResourcesImg break case png nodeImage = PropertiesResourcesImg break case gif nodeImage = PropertiesResourcesVideo break case accdb nodeImage = PropertiesResourcesAccess break default nodeImage = PropertiesResourcesUnknown break それ以外のパスはディレクトリフォルダに属しています else nodeImage = PropertiesResourcesFolder

C

FlexGrid for WinForms

187 Copyright copy GrapeCity Inc All rights reserved

Public Sub ShowImage(ByVal node As C1WinC1FlexGridNode ByVal path As String) パスからファイル拡張子を取得します Dim extension As String = PathGetExtension(path)

パスがファイルに属している場合 If Not Equals(extension ) Then

ファイル拡張子に基づいてノードの画像を設定します Select Case extension Case txt nodeImage = PropertiesResourcesTxt Case resx nodeImage = PropertiesResourcesTxt Case licx nodeImage = PropertiesResourcesTxt Case cs nodeImage = PropertiesResourcesTxt Case vb nodeImage = PropertiesResourcesTxt Case exe nodeImage = PropertiesResourcesExe Case dll nodeImage = PropertiesResourcesDll Case sln nodeImage = PropertiesResourcesVS Case csproj nodeImage = PropertiesResourcesVS Case bmp nodeImage = PropertiesResourcesImg Case png nodeImage = PropertiesResourcesImg Case gif nodeImage = PropertiesResourcesVideo Case accdb nodeImage = PropertiesResourcesAccess Case Else nodeImage = PropertiesResourcesUnknown それ以外のパスはディレクトリフォルダに属しています End Select Else nodeImage = PropertiesResourcesFolder End IfEnd Sub

VBNET

FlexGrid for WinForms

188 Copyright copy GrapeCity Inc All rights reserved

クリップボード

FlexGrid provides flexibility to perform various clipboard operations such as cut copy and paste on the editable griddata To enable automatic handling of common clipboard keys you need to set the AutoClipboard property to trueThe property handles following clipboard operations and their corresponding keys

Copy CTRL+C Ctrl+INS

Cut CTRL+X SHIFT+DEL

Paste CTRL+V SHIFT+INS

Delete DEL

The abovementioned clipboard operations do not have any affect on the styles and images and only work on gridheaders and data You can choose which part of the selected content to copy out of row header column headerand data by using the ClipboardCopyMode property When a datamap or multicolumn combobox exists in thecopied range only the display value is copied Also note that hidden cells are also copied when copying a cellrange To exclude hidden cells from copying see Exclude Hidden Cells

The code below demonstrates how to enable clipboard operations in the WinForms FlexGrid

Clipboard Operations through CodeYou can also perform clipboard operations through code The example below shows how to perform copying andpasting operations on button click

Use the code below to perform the clipboard operations through code in the WinForms FlexGrid

キーボードからクリップボード操作を有効にします c1FlexGrid1AutoClipboard = true データとすべてのヘッダーをコピーするようにコピーモードを設定します c1FlexGrid1ClipboardCopyMode = C1WinC1FlexGridClipboardCopyModeEnumDataAndAllHeaders

C

キーボードからクリップボード操作を有効にしますc1FlexGrid1AutoClipboard = True

データとすべてのヘッダーをコピーするようにコピーモードを設定しますc1FlexGrid1ClipboardCopyMode = C1WinC1FlexGridClipboardCopyModeEnumDataAndAllHeaders

VBNET

private void CopyButton_Click(object sender EventArgs e) クリップボードにコピーするグリッドのデータのみをコピーできるようにします c1FlexGrid1ClipboardCopyMode = ClipboardCopyModeEnumDataOnly

Clipプロパティに改行コードを追加しクリップボードに設定します ClipboardSetDataObject(c1FlexGrid1Clip + r) MessageBoxShow($Copied Range [c1FlexGrid1Rowc1FlexGrid1Col]-[c1FlexGrid1RowSelc1FlexGrid1ColSel])

C

FlexGrid for WinForms

189 Copyright copy GrapeCity Inc All rights reserved

Exclude Hidden CellsIn FlexGrid by default hidden cells are also copied when copying a cell range through keyboard operations enabledusing the AutoClipboard property However you can exclude the hidden rows and columns by using the code below

Following code shows how you can exclude the hidden cells from clipboard operations performed on the WinFormsTree Grid

private void PasteButton_Click(object sender EventArgs e) クリップボードのテキストを取得します IDataObject data = ClipboardGetDataObject() if (dataGetDataPresent(DataFormatsText)) string str1 str2 クリップボードからデータを取得します str1 = (string)dataGetData(DataFormatsText)

クリップボードから最後の行のフィードコードを削除します str2 = str1Remove(str1Length - 1 1)

範囲を選択してデータを貼り付けます c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col c1FlexGrid1RowsCount - 1 c1FlexGrid1ColsCount - 1 true) c1FlexGrid1Clip = str2 c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col)

Private Sub CopyButton_Click(ByVal sender As Object ByVal e As EventArgs) クリップボードにコピーするグリッドのデータのみをコピーできるようにします c1FlexGrid1ClipboardCopyMode = ClipboardCopyModeEnumDataOnly

Clipプロパティに改行コードを追加しクリップボードに設定します ClipboardSetDataObject(c1FlexGrid1Clip amp MicrosoftVisualBasicConstantsvbCr) MessageBoxShow($Copied Range [c1FlexGrid1Rowc1FlexGrid1Col]-[c1FlexGrid1RowSelc1FlexGrid1ColSel])End Sub

Private Sub PasteButton_Click(ByVal sender As Object ByVal e As EventArgs) クリップボードのテキストを取得します Dim data As IDataObject = ClipboardGetDataObject()

If dataGetDataPresent(DataFormatsText) Then Dim str1 str2 As String クリップボードからデータを取得します str1 = CStr(dataGetData(DataFormatsText))

クリップボードから最後の行のフィードコードを削除します str2 = str1Remove(str1Length - 1 1)

範囲を選択してデータを貼り付けます c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col c1FlexGrid1RowsCount - 1 c1FlexGrid1ColsCount - 1 True) c1FlexGrid1Clip = str2 c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col) End If

VBNET

C

FlexGrid for WinForms

190 Copyright copy GrapeCity Inc All rights reserved

列を非表示にしますc1FlexGrid1Cols[2]Visible = falsec1FlexGrid1AutoClipboard = true

次にCtrl + Cを押す前に非表示の列を含むいくつかのセルを選択しますprivate void c1FlexGrid1_KeyDown_1(object sender KeyEventArgs e) [Ctrl + C]でコピーします if ((eControl == true) ampamp (eKeyCode == KeysC)) 自動処理が行われないためキー入力を無効にします eHandled = true 選択したセル範囲のCellRangeオブジェクトを取得します C1WinC1FlexGridCellRange cr cr = c1FlexGrid1Selection

string StrCopy = for (int i = crr1 i lt= crr2 i++) if (c1FlexGrid1Rows[i]Visible == true) for (int j = crc1 j lt= crc2 j++) if (c1FlexGrid1Cols[j]Visible == true) StrCopy = StrCopy + c1FlexGrid1[i j]ToString() if (j = crc2) StrCopy = StrCopy + t StrCopy = StrCopy + n クリップボードに設定します ClipboardSetDataObject(StrCopy) MessageBoxShow(Copied data n + StrCopy)

列を非表示にします c1FlexGrid1Cols(2)Visible = False c1FlexGrid1AutoClipboard = True

次にCtrl + Cを押す前に非表示の列を含むいくつかのセルを選択しますPrivate Sub c1FlexGrid1_KeyDown_1(ByVal sender As Object ByVal e As KeyEventArgs)

[Ctrl + C]でコピーします If eControl = True AndAlso eKeyCode = KeysC Then 自動処理が行われないためキー入力を無効にします eHandled = True 選択したセル範囲のCellRangeオブジェクトを取得します Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1Selection Dim StrCopy =

VBNET

FlexGrid for WinForms

191 Copyright copy GrapeCity Inc All rights reserved

For i = crr1 To crr2

If c1FlexGrid1Rows(i)Visible = True Then For j = crc1 To crc2

If c1FlexGrid1Cols(j)Visible = True Then StrCopy = StrCopy amp c1FlexGrid1(i j)ToString()

If j ltgt crc2 Then StrCopy = StrCopy amp MicrosoftVisualBasicConstantsvbTab End If End If Next

StrCopy = StrCopy amp MicrosoftVisualBasicConstantsvbLf End If Next クリップボードに設定します ClipboardSetDataObject(StrCopy) MessageBoxShow(Copied data amp MicrosoftVisualBasicConstantsvbLf amp StrCopy) End IfEnd Sub

FlexGrid for WinForms

192 Copyright copy GrapeCity Inc All rights reserved

保存ロードと印刷

FlexGrid provides various built-in options so that you can easily save a grid and its content in a text excel or an XML file You can even load these saved filesto another grid or can save it as backup of a particular state of the grid You can also save the grid image in your desired format Not just this you can alsoprint the grid or selected areas of the grid if you need to have a hard copy This topic discusses various options related save load and print available in thegrid

Topic Content

Save Discusses about how to save the grid and its contents in different formats

Save as Text FileSave as Excel FileSave as XMLSave as Image

Load Discusses about how to load grid content from various file formats

Load from Text FileLoad from Excel FileLoad from DatabaseLoad from XML

Print Discusses about how to print the grid and other print related options

Print GridPrint OptionsCustomize Print Preview Dialog

保存

FlexGrid provides various methods to save the grid in the desired format such as text excel xml and image formatsThis feature is enabled through an assembly named C1WinC1FlexGridImportExportdll hence you need to addreference to this assembly to save the grid

Save as Text FileTo save grid content as a text file you can use the SaveGrid method of the Extensions class The method hasparameters that let you choose delimiter encoding and also lets you specify which portion of grid should be savedThe resulting text files can later be loaded back into the control or into other applications that support comma or tab-delimited files such as Microsoft Excel

Following code shows how to save content of the WinForms FlexGrid as a text file

private void btnSaveTxt_Click(object sender EventArgs e) c1FlexGrid1SaveGrid(ExportedGridtxt FileFormatEnumTextComma FileFlagsAsDisplayed | FileFlagsIncludeFixedCells)

C

Private Sub btnSaveTxt_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1SaveGrid(ExportedGridtxt FileFormatEnumTextComma FileFlagsAsDisplayed Or FileFlagsIncludeFixedCells)End Sub

VBNET

FlexGrid for WinForms

193 Copyright copy GrapeCity Inc All rights reserved

Save as Excel FileTo save grid as an excel file you can use the abovementioned SaveGrid method and simply set the format parameterto FileFormatEnumExcel You dont need to have Microsoft Excel installed on your computer However SaveGridmethod can only save the data in a workbook with single worksheet

To get an additional control over how you save your data to an excel file you can use the SaveExcel method insteadIn this case the process of saving excel files converts most data types and formatting information including row andcolumn dimensions fonts colors formats and cell alignment However some other features such as frozen andmerged cells images data maps and cell borders are not translated while converting to an excel file

Use the code below to save the WinForms FlexGrid as an Excel file

Save as XMLTo serialize grid contents into an XML document you can simply call WriteXML method of the C1FlexGrid class andparse path of the XML document as a parameter The method serializes all grid contents into the Xml documentincluding the data stored in the cells row and column properties styles and images Objects of custom types storedin the grid are also serialized as long as they have an associated SystemComponentModelTypeConverter thatprovides conversions to and from string

Below code demonstrates how to save contents of the WinForms FlexGrid to an XML document

Save as ImageTo save a grid as an image you can create the grid image using CreateImage method of the C1FlexGrid class andsave that image object at the specified path You can also specify a cell range or pass a cell range object as itsparameter to save a specific portion of the grid as an image

Use the code below to save the WinForms FlexGrid as an image

private void btnSaveExcl_Click(object sender EventArgs e) c1FlexGrid1SaveExcel(ExportedGridxlsx FileFlagsAsDisplayed | FileFlagsIncludeFixedCells)

C

Private Sub btnSaveExcl_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1SaveExcel(ExportedGridxlsx FileFlagsAsDisplayed Or FileFlagsIncludeFixedCells)End Sub

VBNET

private void btnSaveXML_Click(object sender EventArgs e) c1FlexGrid1WriteXml(ExportedGridxml)

C

Private Sub btnSaveXML_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1WriteXml(ExportedGridxml)End Sub

VBNET

FlexGrid for WinForms

194 Copyright copy GrapeCity Inc All rights reserved

private void btnSaveImg_Click(object sender EventArgs e) Image gridImage = c1FlexGrid1CreateImage() gridImageSave(ExportedGridpng)

C

Private Sub btnSaveImg_Click(ByVal sender As Object ByVal e As EventArgs) Dim gridImaage As Image = c1FlexGrid1CreateImage() gridImaageSave(ExportedGridpng)End Sub

VBNET

ロード

FlexGrid not only lets you save the grid to various formats but also lets you load data from various formats such textexcel XML or databases This feature is enabled through an assembly named C1WinC1FlexGridImportExportdllhence you need to add reference to this assembly to load the grid with data from these sources

Load from Text FileTo load data from a text file FlexGrid provides LoadGrid method of the Extensions class The method has parametersthat let you choose delimiter encoding etc You can also load text files saved using SaveGrid method When loadingtext files rows and columns are added to the grid if needed to accommodate the file contents The method supportsformats such as comma-delimited text files (CSV format) tab-delimited text files and even MS Excel files (xls)

Following code shows how to populate data in the WinForms FlexGrid by loading it from a text file

Load from Excel FileTo load grid from an excel file you can use the abovementioned LoadGrid method and simply set the formatparameter to FileFormatEnumExcel You dont need to have Microsoft Excel installed on your computer However theLoadGrid method can only load the data from first worksheet of a workbook

To get an additional control over how you load your data from an excel file you can use the LoadExcel methodinstead In this case the process of loading excel files converts most data types and formatting information includingrow and column dimensions fonts colors formats and cell alignment However there are still some exceptions Forexample the grid loads the values in excel cells but cannot load the underlying formulas Other features such asfrozen and merged cells images data maps and cell borders are not translated either

Use the code below to load contents in the WinForms FlexGrid from an excel file

private void btnLoadTxt_Click(object sender EventArgs e) c1FlexGrid1LoadGrid(ExportedGridtxt FileFormatEnumTextComma )

C

Private Sub btnLoadTxt_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1LoadGrid(ExportedGridtxt FileFormatEnumTextComma)End Sub

VBNET

FlexGrid for WinForms

195 Copyright copy GrapeCity Inc All rights reserved

Load from DatabaseTo load grid data from a database you can use the DataReader objects This process is different from data bindingwhich keeps a live connection between one or more controls and the underlying data source

Below code demonstrates how to load contents in the WinForms FlexGrid from the database

private void btnLoadExcl_Click(object sender EventArgs e) c1FlexGrid1LoadExcel(ExportedGridxlsx)

C

Private Sub btnLoadExcl_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1LoadExcel(ExportedGridxlsx)End Sub

VBNET

private void btnLoadDB_Click(object sender EventArgs e) DataReaderを準備します string strConn = data source=MYMACHINEinitial catalog=Northwind SystemDataSqlClientSqlConnection myConn = new SystemDataSqlClientSqlConnection(strConn) SystemDataSqlClientSqlCommand myCMD = new SystemDataSqlClientSqlCommand(SELECT FROM Employees myConn) myConnOpen() SystemDataSqlClientSqlDataReader myReader = myCMDExecuteReader()

DBスキーマからグリッド構造を構築します DataTable dt = myReaderGetSchemaTable() c1FlexGrid1ColsCount = 1 foreach (DataRow dr in dtRows) Column c =c1FlexGrid1ColsAdd() cCaption = cName = (string)dr[ColumnName] cDataType = (Type)dr[DataType]

グリッドにデータを入力します c1FlexGrid1RowsCount = 1 int row = 1 int cols = dtColumnsCount object[] v = (object[])ArrayCreateInstance(typeof(object) cols) while (myReaderRead()) myReaderGetValues(v) c1FlexGrid1AddItem(v row++ 1)

クリーンアップします c1FlexGrid1AutoSizeCols() myReaderClose() myConnClose()

C

FlexGrid for WinForms

196 Copyright copy GrapeCity Inc All rights reserved

Load from XMLTo deserialize grid contents from an XML document you can simply call ReadXML method of the C1FlexGrid classand parse path of the XML document as a parameter

Use the code below to load contents for the WinForms FlexGrid from an XML document

Private Sub btnLoadDB_Click(ByVal sender As Object ByVal e As EventArgs) DataReaderを準備します Dim strConn As String = data source=MYMACHINEinitial catalog=Northwind Dim myConn As New SqlClientSqlConnection(strConn) Dim myCMD As New SqlClientSqlCommand(SELECT FROM Employees myConn) myConnOpen() Dim myReader As SqlClientSqlDataReader = myCMDExecuteReader() DBスキーマからグリッド構造を構築します Dim dt As DataTable = myReaderGetSchemaTable() _flexColsCount = 1 Dim dr As DataRow For Each dr In dtRows Dim c As C1WinC1FlexGridColumn = _flexColsAdd() cCaption =(cName lt= CStr(dr(ColumnName))) cDataType = CType(dr(DataType) Type) Next dr グリッドにデータを入力します _flexRowsCount = 1 Dim row As Integer = 1 Dim cols As Integer = dtColumnsCount Dim v As Object() = CType(ArrayCreateInstance(GetType(Object) cols) Object()) While myReaderRead() myReaderGetValues(v) _flexAddItem(v row + 1 1) End While クリーンアップします _flexAutoSizeCols() myReaderClose() myConnClose()End Sub

VBNET

private void btnLoadXML_Click(object sender EventArgs e) c1FlexGrid1ReadXml(ExportedGridxml)

C

Private Sub btnLoadXML_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1ReadXml(ExportedGridxml)End Sub

VBNET

FlexGrid for WinForms

197 Copyright copy GrapeCity Inc All rights reserved

印刷

FlexGrid lets you print the grid and perform various basic and advanced print settings using its built-in methods andproperties

Print GridFlexGrid provides PrintGrid method of the C1FlexGrid class which lets you print the grid contents with some basicprinting options The method has an optional parameter PrintGridFlags that allows you to specify how to print thegrid such as its scaling mode and whether to display various print related dialog boxes You can also set text in headerand footer of the printed grid using this method

Following code shows how to use PrintGrid method to print the WinForms FlexGrid

Print OptionsTo set advanced printing options such as header and footer fonts page margins and page orientation you can usePrintParameter property of the C1FlexGrid class

Use the code below to print the WinForms FlexGrid with advanced print options

プレビューダイアログを表示し指定したヘッダとフッターでグリッドを印刷しますc1FlexGrid1PrintGrid(C1FlexGrid PrintGridFlagsFitToPageWidth | PrintGridFlagsShowPreviewDialog C1FlexGridtt + StringFormat(DateTimeNowToString() d) ttPage 0 of 1)

C

プレビューダイアログを表示し指定したヘッダとフッターでグリッドを印刷しますc1FlexGrid1PrintGrid(C1FlexGrid PrintGridFlagsFitToPageWidth Or PrintGridFlagsShowPreviewDialog C1FlexGrid amp vbTab amp vbTab amp StringFormat(DateNowToString() d) vbTab amp vbTab amp Page 0 of 1)

VBNET

FlexGrid for WinForms

198 Copyright copy GrapeCity Inc All rights reserved

Customize Print Preview DialogYou can customize the print preview dialog by using PrintPreviewDialog property of the GridPrinter class Theproperty can be accessed through PrintParameter property of the C1FlexGrid class The code below uses thePrintPreviewDialog property to display a maximized preview dialog with a custom caption

Below code demonstrates how to customize the print preview dialog of the WinForms FlexGrid

グリッドのPrintDocumentオブジェクトを取得しますSystemDrawingPrintingPrintDocument pd = c1FlexGrid1PrintParametersPrintDocument

ページを設定します(横向き15 左マージン)pdDefaultPageSettingsLandscape = truepdDefaultPageSettingsMarginsLeft = 150

ヘッダとフッタのフォントを設定しますc1FlexGrid1PrintParametersHeaderFont = new Font(Arial Black 14 FontStyleBold)c1FlexGrid1PrintParametersFooterFont = new Font(Arial Narrow 8 FontStyleItalic)

C

グリッドのPrintDocumentオブジェクトを取得しますDim pd As DrawingPrintingPrintDocument = c1FlexGrid1PrintParametersPrintDocument

ページを設定します(横向き15 左マージン)pdDefaultPageSettingsLandscape = TruepdDefaultPageSettingsMarginsLeft = 150

ヘッダとフッタのフォントを設定しますc1FlexGrid1PrintParametersHeaderFont = New Font(Arial Black 14 FontStyleBold)c1FlexGrid1PrintParametersFooterFont = New Font(Arial Narrow 8 FontStyleItalic)

VBNET

Form dlg = c1FlexGrid1PrintParametersPrintPreviewDialog as Form dlgText = Order Details dlgStartPosition = FormStartPositionCenterParent dlgWindowState = FormWindowStateMaximized c1FlexGrid1PrintGrid(Orders PrintGridFlagsShowPreviewDialog)

C

Dim dlg As Form = TryCast(c1FlexGrid1PrintParametersPrintPreviewDialog Form) dlgText = Order Details dlgStartPosition = FormStartPositionCenterParent dlgWindowState = FormWindowStateMaximized c1FlexGrid1PrintGrid(Orders PrintGridFlagsShowPreviewDialog)

VBNET

FlexGrid for WinForms

199 Copyright copy GrapeCity Inc All rights reserved

外観とスタイル設定

FlexGrid provides built-in visual styles as well as various design time and run time options so that you can style the grid and its elements as per the needsand appearance of your application The grid also provides style editors to let you customize appearance of your grid without writing a single line of codeFor more information about these editors and design time styling see Editors

This section discusses the built-in options provided by FlexGrid as well as various other ways to customize the appearance of grid and its elements

Topic Snapshot Content

Built-in Options Discusses about the available visual styles and built-in collection of styles

Visual StylesStyles Collection

Custom Styles Discusses how to create and apply the custom styles

Approach 1 Style an ObjectApproach 2 Create Re-usable Style

Customize Grid Discusses about customization at grid level

Set Alternate RowSet Background Image

Customize Border Discusses about customization of cell borders at row column or grid level

Customize Grid BorderCustomize RowColumn BorderCustomize Cell Border

Customize Text Discusses about various aspects of styling the grid text

Change FontSet MarginSet Vertical TextWrap TextDisplay Trimmed TextAlign TextApply Text Effect

Custom Glyphs Discusses about applying custom glyphs in the grid

組み込みオプション

Visual StylesFlexGrid provides six built-in visual styles so that you can easily customize the appearance of FlexGrid based on any ofthe Microsoft Office 2007 and 2010 themes These visual styles can be accessed through VisualStyle property ofthe C1FlexGrid class Apart from MS Office based visual styles you can also set this property to Custom and SystemWhen set to Custom the grid does not apply any visual styles and uses the grid properties for rendering When theproperty is set to System the grid renders its appearance based on current system settings

FlexGrid for WinForms

200 Copyright copy GrapeCity Inc All rights reserved

The property can be set using designer as well as through code To set the property at design time click smart tag toopen the C1FlexGrid Tasks menu and select a visual style from the VisualStyle combobox To apply visual style in theWinForms FlexGrid through code use the code below

Styles CollectionFlexGrid provides built-in collection of styles for predefined cell types and states such as normal cells fixed cellsfocused cells and so on You can use these built-in styles at design time as well as through code In design view youcan access these styles through the C1FlexGrid Style Editor which can be opened by clicking Styles option in Tasksmenu This collection of styles is represented by the CellStyleCollection class which can be accessed through Stylesproperty of the C1FlexGrid class Each built-in style is an object of the CellStyle class and holds various propertiessuch as BackColor DataType and Format

Following code shows how to use the styles from Styles collection of the WinForms FlexGrid

視覚スタイルをOffice2010Blueスキームに設定しますc1FlexGrid1VisualStyle = VisualStyleOffice2010Blue

C

視覚スタイルをOffice2010Blueスキームに設定しますc1FlexGrid1VisualStyle = VisualStyleOffice2010Blue

VBNET

組み込みセルスタイルNormalのプロパティを設定しますc1FlexGrid1Styles[Normal]BackColor = ColorAzurec1FlexGrid1Styles[Normal]ForeColor = ColorBlueViolet

固定セルの背景色を設定しますc1FlexGrid1Styles[Fixed]BackColor = ColorAqua

C

FlexGrid for WinForms

201 Copyright copy GrapeCity Inc All rights reserved

You can also add your own custom styles to Styles collection by using the Add method For more information abouthow to create and apply custom styles to grid cells see Custom Styles

組み込みセルスタイルNormalのプロパティを設定しますc1FlexGrid1Styles(Normal)BackColor = ColorAzurec1FlexGrid1Styles(Normal)ForeColor = ColorBlueViolet

固定セルの背景色を設定しますc1FlexGrid1Styles(Fixed)BackColor = ColorAqua

VBNET

カスタムのスタイル

Approach 1 Style an ObjectTo style a specific row column or a cell range of the WinForms FlexGrid you can use StyleNew property of the rowcolumn or cell range object

This approach is useful for styling a particular object when style is not expected to be reused To reuse a particularstyle you must create a style using the CellStyle object as discussed in the section below

Approach 2 Create Re-usable StyleIn this approach you can create a custom style as an object of CellStyle class and add it to the Styles collection usingthe Add method Then define its properties and apply it to a row column or cell range whenever required Asmentioned above this approach is very useful when you need to repeatedly use a particular style

Use the code below to create re-usable custom styles for your WinForms FlexGrid

特定の行にカスタムスタイルを適用しますc1FlexGrid1Rows[1]StyleNewBackColor = ColorAzurec1FlexGrid1Rows[1]StyleNewForeColor = ColorBlueViolet

C

特定の行にカスタムスタイルを適用しますc1FlexGrid1Rows(1)StyleNewBackColor = ColorAzurec1FlexGrid1Rows(1)StyleNewForeColor = ColorBlueViolet

VBNET

新しいスタイルを作成しスタイルコレクションに追加しますCellStyle cs = thisc1FlexGrid1StylesAdd(Custom) 新しいカスタムスタイルのプロパティを定義しますcsBackColor = ColorAzurecsForeColor = ColorBlueViolet

行にカスタムスタイルを適用しますc1FlexGrid1Rows[1]Style = cs

C

VBNET

FlexGrid for WinForms

202 Copyright copy GrapeCity Inc All rights reserved

新しいスタイルを作成しスタイルコレクションに追加しますDim cs As CellStyle = Mec1FlexGrid1StylesAdd(Custom)

新しいカスタムスタイルのプロパティを定義しますcsBackColor = ColorAzurecsForeColor = ColorBlueViolet

行にカスタムスタイルを適用しますc1FlexGrid1Rows(1)Style = cs

グリッドのカスタマイズ

FlexGrid also lets you customize overall look of the grid not to just increase its aesthetic value but also increases itsreadability You can add the alternate rows which make the grid more readable Also you can set image for instance awatermark or a company logo in background of the grid

Set Alternate RowTo set the alternate row color and styles in the grid you can use the built-in style Alternate either at design time orat runtime To apply style at design time you need to access the FlexGrid Style Editor and set properties for Alternatestyle

To apply alternate row style in the WinForms FlexGrid through code you need to use the CellStyle item Alternate ofthe CellStyleCollection class and set various properties for setting the alternate style

代替行の前色を設定します c1FlexGrid1Styles[Alternate]ForeColor = ColorWhite

代替行の背景色を設定します c1FlexGrid1Styles[Alternate]BackColor = ColorCadetBlue

C

FlexGrid for WinForms

203 Copyright copy GrapeCity Inc All rights reserved

Set Background Image in GridTo set the background image on a grid you can use the BackgroundImage property and assign the path of the imagefile to it Another property called BackgroundImageLayout property lets you choose whether and how to renderimage on the grid

Use the code below to set the background image on the WinForms FlexGrid

代替行の前色を設定しますc1FlexGrid1Styles(Alternate)ForeColor = ColorWhite

代替行の背景色を設定しますc1FlexGrid1Styles(Alternate)BackColor = ColorCadetBlue

VBNET

背景画像をグリッドに設定しますc1FlexGrid1BackgroundImage = ImageFromFile(CIMG-20190524-WA0037png)c1FlexGrid1BackgroundImageLayout = ImageLayoutStretch

C

背景画像をグリッドに設定しますc1FlexGrid1BackgroundImage = ImageFromFile(CIMG-20190524-WA0037png)c1FlexGrid1BackgroundImageLayout = ImageLayoutStretch

VBNET

境界線のカスタマイズ

The FlexGrid control lets you customize the border of grid row column and even cells by changing its style colordirection and so on

FlexGrid for WinForms

204 Copyright copy GrapeCity Inc All rights reserved

Customize Grid BorderTo customize border of the grid control you can use the BorderStyle property which accepts valuesfrom BorderStyleEnum provided by the C1WinFlexGridUtilBaseControls namespace

Following code shows how to customize border of the WinForms FlexGrid control

Customize RowColumn BorderTo customize the border style of a particular row or column you must access the Border item of CellStyle classusing StyleNew property and set its properties such as border style direction and color The grid controlprovides BorderStyleEnum as well as BorderDirEnum to set the border style and direction respectively

Use the below code to change border of rows or columns of the WinForms FlexGrid

Customize Cell BorderTo customize border of every cell in the grid you can access the built-in style Normal and set its border propertiesSimilarly you can change the style of specific types of cells such fixed or frozen by accessing their correspondingstyles from Styles collection

Below code lets you customize the border of normal cells of the WinForms FlexGrid

グリッドの境界線を3次元の境界線に変更しますc1FlexGrid1BorderStyle = C1WinC1FlexGridUtilBaseControlsBorderStyleEnumFixed3D

C

グリッドの境界線を3次元の境界線に変更しますc1FlexGrid1BorderStyle = C1WinC1FlexGridUtilBaseControlsBorderStyleEnumFixed3D

VBNET

最初の列の境界線スタイルを設定しますc1FlexGrid1Cols[1]StyleNewBorderStyle = BorderStyleEnumGroovec1FlexGrid1Cols[1]StyleNewBorderColor = ColorRedc1FlexGrid1Cols[1]StyleNewBorderDirection = BorderDirEnumVertical

最初の行の境界線スタイルを設定しますc1FlexGrid1Rows[1]StyleNewBorderStyle = BorderStyleEnumRaisedc1FlexGrid1Rows[1]StyleNewBorderColor = ColorBlue

C

最初の列の境界線スタイルを設定しますc1FlexGrid1Cols(1)StyleNewBorderStyle = BorderStyleEnumGroovec1FlexGrid1Cols(1)StyleNewBorderColor = ColorRedc1FlexGrid1Cols(1)StyleNewBorderDirection = BorderDirEnumVertical

最初の行の境界線スタイルを設定しますc1FlexGrid1Rows(1)StyleNewBorderStyle = BorderStyleEnumRaisedc1FlexGrid1Rows(1)StyleNewBorderColor = ColorBlue

VBNET

FlexGrid for WinForms

205 Copyright copy GrapeCity Inc All rights reserved

すべてのグリッドセルの境界線スタイルを設定しますc1FlexGrid1StylesNormalBorderStyle = BorderStyleEnumDouble

C

すべてのグリッドセルの境界線スタイルを設定しますc1FlexGrid1StylesNormalBorderStyle = BorderStyleEnumDouble

VBNET

テキストのカスタマイズ

FlexGrid lets you customize text in various ways such as changing its font margin orientation alignment effects and soon This topic caters to various aspects of text styling by taking a particular row object However if you wish to use anexisting built-in style or want to create your own custom style to re-use it see the corresponding topics

Change FontTo change font of text in a particular row or column object you can use Font property of its CellStyle Following codeshows how to change font of the WinForms FlexGrid row

カスタムスタイルを特定の行に適用しますc1FlexGrid1Rows[1]StyleNewFont = new Font(verdana 10 FontStyleUnderline)c1FlexGrid1Rows[0]StyleNewFont = new Font(verdana 10 FontStyleBold)

C

カスタムスタイルを特定の行に適用しますc1FlexGrid1Rows(1)StyleNewFont = new Font(verdana 10 FontStyleUnderline)c1FlexGrid1Rows(0)StyleNewFont = new Font(verdana 10 FontStyleBold)

VBNET

FlexGrid for WinForms

206 Copyright copy GrapeCity Inc All rights reserved

However if you want to change font of the whole grid you can set Font property of the C1FlexGrid class Followingcode shows how to change font of the entire WinForms FlexGrid

Set MarginTo set margin on text of a particular row or column you can set Margins property of the CellStyle Use the code belowto change margins in WinForms FlexGrid row

Set Vertical TextTo change the orientation and display a text as vertical text you can set TextDirection property of CellStyle of theobject Also to display the vertical text properly you may have to adjust height of the target cells depending upon thetext length Below code lets you set vertical text in the WinForms FlexGrid row

Wrap TextTo wrap a text which is longer than the available cell width you can set the WordWrap property of its CellStyle to trueFollowing code demonstrates how to apply text wrap in the WinForms FlexGrid row

グリッドの内容全体のフォントを変更しますc1FlexGrid1Font = new Font(verdana 10 FontStyleItalic)

C

グリッドの内容全体のフォントを変更しますc1FlexGrid1Font = New Font(verdana 10 FontStyleItalic)

VBNET

右側のマージンを設定しますc1FlexGrid1Rows[1]StyleNewMarginsRight = 10

C

右側のマージンを設定しますc1FlexGrid1Rows(1)StyleNewMarginsRight = 10

VBNET

行の内容のテキスト方向を設定しますc1FlexGrid1Rows[1]StyleNewTextDirection = TextDirectionEnumDown 行の高さを設定して垂直方向のテキストを表示しますc1FlexGrid1Rows[1]Height = 60

C

行の内容のテキスト方向を設定しますc1FlexGrid1Rows(1)StyleNewTextDirection = TextDirectionEnumDown

行の高さを設定して垂直方向のテキストを表示しますc1FlexGrid1Rows(1)Height = 60

VBNET

C

FlexGrid for WinForms

207 Copyright copy GrapeCity Inc All rights reserved

Display Trimmed TextTo display trimmed text when text is longer than the cell width set Trimming property of the style which takes its valuesfrom StringTrimming enumeration Use the code below to trim the long text to display ellipsis character in theWinForms FlexGrid row

Align TextYou can set the text alignment or position of the text with respect to cell by using the TextAlign property The propertyaccepts values from the TextAlignEnum enumeration

Use the code below to apply text alignment on the WinForms FlexGrid row

Apply Text EffectTo set various effects on the text you can use the TextEffect property which accepts its values from TextEffectEnumenumeration

Apply text on the WinForms FlexGrid row using the following code

セルの幅に応じて特定の行のテキストを折り返しますc1FlexGrid1Rows[1]StyleNewWordWrap = true

セルの幅に応じて特定の行のテキストを折り返しますc1FlexGrid1Rows(1)StyleNewWordWrap = True

VBNET

長いテキストをトリミングして最後に省略記号を表示しますc1FlexGrid1Rows[1]StyleNewTrimming = StringTrimmingEllipsisCharacter

C

長いテキストをトリミングして最後に省略記号を表示しますc1FlexGrid1Rows(1)StyleNewTrimming = StringTrimmingEllipsisCharacter

VBNET

テキストの配置を設定しますc1FlexGrid1Rows[1]StyleNewTextAlign = TextAlignEnumLeftCenter

C

テキストの配置を設定しますc1FlexGrid1Rows(1)StyleNewTextAlign = TextAlignEnumLeftCenter

VBNET

上げ表示するテキストを設定しますc1FlexGrid1Rows[1]StyleNewTextEffect = TextEffectEnumRaised

C

上げ表示するテキストを設定します c1FlexGrid1Rows(1)StyleNewTextAlign = TextAlignEnumLeftCenter

VBNET

FlexGrid for WinForms

208 Copyright copy GrapeCity Inc All rights reserved

カスタムのグリフ

FlexGrid lets you change the default glyph images used in the grid to indicate various actions such as column filteringand sorting This behavior of grid is exposed through GridGlyphs class which is a collection of images used by the gridto represent filtered state sorting order checkbox states and so on These images can be accessed through Glyphsproperty of the C1FlexGrid class which accepts values from GlyphEnum enumeration

Change the default glyphs used for filter editor and filtered column in the WinForms FlexGrid to a custom image usingthe code below

Note that setting this property to null restores the default glyph In order to hide a glyph you can set the Glyphproperty to a blank image

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilterEditor] = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilteredColumn] = ImageFromFile(filterico)

C

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilterEditor) = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilteredColumn) = ImageFromFile(filterico)

VBNET

FlexGrid for WinForms

209 Copyright copy GrapeCity Inc All rights reserved

永続的な状態

Grid persistence refers to saving the current state of the grid for later use and then restoring it back when needed Forinstance the user may apply grouping sorting filtering or some styling to the grid which he wants to use after fewmore operations or on opening the application again This behavior can be achieved by persisting the grids state

There are two steps to implement persistence of the grid state First we have to serialize the grid state and then werestore it In this topic we discuss how to persist the filtered sorted and grouped state of the FlexGrid control

You can implement persisting grid states by using XMLWriter and XMLReader class of the SystemXML namespace Tosave the grid state you can use the WriteStartElement method to write the specified start tag andWriteAttributeString method to write the filter sort and group attributes Finally call WriteEndElement method toclose the WriteStartElement method and save the state in the form of stream string or a file

Use the code below to serialize the state of WinForms FlexGrid to an XML file for later use

フィルタグループ並べ替えの定義をファイルに書き込みますprivate void WriteStateToXML(string filePath) using (XmlWriter writer = XmlWriterCreate(filePath)) writerWriteStartElement(FlexGrid) writerWriteStartElement(Definition ) writerWriteAttributeString(Filter flexGridFilterDefinition) writerWriteAttributeString(Sort flexGridSortDefinition) writerWriteAttributeString(Group flexGridGroupDefinition) writerWriteEndElement() writerWriteEndElement() writerFlush()

C

フィルタグループ並べ替えの定義をファイルに書き込みますPrivate Sub WriteStateToXML(ByVal filePath As String)

VBNET

FlexGrid for WinForms

210 Copyright copy GrapeCity Inc All rights reserved

To load the saved state back into the grid you can use the GetAttribute method of the object to read the filter sortand group attributes Then assign them to the FilterDefinition SortDefinition or GroupDefinition properties of theFlexGrid respectively

Use the code below to load saved state of the WinForms FlexGrid

Using writer = XmlWriterCreate(filePath) writerWriteStartElement(FlexGrid) writerWriteStartElement(Definition ) writerWriteAttributeString(Filter flexGridFilterDefinition) writerWriteAttributeString(Sort flexGridSortDefinition) writerWriteAttributeString(Group flexGridGroupDefinition) writerWriteEndElement() writerWriteEndElement() writerFlush() End UsingEnd Sub

保存したファイルからフィルタ並べ替えグループの定義を読み取りFlexGridに適用しますprivate void ReadStateXML(string filePath)

using (XmlReader reader = XmlReaderCreate(filePath)) readerReadToFollowing(Definition) flexGridSortDefinition = readerGetAttribute(Sort) flexGridFilterDefinition = readerGetAttribute(Filter) flexGridGroupDefinition = readerGetAttribute(Group) readerClose()

C

保存したファイルからフィルタ並べ替えグループの定義を読み取りFlexGridに適用しますPrivate Sub ReadStateXML(ByVal filePath As String) Using reader = XmlReaderCreate(filePath) readerReadToFollowing(Definition) flexGridSortDefinition = readerGetAttribute(Sort) flexGridFilterDefinition = readerGetAttribute(Filter) flexGridGroupDefinition = readerGetAttribute(Group) readerClose() End Using

VBNET

FlexGrid for WinForms

211 Copyright copy GrapeCity Inc All rights reserved

NET 5 リファレンス

FlexGrid for WinForms

212 Copyright copy GrapeCity Inc All rights reserved

NET 452 リファレンス

FlexGrid for WinForms

213 Copyright copy GrapeCity Inc All rights reserved

  • 目次
  • FlexGrid for WinForms
  • 主な特長
  • 機能比較
    • FlexGrid の比較
    • WinFormsグリッドの比較
      • クイックスタート
      • 設計時サポート
        • タスクメニュー
        • エディタ
          • データ
            • 非連結モード
            • 連結モード
              • 連結モードでの操作
                    • 基本操作
                    • ユーザー操作
                    • エディタ
                      • チェックボックス
                      • 数値
                      • 日付
                      • コンボボックス
                      • マスク
                      • マップリスト
                      • セルボタン
                        • 検証
                        • データ注釈
                        • スパークライン
                        • ヘッダとフッタ
                        • サイズ変更
                            • 基本操作
                            • ユーザー操作
                            • ヘッダ
                            • 行の詳細
                            • サイズ変更
                              • セル
                                • 基本操作
                                • セルの書式設定
                                  • グリッド
                                    • 基本操作
                                    • キーボードによる移動
                                    • パフォーマンスの向上
                                      • スクロールバー
                                      • 選択
                                      • 編集
                                        • 編集モード
                                        • 編集の無効化
                                          • 並べ替え
                                            • 並べ替えの操作
                                            • 並べ替えのインジケータ
                                              • フィルタ
                                                • フィルタの操作
                                                  • フィルタの種類
                                                    • フィルタUI
                                                      • 検索
                                                      • マージ
                                                        • 自動マージ
                                                        • はみ出して表示されるセルの処理
                                                        • カスタムのマージ
                                                          • グループ
                                                          • 集計
                                                          • ツリーグリッド
                                                            • ノードの操作
                                                            • データの操作
                                                            • ツリーグリッドのカスタマイズ
                                                              • クリップボード
                                                              • 保存ロードと印刷
                                                                • 保存
                                                                • ロード
                                                                • 印刷
                                                                  • 外観とスタイル設定
                                                                    • 組み込みオプション
                                                                    • カスタムのスタイル
                                                                    • グリッドのカスタマイズ
                                                                    • 境界線のカスタマイズ
                                                                    • テキストのカスタマイズ
                                                                    • カスタムのグリフ
                                                                      • 永続的な状態
                                                                      • NET 5 リファレンス
                                                                      • NET 452 リファレンス
Page 4: FlexGrid for WinForms

ツリーグリッドのカスタマイズ 181-188

クリップボード 189-192

保存ロードと印刷 193

保存 193-195

ロード 195-197

印刷 197-199

外観とスタイル設定 200

組み込みオプション 200-202

カスタムのスタイル 202-203

グリッドのカスタマイズ 203-204

境界線のカスタマイズ 204-206

テキストのカスタマイズ 206-208

カスタムのグリフ 209

永続的な状態 210-211

NET 5 リファレンス 212

NET 452 リファレンス 213

FlexGrid for WinForms

3 Copyright copy GrapeCity Inc All rights reserved

FlexGrid for WinForms

FlexGrid for WinForms is one of the fastest datagrids available in the market that renders and displays large data sets quicker than any other NET datagrid It is a powerfulgrid packed with basic as well as advanced features like in-cell editing sorting filtering merging grouping and much more Moreover it displays the hierarchical dataefficiently using tree grids with multiple columns aggregates subtotals and row details Not just this the control offers robust API and extensive design-time support sothat you can give your end-users a familiar Excel-like experience

The FlexGrid control binds with any of the NET data sources such as ADONET data source objects and custom business objects It also lets you work in the unbound modegiving you the power to manually add each row or column and set the cell values

One of the main strengths of FlexGrid is the ability to customize almost every aspect of appearance of the entire grid and individual cells In addition to standard formatstrings and cell styling FlexGrid goes above and beyond most NET datagrid components by providing complete control over the cell drawing using its OwnerDrawCell event

Besides the main C1FlexGrid control FlexGrid for WinForms also contains a C1FlexGridClassic control derived from C1FlexGrid It provides an object model that is virtuallyidentical to the VSFlexGrid ActiveX control and is mainly targeted for customers who want to migrate their existing VSFlexGrid projects from ActiveX to the latest technology

Not just this if you are developing your own custom grid control you can use C1FlexGridClassic as a reference The C1FlexGridClassic control is a perfect example of customgrid control created with C1FlexGrid control as base class We ship its source code as a product sample named Classic

Release Notes Product Samples

See the version-wise updates for all controls here Product samples are located at DocumentsComponentOne SamplesWinFormsvxxxC1FlexGridCS onyour system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

Documentation Blogs

Create your First Application with FlexGrid

FlexGrid at Design-time

Work with Columns and Editors

Filter Grid Data

Enable Merging in FlexGrid

Create Groups

Create a Tree Grid

Financial Data Displays using FlexGrid

FlexGrid Performance Compare WinForms WPF UWP

Creating Custom Styles for FlexGrid

Add Dynamic Grouping to your WinForms Data Grid

Implement responsive columns in a WinForms data grid

Creating a Derived Accordion Control with FlexGrid

Show RadioButton in a ComponentOne FlexGrid Tree

Videos Demo Samples

Meet FlexGrid WinForms and WPF Grid Demo

Note ComponentOne FlexGrid for WinForms is compatible with both NET 452 and NET 5

API Reference

C1WinFlexGrid452 Assembly C1WinFlexGrid5 Assembly

FlexGrid for WinForms

4 Copyright copy GrapeCity Inc All rights reserved

主な特長

Code-free Development

Why write code when a click is enough With rich design-time options beginning from binding to styling whichare accessible through the tasks menu and various editors FlexGrid lets you do a lot even without writing a single lineof code

Advanced Cell Editing

Choose from a variety of built-in editors or just create one for yourself FlexGrid offers various built-in cell editors sothat you can choose from simple text editing drop-down lists combo lists cell buttons masks and so on Not justthis with an option to create your own custom cell editors you can change your cells to accept or display almostany type of data

Work in Bound Mode or Unbound Mode

Bound grid or unbound populate the data seamlessly FlexGrid lets you bind the grid with any of the NET datasources such as ADONET and DataObjects for NET You can also work in unbound mode and let FlexGrid manage thedata itself

Present Hierarchical Data

View data the way that is best for you and your users When FlexGrid is bound to a hierarchical data source eachmaster record can be expanded or collapsed to show or hide the details in child grids which may contain moredetails The result is a data tree similar to the type of grid presented by Microsoft Access when displayinghierarchical data When bound the control detects subordinate data sources and creates additional instances of itselfto display child tables

Summarize Data and Show Aggregates

Get a quick outline of your grid data by summarizing it FlexGrid allows you to summarize data by adding a subtotalrow and display aggregates such as sum average count and so on for the specified column

Make it a Tree

Easily display your hierarchical data by converting your grid into a tree FlexGrid lets you represent your bound orunbound hierarchical data in Tree Grid which is similar to a TreeView control and gives a clean yet accessible structureto the data

Built-in Data Filtering

Let your users filter the data by value by condition or just give them both the options to choose from FlexGridprovides advanced built-in filtering with column filter value filter and condition filter already in place Still does notwork for you Create your own custom filter using rich FlexGrid API

Grouping

Group programmatically or at run-time With FlexGrid both are possible FlexGrid lets you group either through codeand even give your users an option to group at run-time using the FlexGridGroupPanel control or through contextmenu

Instant Search

Search the entire grid in one go and locate entries among millions of records instantly FlexGridprovides FlexGridSearchPanel control which lets the user type in the search box filters the records that match thetyped text and also highlights the search results

Merge Cells

Give your grid a tidy look by merging the cells with the same values FlexGrid lets you merge the contiguous cells withthe same values the way you want With free and restricted auto-merge options the grid can intelligently decidewhich cells to merge

Save and Load Multiple Formats

Back up the grid data or load it back in a jiffy FlexGrid lets you save the grid in your favorite format be it a text fileexcel file or XML You can even load content from these formats Not just this you can also load grid data from a

FlexGrid for WinForms

5 Copyright copy GrapeCity Inc All rights reserved

database using DataReader objects

Show Sparklines

Perk up your grid with the tiny charts FlexGrid allows you to add sparklines to grid columns so that you can easilydisplay trends and fluctuations in a single cell and make your grid data more useful and attractive at the same time

Perform Clipboard Operations

Move your text easily with Ctrl+C and Ctrl+V FlexGrid lets you perform clipboard operations on the grid data andheaders using your favorite keys

Assign Field Names to Columns

No need to remember the index of columns just call them by name FlexGrid automatically assigns column keysto field names when the grid is data-bound or you may assign them through code You can refer to a column using aColIndex(ColKey) syntax later which will retrieve the column you want even if your user has moved it to a differentposition on the grid

Use Data Annotations

Hint the user with data annotations FlexGrid lets you add data annotations in the form of metadata tags to theclasses and other objects to display messages and tips for the users

UI Automation and Support

Enable accessible and rich client applications through UI Automation (UIA) FlexGrid control supports UI Automationusing frameworks such as TestStackWhite You can enable applications such as screen readers coded UI testing toexamine user-interface elements and even simulated user interaction through code

Note UI Automation works only for the 452 version of C1FlexGrid and NET framework 47 or above applicationtarget frameworks

Add Special Drawing Effects

Make your grid look different and attractive with special drawing effects FlexGrid lets you paint special drawingeffects such as lines bitmaps and icons in the grid cells Additionally you can even scale images and addtransparency to them

Display Images in Cells

Need to display images in columns not an issue at all With FlexGrid you can display images along with data You caneven bind grid columns to image lists an easy and efficient way to display graphical information from data sources

Integrated Printing

Print the grid with a single statement FlexGrid gives you control over paper orientation margins header and footertext as well as the dialog boxes to set up the printer or see a preview You can even implement advanced printingoptions such as adding page breaks or custom elements to each page by using printing events

Styling

Use the visual styles or create your own custom styling use the designer or write your own code FlexGrid gives youenormous options to customize the appearance of the grid to match your requirements You can customize everyelement of the FlexGrid starting from headers and icons to borders and subtotal rows

FlexGrid for WinForms

6 Copyright copy GrapeCity Inc All rights reserved

機能比較

This section compares the features of various FlexGrids available across different platforms as well as shows acomparison with MS DataGridView

Topic Content

ComparingFlexGrids

Lists the difference between ActiveX version(VSFlexGrid control) and NET version of the FlexGridcontrol making it easy to migrate your grid from AciveX to NET

VSFlexGrid (ActiveX) and C1FlexGrid (NET)

ComparingWinForms Grids

Shows comparison between features of grids available in ComponentOne WinForms Edition andMS DataGridView

FlexGrid or True DBGridComparing ComponentOne Grids with MS DataGridView

FlexGrid の比較

VSFlexGrid (ActiveX) and C1FlexGrid (NET)ComponentOne provides ActiveX as well as NET version of the FlexGrid control While the ActiveX version is known asVSFlexGrid the NET version is shipped in the name of C1FlexGrid Being a NET version C1FlexGrid came laterinto the picture and instead of porting from the already existing VSFlexGrid we decided to create a brand new gridcontrol written from the ground up in C with the same design principles but with a new object model that is moremodern clean and powerful than the one in the ActiveX control

This section caters to original users of the VSFlexGrid control who want to migrate their applications from ActiveX tothe NET version that is the C1FlexGrid control To facilitate the hassle-free migration and a smooth learning curvethe NET version provides the C1FlexGridClassic control that derives from the C1FlexGrid class and provides an objectmodel that is virtually identical to the VSFlexGrid control The C1FlexGridClassic control is available in the form of aproduct sample Classic so that you may know exactly how to use the new object model This sample can also beused as a reference for creating the custom grid controls based on the C1FlexGrid class

Note The Classic sample is located at DocumentsComponentOne SamplesWinFormsv452C1FlexGridCS onyour system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

For users creating new applications we recommend using the new C1FlexGrid control However for the users who areporting their existing applications from ActiveX to NET we recommend using the C1FlexGridClassic control tominimize the programming effort Following table highlights some of the key differences between VSFlexGrid andC1FlexGrid

VSFlexGrid (ActiveX) C1FlexGrid (NET)

RowsCols1 Rows and Cols properties are used to

get or set the number of rows andcolumns

2 VSFlexGrid uses the TextMatrixproperty to represent the rows andcolumns

1 In C1FlexGrid Rows and Cols propertiesreturn the rows and column collectionsThe collections have readwriteproperties that return the number ofelements and fixed elements in eachcollection

FlexGrid for WinForms

7 Copyright copy GrapeCity Inc All rights reserved

For instance in ActiveX you would write

Dim r c c = 1

For r = c1FlexGrid1FixedRows To

c1FlexGrid1Rows - 1

DebugPrint

c1FlexGrid1TextMatrix(rc)

Next

2 C1FlexGrid uses indexers to representrows and columns

For instance in NET you would write

Dim r c c = 1

For r = c1FlexGrid1RowsFixed To

c1FlexGrid1RowsCount - 1

DebugPrint(c1FlexGrid1(r c))

Next

CellCell range The Cell property is one of the mostpowerful elements of the VSFlexGrid objectmodel It allows you to get or set anyproperty of any cell or cell range with asingle command Using a single propertymeans using variants and this prevents thecompiler from catching many subtleproblems in case you make mistakes whilecoding

For instance in ActiveX you would write

flexCell(flexcpPicture 5 5

10 10)

= theImage

In C1FlexGrid CellRange object has replacedthe Cell property to expose type-safeproperties and methods for accessing cellrange So if variable theImage contained astring instead of an image you get a compilererror and not a runtime error Also you getcommand-completion when writing the codebecause the types for each property are known

For instance in NET you would write

Dim rg As CellRange

rg =

c1FlexGrid1GetCellRange(551010)

rgImage = theImage

Typed Columns In the ActiveX version the ColDataTypeproperty allows you to set the type of datathat each column contains This informationis used mainly for sorting columns thatcontain dates or numbers

In the NET version Cols[i]DataType propertydetermines the type of data the column holdsBy default the DataType property for allcolumns is set to object that is you can storeany type of data in any column You can set thedata type to specific types however the gridtries to coerce any data stored in the grid tothe proper type

For instance in NET you would write

c1FlexGrid1Cols(2)DataType =

GetType(Integer)

Sets the value to 12

c1FlexGrid1(1 2) = 12

Can not convert hello string to

integer

Fires the GridError event

Retains the original value

c1FlexGrid1(2 2) = hello

Styles In VSFlexGrid you can customize theappearance of individual cells or cell rangesusing the Cell property

For instance in ActiveX you would write

Set the backcolor of second row

c1FlexGrid1Cell(flexcpBackColor

In C1FlexGrid cell appearance can becustomized using the CellStyle object

For instance in NET you would write

Create a cell style

Dim redStyle As CellStyle =

c1FlexGrid1Styles

FlexGrid for WinForms

8 Copyright copy GrapeCity Inc All rights reserved

2 0 2

c1FlexGrid1Cols-1) = vbRed

Demerit

To change the appearance of all red cellsyou need to clear all styles and start again oryou need to scan for red cells and thenchange their appearance

Add(Red)

redStyleBackColor = ColorRed

Set the backcolor of second row

c1FlexGrid1Rows(2)Style =

redStyle

Merit

The main advantage of this approach is that thenew style is an object that can be changed orassigned to new ranges For instance tochange the fore-color and text font of red cellsyou would write

c1FlexGrid1Styles(Red)ForeColor

= ColorWhite

c1FlexGrid1Styles(Red)Font =

new Font(Arial 9)

The VSFlexGrid control had many propertiesthat affected the way the grid was displayed(eg BackColor BackColorAlternateBackColorBkg BackColorFixedBackColorFrozen BackColorSel and so on)

The C1FlexGrid control replaces all theseproperties with a collection of CellStyle objectsso you can write something likeStylesFixedBackColor orStylesHighlightForeColor This makes theobject model simpler more consistent andmore powerful You can change the built-instyles or define your own and assign them torows columns or arbitrary cell ranges

WinFormsグリッドの比較

FlexGrid or True DBGridComponentOne offers two grid components in WinForms Edition FlexGrid and True DBGrid While both of these are robust and easy-to-usegrids allowing you to browse edit add delete and manipulate tabular data they still have their own strengths and capabilities

Both ComponentOne WinForms Edition grids can be used in bound as well as unbound mode but C1FlexGrid allows you to work more easilyin unbound mode With C1FlexGrid you can customize trees and make use of its cell merging capabilities FlexGrid is also apt for deriving acustomized grid

If you are planning to develop or migrate to NET 5 or higher it is recommended to use C1FlexGrid While we will continue to supportC1TrueDBGrid in NET 5 it no longer receives new enhancements and features like C1FlexGrid

Comparing ComponentOne Grids with MS DataGridViewThis section gives you a quick comparison between the two ComponentOne WinForms Edition grids and the standard MS DataGridViewavailable for WinForms platform For easy navigation we have broadly divided these features into different categories Click on thecorresponding category in the right hand pane or scroll down to know more about availability of a particular feature

Data Binding

Features FlexGrid TrueDBGrid MS DataGridView

Binding Data Sources

Binding Data Sources with hierarchical datarelations

With custom code

Unbound data storage and manipulations

Data Presentation

FlexGrid for WinForms

9 Copyright copy GrapeCity Inc All rights reserved

Features FlexGrid TrueDBGrid MS DataGridView

Hierarchical Styles With custom code

TreeView-like Styles

MultiLine Data View

Grouping

Built-in Drag And Drop

Horizontal and Vertical Interactive Splits

Child grids within master grid support

Drop-Down Objects Support

Drop-Down Multicolumn Object support

Drop-Down Multicolumn Bindable and SortableObject support

Data Exchange

Features FlexGrid TrueDBGrid MS DataGridView

Export Data (Delimited Text XLS and XLSX)

Export Data in other formats (PDF HTML RTFJPG and other)

Load data from Excel files

Enhanced Printing data from grid and PrintPreview support

Cell Manipulations

Features FlexGrid TrueDBGrid MS DataGridView

In-Cell Objects

Enhanced Cell Editing with Custom Editors

Merging Cells and Rows

Customize Cells Merging

Drag And Drop Columns and rows

Automatic Cell Sizing

Fixed Non-scrolling Columns

Excel-style Cell Selection

Customize each Cell Rendering

Zooming Cells

Run-Time CellTips

Data Manipulations with Cell Ranges

Layout and Styling

Features FlexGrid TrueDBGrid MS DataGridView

Visual Styles Support

Dynamic Support of 38 Decoration Themes

Office 2007 and 2010 Styling

Alternating Row Colors

Customizable Cell Border Style

FlexGrid for WinForms

10 Copyright copy GrapeCity Inc All rights reserved

Add Special Drawing Effects

Data-Sensitive Display

Input and Navigation

Features FlexGrid TrueDBGrid MS DataGridView

Input Masking

Simplify Data Input

Automatic Data Translation

Spell Checking support

Customizable Keyboard Navigation and keysbehavior

Right-To-Left navigation

Touch Support

Clipboard support

Rich Scrolling Capabilities

Data Manipulations

Features FlexGrid TrueDBGrid MS DataGridView

Sorting

Multi-column Sorting

Built-in Data Filtering

Extended and Conditional Filtering

Customizable filter form

Additional Filter Bar row

Multi-language Filtering

AutoSearch

Range Aggregates

Localization

Features FlexGrid TrueDBGrid MS DataGridView

Right-To-Left support

Net localization support

Regional settings support

Other Features

Features FlexGrid TrueDBGrid MS DataGridView

Optimize performance for displaying largeamount of data in bound and unbound mode

Just-In-Time Data Loading

Server-side Data Virtualization withC1DataSource

Automatic Lookup Columns with C1DataSource

Design-time extended support

Assembly size 1508 K 2108 K Part of

FlexGrid for WinForms

11 Copyright copy GrapeCity Inc All rights reserved

SystemWindowsForms

FlexGrid for WinForms

12 Copyright copy GrapeCity Inc All rights reserved

クイックスタート

This quick start will guide you through the steps of creating a simple grid application using the FlexGrid control Follow thesteps below to get started

FlexGrid for WinForms

13 Copyright copy GrapeCity Inc All rights reserved

This section demonstrates how to create a FlexGrid application in NET 452 by binding it to an externaldatasource You can also create a class to supply data to the grid as shown in the NET 5 tab Similarly you can usebelow steps to bind FlexGrid to a datasource in NET 5 However note that some design-time steps may vary in caseof NET 5

Set Up the Application1 Create a new Windows Forms app(NET Framework)2 Configure your project and set the Framework property3 Drag and drop the FlexGrid control from the Visual Studio toolbox onto the form

Observe An empty grid is added to the form at design time

Bind FlexGrid to a Data SourceThere are two ways to bind data with the FlexGrid control either choose to bind at design time or through code atrun time

Binding at Design Time

1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Click the Choose Data Source drop down button and select Add Project Data Source option to open the

Data Source Configuration Wizard3 On Choose a Data Source Type page select Database and click Next4 On Choose a Database Model page select Dataset and click Next5 On Choose Your Data Connection page click New Connection to open the Add Connection dialog6 Against the DataSource field click Change button to open the Change Data Source dialog7 Select Microsoft Access Database File and click OK to return to the Add Connection dialog8 Against the Database file name field click Browse and navigate to the database file Provide the User name

and Password if required to connect to the database file This example uses C1NWindmdb file located atthe following location by defaultDocumentsComponentOne SamplesCommon

9 Click Test Connection to make sure that you have successfully connected to the database or server and clickOK

NET 452

FlexGrid for WinForms

14 Copyright copy GrapeCity Inc All rights reserved

10 Click OK again to close the Add Connection dialog box11 Click Next 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 Choose the appropriate option as per your requirement12 Save the connection string in the application configuration file by checking the Yes save the connection as

box and entering a name13 Click Next to switch to the Choose Your Database Objects page14 Choose a table say Products from the Tables node and click Finish15 The above steps add a dataset and connection string to your project Also Visual Studio automatically creates

the following code to fill the datasetC

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて

移動または削除できます

thisproductsTableAdapterFill(thisc1NWindDataSetProducts)

VBNET

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移

動または削除できます

MeProductsTableAdapterFill(Mec1NWindDataSetProducts)

Binding at Run Time

To bind the grid through code first we need to create a database connection string Then use an object of dataadapter (in this case OleDbDataAdapter) to create a query to fetch products from the data table and fill it in thedata table which is assigned to the DataSource property of C1FlexGrid class

C

グリッドをデータソースに連結します

string conn = GetConnectionString()OleDbDataAdapter da = new OleDbDataAdapter(select from products conn)DataTable dt = new DataTable(Products)daFill(dt)c1FlexGrid1DataSource = dt

VBNET

グリッドをデータソースに連結します

Dim conn As String = GetConnectionString()Dim da As OleDbDataAdapter = New OleDbDataAdapter(select from products conn)Dim dt As DataTable = New DataTable(Products)daFill(dt)c1FlexGrid1DataSource = dt

Note that the above sample code uses a custom method named GetConnectionString to create a connection stringwith database

C

static string GetConnectionString() string path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) + ComponentOne SamplesCommon string conn = provider=microsoftjetoledb40data source=0c1nwindmdb return stringFormat(conn path)

VBNET

Private Shared Function GetConnectionString() As String Dim path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) amp

FlexGrid for WinForms

15 Copyright copy GrapeCity Inc All rights reserved

ComponentOne SamplesCommon Dim conn = provider=microsoftjetoledb40data source=0c1nwindmdb Return StringFormat(conn path)End Function

Configure the FlexGrid controlThis section walks you through the design-time and run-time steps to configure the grid with some basic settingsThese settings and features are explained in detail in the topics below

Configuring Grid at Design Time

Click smart tag to open the C1FlexGrid Tasks MenuClick the Styles option to open C1FlexGrid Styles EditorSelect Fixed from Built-in Styles pane customize some settings such as Backcolor Font and ForeColor andclick OKTo fit the grid to the form click the Dock in Parent Container optionFor customizing a column click the column (say Unit Price column) to open C1FlexGrid Column TasksMenuClick the ellipsis alongside Format field to open the Format String dialogSelect Currency as Format Type and click OK

Configuring Grid at Run Time

Add following code to configure the grid and its columns at run time

C

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = new Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols[6]Format = c

VBNET

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = New Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols(6)Format = c

FlexGrid for WinForms

16 Copyright copy GrapeCity Inc All rights reserved

This section demonstrates how to create a FlexGrid application in NET 5 by populating its data from a custom classYou can also use an external datasource to supply data to the grid as shown in NET 452 tab However note thatsome design-time steps given in the aforementioned tab may vary in case of NET 5 Similarly you can use belowsteps to bind FlexGrid to an internal datasource in NET 452

Set Up the Application1 Create a new Windows Forms app(NET Framework)2 Configure your project and set the Framework property3 Initialize the FlexGrid control and add it to the form

C

コントロールを初期化します

C1FlexGrid flexGrid = new C1FlexGrid() フォームにコントロールを追加します

thisControlsAdd(flexGrid)

VBNET

コントロールを初期化します

Dim flexGrid As C1FlexGrid = New C1FlexGrid() フォームにコントロールを追加します

MeControlsAdd(flexGrid)

Bind FlexGrid to a Data Source1 Create a custom class Product to be used as a data source

C

カスタムクラスProductを作成します

public class Product static Random _rnd = new Random()

NET 5

FlexGrid for WinForms

17 Copyright copy GrapeCity Inc All rights reserved

static string[] _names = Macko|Surfair|Pocohey|StudebySplit(|) static string[] _lines = Computers|Washers|Stoves|CarsSplit(|) static string[] _colors = Red|Green|Blue|WhiteSplit(|) public Product() Name = _names[_rndNext() _namesLength] Line = _lines[_rndNext() _linesLength] Color = _colors[_rndNext() _colorsLength] Price = 30 + _rndNextDouble() 1000 Cost = 3 + _rndNextDouble() 300 Discontinued = _rndNextDouble() lt 2 Introduced = DateTimeTodayAddDays(_rndNext(-600 0)) public string Name get set public string Color get set public string Line get set public double Price get set public double Cost get set public DateTime Introduced get set public bool Discontinued get set

VBNET

カスタムクラスProductを作成します

Public Class Product Private Shared _rnd As Random = New Random() Private Shared _names As String() = Macko|Surfair|Pocohey|StudebySplit(|c) Private Shared _lines As String() = Computers|Washers|Stoves|CarsSplit(|c) Private Shared _colors As String() = Red|Green|Blue|WhiteSplit(|c)

Public Sub New() Name = _names(_rnd[Next]() Mod _namesLength) Line = _lines(_rnd[Next]() Mod _linesLength) Color = _colors(_rnd[Next]() Mod _colorsLength) Price = 30 + _rndNextDouble() 1000 Cost = 3 + _rndNextDouble() 300 Discontinued = _rndNextDouble() lt 2 Introduced = DateTodayAddDays(_rnd[Next](-600 0)) End Sub

Public Property Name As String Public Property Color As String Public Property Line As String Public Property Price As Double Public Property Cost As Double Public Property Introduced As Date Public Property Discontinued As BooleanEnd Class

2 Initialize a list of type ProductC

Productがクラス型であるProduct型のリストを初期化します

ListltProductgt _products = new ListltProductgt()

FlexGrid for WinForms

18 Copyright copy GrapeCity Inc All rights reserved

VBNET

Productがクラス型であるProduct型のリストを初期化します

Dim _products As List(Of Product) = New List(Of Product)()

3 Initialize a For loop and add products to the list

C

forループを初期化し製品をリストに追加します

for (int i = 0 i lt100 i++) _productsAdd(new Product())

VBNET

forループを初期化し製品をリストに追加します

For i As Integer = 0 To 100 - 1 _productsAdd(New Product())Next

4 Bind FlexGrid to the created data sourceC

FlexGridにデータを連結します flexGridDataSource = _products

VBNET

FlexGridにデータを連結します flexGridDataSource = _products

Configure the FlexGrid controlAdd following code to configure the grid and its columns at run time

C

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = new Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols[6]Format = c

VBNET

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = New Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols(6)Format = c

FlexGrid for WinForms

19 Copyright copy GrapeCity Inc All rights reserved

設計時サポート

FlexGrid for WinForms comes with various design time options to make your programming tasks a lot easier In addition to smart tag context menu andproperty grid FlexGrid provides tasks menus and editors as well While C1FlexGrid Tasks menu lets you work on the entire grid in design time the ColumnTasks menu provides options to set some common properties for each column of the grid At the same time various editors such as C1FlexGrid ColumnEditor and C1FlexGrid Style Editor provide detailed properties to customize the columns and styles

This section discusses about various design-time options available in the FlexGrid control

Topic Snapshot Content

Tasks Menus Discusses about the C1FlexGrid Tasks menu the Column Tasks menu and their options

C1FlexGrid Tasks MenuC1FlexGrid Column Tasks Menu

Editors Discusses about the various editors and how to access them

C1FlexGrid Column EditorC1FlexGrid Style EditorCaption Style EditorColumn Style Editor

タスクメニュー

C1FlexGrid Tasks MenuC1FlexGrid Tasks menu provides you an easy access to the commonly used properties of FlexGrid It also providesoptions to open various editors such as C1FlexGrid Column Editor C1FlexGrid Style Editor

To access the C1FlexGrid Tasks menu click the smart tag ( ) in the upper right corner of the grid Following tableexplains various options available through the C1FlexGrid Tasks menu

Option Description

ChooseDataSource

The dropdown opens the list of available data sourcesand gives you Add Project Data Source option to openData Source Configuration Wizard

For more information on how to add a new data sourceto the project see Bound Mode

EnableAddingRows

The checkbox toggles the AllowAddNew propertywhich allows users to add new row to the grid at runtime When checked ON it displays a template row withstar at the bottom of the grid to enter the new record

EnableDeletingRows

The checkbox toggles the AllowDelete property whichallows users to delete the selected rows by pressing theDelete key

EnableEditing

The checkbox toggles the AllowEditing property whichallows users to edit the grid

Enable Column Reordering The checkbox sets the AllowDragging property toColumns which allows users to re-order the columns by draggingthe column headers

Enable Column Filtering The checkbox toggles the FlexGridAllowFiltering property to

FlexGrid for WinForms

20 Copyright copy GrapeCity Inc All rights reserved

enable or disable the filtering on grid columns

VisualStyle The dropdown lets you choose the built-in visual styles availablein the grid By default the value is set to Custom

Designer The option opens C1FlexGrid Column Editor which allows you toset the properties of each column of the grid

Styles The option opens C1FlexGrid Style Editor which allows youto customize the various pre-defined styles or create the newstyles at design time

Display Hidden Columns The checkbox lets you display or hide grid columns in the designview Note that this option is NOT associated with the run-timevisibility of columns Hence even if this checkbox is checked ONcolumns with Visible property set to False still remain hiddenwhen the application is run

Column Tasks The option switches the task menu to C1FlexGrid Column Tasksmenu which provides options to set the properties for theselected column

About C1FlexGrid The option displays a dialog box displaying the information suchas version of the FlexGrid control

Dock in Parent Container This option sets the Dock property of the grid to Fill which resizesthe grid to occupy the whole form space Clicking the option alsoswitches the text and provides option to Undock in ParentContainer which restores the grid to its original size

C1FlexGrid Column Tasks MenuC1FlexGrid Column Tasks menu provides you an easy access to the commonly used properties of grid columns Italso provides options to open editors named Caption Style and Column Style

To access the C1FlexGrid Column Tasks menu double-click header of the column to be configured at design-timeAnother way to open C1FlexGrid Column Tasks menu is to click on the smart tag ( ) in the upper right corner of thegrid and then navigate to the Column Tasks option Following table explains various options available through theC1FlexGrid Column Tasks menu

FlexGrid for WinForms

21 Copyright copy GrapeCity Inc All rights reserved

Option Description

ColumnCaption

The field allows you to specify the value of Captionproperty which sets text in header cell of the column

DataField

The dropdown opens a list of available fields in the datasource to choose from and sets value of Name property ofthe column

DataType

The dropdown opens a list of available data types and letsyou set the data type of the selected column This fieldcorresponds to the DataType property of the column

EditMask

The field lets you specify value of EditMask property whichsets mask for the selected column The ellipsis button onthe right side of the field opens the Input Mask dialog boxwhere you can select from the list of pre-defined masks

FormatString

The field lets you specify the value of Format propertywhich sets format string to display data value from source

ComboList

The field lets you specify the list of multiple values fromwhich user can choose The ellipsis button on the right sideof the field lets you open the Combo List dialog box whereyou can specify the value options

Allow Sorting The checkbox toggles the AllowSorting property to enable ordisable sorting in the column By default sorting is enabled for allcolumns

Allow Editing The checkbox toggles the AllowEditing property to make thecolumn read-only or editable By default editing is enabled for allcolumns

Allow Resizing The checkbox toggles the AllowResizing property which allows usersto adjust the size of column at run time By default resizing isenabled for all columns

Allow Dragging The checkbox toggles the AllowDragging property to enable ordisable re-ordering of the column at run time By default dragging isenabled for all columns

Allow Merging The checkbox toggles the AllowMerging property to enable ordisable merging two adjacent column cells having same values Bydefault merging is disabled for all columns

Allow Filtering The dropdown lets you specify the value of ColumnAllowFilteringproperty and choose the type of filter for each column The availableoptions are Default ByValue ByCondition Custom or None

Visible The checkbox lets you set the visibility of the column in the grid atrun time by toggling value of its Visible property

FlexGrid for WinForms

22 Copyright copy GrapeCity Inc All rights reserved

Caption Style The option opens the Caption Style editor which gives you options tostyle the text alignment background and border for the header cellof column

Column Style The option opens the Column Style editor which gives you options tostyle the text alignment background and border for the column text

C1FlexGrid Tasks The option switches the task menu to C1FlexGrid Tasks menu whichprovides options to set the properties for the entire grid

Dock in Parent Container The option sets the Dock property of the grid to Fill which resizes thegrid to occupy the whole form Clicking the option also switches thetext and provides option to Undock in Parent Container whichrestores the grid to its original size by setting the Dock property toNone

エディタ

Apart from the tasks menu FlexGrid also provides various editors that help you set a number of properties related togrid its columns and their styles

C1FlexGrid Column EditorFlexGrid provides the C1FlexGrid Column Editor making it easy to work with columns at design-time instead ofwriting code The editor lets you set various properties related to columns such as Caption DataTypeAllowFiltering and AllowMerging through its property pane on left hand side Toolbar on the top of this editorgives you options such as reloading data from the data source adding removing and resizing columns You can evenstyle the column text using the options given in this toolbar For further customization of column text you can usethe Column Style editor to access more specific properties

FlexGrid for WinForms

23 Copyright copy GrapeCity Inc All rights reserved

There are three ways in which you can access the C1FlexGrid Column Editor at design time

Smart Tag Click the smart tag ( ) in the upper right corner of the grid and select Designer from theC1FlexGrid Tasks menuProperty Window Select the grid go to the Properties window and click the ellipsis button (hellip) next to theCols propertyContext Menu Right-click the grid and select Designer from the context menu

C1FlexGrid Style EditorFlexGrid provides the C1FlexGrid Style editor which lets you style the grid at design time by customizing the built-instyles and creating the new ones The editor offers a list of styles for specific types of cell on left hand side and aproperty window on right hand side to customize these styles The list of styles is divided into two sections thedefault Built-in Styles and Custom Styles Towards the bottom there are Add and Remove buttons to add anddelete the custom styles and a Clear button to revert the editor to default settings The AutoFormat button in theend opens a secondary dialog C1FlexGrid Auto Format which lists the pre-defined set of styles and also shows apreview in the Preview pane

FlexGrid for WinForms

24 Copyright copy GrapeCity Inc All rights reserved

There are three ways in which you can access the C1FlexGrid Style Editor at design-time

Smart Tag Click the smart tag ( ) in the upper right corner of the grid and select Styles from theC1FlexGrid Tasks menuProperty Window Select the grid go to the Properties window and click the ellipsis button (hellip) next to theStyles propertyContext Menu Right-click the grid and select Styles from the context menu

Caption Style EditorFlexGrid provides the Caption Style editor which allows you to set styling related properties of the column header celland its text The editor comprises of four tabs Text Alignment Border and Background for customizing variousaspects of the header cells

To access the Caption Style editor click smart tag ( ) click the C1FlexGrid Column Tasks option on the task menu toopen column tasks and then go to Caption Style option

FlexGrid for WinForms

25 Copyright copy GrapeCity Inc All rights reserved

Column Style EditorSimilar to Caption Style editor FlexGrid provides another editor the Column Style editor for styling the column textThe editor has got the same options as that of Caption Style editor The only difference is that Caption Style editorcustomizes the column header text while this editor works on the general text in the column cells

To access the Column Style editor click smart tag ( ) click the C1FlexGrid Column Tasks option on the task menu toopen column tasks and then go to Column Style option

FlexGrid for WinForms

26 Copyright copy GrapeCity Inc All rights reserved

データ

This section discusses about various ways to populate data in the FlexGrid control

Topic Snapshot Content

Unbound Mode Discusses how to populate data in the unbound grid

Bound Mode Discusses ways of populating data in the grid through data binding and various operations on bound grid

Binding at design timeBinding at run time using DataSource propertyBinding at run time using SetDataBinding methodOperations in Bound Mode

非連結モード

As the name suggests in unbound mode grid is not bound to any data source and data is stored in the control itselfIn this case you need to provide data by adding rows and columns either at design time or programmatically throughrow and column collections You can also create an empty grid to let user enter the data

An unbound grid is not a very common scenario as grid does not store the data and hence user needs to manage itmanually However unbound grids suits better to some business scenarios like creation and maintenance of recordsFor instance you can use the grid in unbound mode for recording the date-wise sales data or to maintain the dailyinventory changes Below example demonstrates a grid with data populated through code

In C1FlexGrid you can add empty rows or columns by setting the Count property of row or column objects Also youcan use the Add method of these collections to add the empty rows and columns to a grid To set data in the cellsyou can either use the familiar index notation(Item property) or the SetData method For more information on settingdata in the cells see Storing and Retrieving Data

Use the code below to populate data in unbound FlexGrid for WinForms

連結されていない列を追加しますColumn col = _flexColsAdd()colName = colCaption = Unbound_flex[1 Unbound] = 123

C

連結されていない列を追加しますDim col As Column = C1FlexGrid1ColsAdd()colName = UnboundcolCaption = Unbound

VBNET

FlexGrid for WinForms

27 Copyright copy GrapeCity Inc All rights reserved

連結モード

Bound mode as the name suggests refers to a state where grid fetches its data from an underlying data source Databinding also allows multiple data consumers to be connected to a data provider in the synchronized manner

FlexGrid supports data binding to most of the commonly used data sources such as ObservableCollection IListltTgtListltTgt Array BindingSource ADONET objects such as DataSet DataTable etc

There are three ways of binding FlexGrid to a data source

Binding at design timeBinding at run time using DataSource propertyBinding at run time using SetDataBinding method

Binding at Design Time1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Click the Choose Data Source drop down button and select Add Project Data Source option to open the

Data Source Configuration Wizard3 On Choose a Data Source Type page select Database and click Next4 On Choose a Database Model page select Dataset and click Next5 On Choose Your Data Connection page click New Connection to open the Add Connection dialog6 Against the DataSource field click Change button to open the Change Data Source dialog7 Select Microsoft Access Database File and click OK to return to the Add Connection dialog8 Against the Database file name field click Browse and navigate to the database file Provide the User name

and Password if required to connect to the database file This example uses C1NWindmdb file located at thefollowing location by defaultDocumentsComponentOne SamplesCommon

FlexGrid for WinForms

28 Copyright copy GrapeCity Inc All rights reserved

9 Click Test Connection to make sure that you have successfully connected to the database or server and clickOK

10 Click OK again to close the Add Connection dialog box11 Click Next 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 Choose the appropriate option as per your requirement12 Save the connection string in the application configuration file by checking the Yes save the connection as

box and entering a name13 Click Next to switch to the Choose Your Database Objects page14 Choose a table say Products from the Tables node and click Finish15 The above steps add a dataset and connection string to your project Also Visual Studio automatically creates

the following code to fill the dataset

Binding at Run Time Using DataSource PropertyFlexGrid provides the DataSource property to bind the FlexGrid control to a data source at run time You need toassign a data source object to the DataSource property of FlexGrid If the data source object contains more than onetable you can set the DataMember property to table name to specify the target table

Following code uses DataSource property to bind data to the WinForms FlexGrid

Note that the above sample code uses a custom method named GetData to supply data You can set up the datasource as per your requirements Following code shows an example of creating data for WinForms FlexGrid

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移動または削除できます thisproductsTableAdapterFill(thisc1NWindDataSetProducts)

C

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移動または削除できます MeProductsTableAdapterFill(Mec1NWindDataSetProducts)

VBNET

c1FlexGrid1BeginUpdate()C1DataCollectionltCustomergt c1DataCollection = new C1DataCollectionltCustomergt(GetData())c1FlexGrid1DataSource = new C1DataCollectionBindingList(c1DataCollection)c1FlexGrid1EndUpdate()

C

c1FlexGrid1BeginUpdate()Dim c1CollectionView As C1DataCollectionC1DataCollection(Of Customer) = New C1DataCollectionC1DataCollection(Of Customer)(GetData())c1FlexGrid1DataSource = New C1DataCollectionBindingListC1DataCollectionBindingList(c1CollectionView)c1FlexGrid1EndUpdate()

VBNET

ObservableCollectionltCustomergt GetData() var data = new ObservableCollectionltCustomergt() for (int i = 0 i lt 25 i++)

C

FlexGrid for WinForms

29 Copyright copy GrapeCity Inc All rights reserved

Binding at Run Time Using SetDataBinding MethodFlexGrid also provides the SetDataBinding method using which you can set DataSource and DataMember propertiesboth using a single call The following code demonstrates an example of rendering a parent table and its child tablesin different grids with the help of the SetDataBinding method

Below code demonstrates how to bind data to WinForms FlexGrid using SetDataBinding method

dataAdd(new Customer()) return data

Private Function GetData() As ObservableCollection(Of Customer) Dim data = New ObservableCollection(Of Customer)()

For i = 0 To 25 - 1 dataAdd(New Customer()) Next

Return dataEnd Function

VBNET

グリッドにデータセットを連結します_flexCustomersBeginUpdate()_flexCustomersSetDataBinding(ds Customers)_flexCustomersEndUpdate()

_flexOrdersBeginUpdate()_flexOrdersSetDataBinding(ds CustomersCustomerOrders)_flexOrdersEndUpdate()

_flexOrderDetailsBeginUpdate()_flexOrderDetailsSetDataBinding(ds CustomersCustomerOrdersOrderDetails)_flexOrderDetailsEndUpdate()

C

グリッドにデータセットを連結します_flexCustomersBeginUpdate()_flexCustomersSetDataBinding(ds Customers)_flexCustomersEndUpdate() _flexOrdersBeginUpdate()_flexOrdersSetDataBinding(ds CustomersCustomerOrders)_flexOrdersEndUpdate() _flexOrderDetailsBeginUpdate()_flexOrderDetailsSetDataBinding(ds CustomersCustomerOrdersOrderDetails)_flexOrderDetailsEndUpdate()

VBNET

連結モードでの操作

Adding Unbound Column in Bound ModeIn the bound mode grid fetches the data from data source and display it as records and bound columns To add a column to

FlexGrid for WinForms

30 Copyright copy GrapeCity Inc All rights reserved

display data that does not exist in the data source you need to add unbound columns at design time or through code

Adding unbound column at design time

1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Bind the grid control with a data source For detailed steps about how to bind FlexGrid to a data source see Bound

Mode3 Click the Designer option to open the C1FlexGrid Column Editor4 In the right hand side pane select an existing column from the grid preview5 Click Insert Column options in the toolbar to add a column before or after the selection

Adding unbound column through code

FlexGrid provides Add Insert and InsertRange method of the ColumnCollection class to add an unbound column to the gridWhile Add method adds a column at the end the Insert method lets you specify the position where you want to add a newcolumn Similarly you can add multiple columns at a specified position by using the InsertRange method

Use the code below to add unbound column in a bound WinForms FlexGrid

連結されていない列を追加しますColumn col = _flexColsAdd()colName = colCaption = Unbound_flex[1 Unbound] = 123

C

連結されていない列を追加しますDim col As Column = C1FlexGrid1ColsAdd()colName = UnboundcolCaption = Unbound

VBNET

FlexGrid for WinForms

31 Copyright copy GrapeCity Inc All rights reserved

Set Values in Unbound ColumnTo define values in the unbound column of bound grid you need to usethe SetUnboundValue and GetUnboundValue events of the C1FlexGrid class First create a hash table to store the enteredvalues then use the SetUnboundValue event to set unbound value in the hash table using a unique key to identify therecord and use GetUnboundValue event to get the value stored in the hash table using its unique key and set unboundvalue to be displayed in the cell

Following code shows how to set values in an unbound column added to a bound WinForms FlexGrid

Displaying Data in Fixed ColumnTo set values in the fixed columns you need to set DrawMode property of the C1FlexGrid class to OwnerDraw in the formload event and then create the OwnerDrawCell event to set values in the fixed column cells In this example we are settingrow numbers in the fixed column of a bound WinForms FlexGrid

get value from hashtable using ProductID as keyvoid _flex_GetUnboundValue(object sender C1WinC1FlexGridUnboundValueEventArgs e) DataRowView drv = (DataRowView)_flexRows[eRow]DataSource eValue = _hash[drv[ProductID]]

store value in hashtable using ProductID as keyvoid _flex_SetUnboundValue(object sender C1WinC1FlexGridUnboundValueEventArgs e) DataRowView drv = (DataRowView)_flexRows[eRow]DataSource _hash[drv[ProductID]] = eValue

C

Private Sub C1FlexGrid1_GetUnboundValue(sender As Object e As C1WinC1FlexGridUnboundValueEventArgs) Handles C1FlexGrid1GetUnboundValue Dim drv As DataRowView = DirectCast(C1FlexGrid1Rows(eRow)DataSource DataRowView) eValue = _hash(drv(ProductID))End Sub

Private Sub C1FlexGrid1_SetUnboundValue(sender As Object e As C1WinC1FlexGridUnboundValueEventArgs) Handles C1FlexGrid1SetUnboundValue Dim drv As DataRowView = DirectCast(C1FlexGrid1Rows(eRow)DataSource DataRowView) _hash(drv(ProductID)) = eValueEnd Sub

VBNET

FlexGrid for WinForms

32 Copyright copy GrapeCity Inc All rights reserved

Auto-adjust Column WidthFlexGrid provides AutoResize property of the C1FlexGrid class to adjust the width of columns automatically according tothe text length You need to set the property to true before binding it to the data source to load the grid with appropriatecolumn width You can also call AutoSizeCol method to adjust the width of the specified column

Use the code below auto-adjust the column width according to the text in WinForms FlexGrid

Display Bitmap Image in FieldIn most of the scenarios grid directly fetches the images from the data source However if the grid is bound to a databasewhich stores images as OLE objects such as Microsoft Access a little bit of extra processing is required to fetch bitmapimages In such case you need to convert the image data stored as byte array to a memory stream and then usethe OwnerDrawCell event to load the image In the form load event you need to set the DrawMode property toOwnerDraw Also adjust the height of row to display the image properly

Following code demonstrates how to display bitmap image in fields of WinForms FlexGrid

private void C1FlexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if ((eRow gt= thisc1FlexGrid1RowsFixed) amp (eCol == (thisc1FlexGrid1ColsFixed - 1))) eText = eRowToString() または任意のテキスト

C

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If eRow gt= Mec1FlexGrid1RowsFixed And eCol Is Mec1FlexGrid1ColsFixed - 1 Then eText = eRowToString() または任意のテキスト End IfEnd Sub

VBNET

すべての列の幅を自動的に調整します c1FlexGrid1AutoResize = true

4列目の幅を自動調整します c1FlexGrid1AutoSizeColumns(3)

C

すべての列の幅を自動的に調整します c1FlexGrid1AutoResize = True

4列目の幅を自動調整します c1FlexGrid1AutoSizeColumns(3)

VBNET

private void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) if(eMeasuring ampamp eRowgt=c1FlexGrid1RowsFixed ampamp eCol gt=

C

FlexGrid for WinForms

33 Copyright copy GrapeCity Inc All rights reserved

Note that the above sample code uses a custom method LoadImage method to convert the images from byte array to amemory stream

c1FlexGrid1ColsFixed) 「Photo」はblob(byte [])に保存された画像です if (c1FlexGrid1Cols[eCol]Name == Picture) mdbからロードしてみてください eImage = LoadImage(c1FlexGrid1[eRow eCol] as byte[])

画像が表示された場合はテキストを入力しないでください if (eImage = null) eText = null

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) If Not eMeasuring AndAlso eRow gt= c1FlexGrid1RowsFixed AndAlso eCol gt= c1FlexGrid1ColsFixed Then

「Photo」はblob(byte [])に保存された画像です If c1FlexGrid1Cols(eCol)Name Is Picture Then mdbからロードしてみてください eImage = LoadImage(TryCast(c1FlexGrid1(eRow eCol) Byte()))

画像が表示された場合はテキストを入力しないでください If eImage IsNot Nothing Then eText = Nothing End If End IfEnd Sub

VBNET

Image LoadImage(byte[] picData) static Image LoadImage(byte[] picData) これが埋め込みオブジェクトであることを確認してください const int bmData = 78 if (picData == null || picDataLength lt bmData + 2) return null if (picData[0] = 0x15 || picData[1] = 0x1c) return null

現在点ではビットマップのみを処理します if (picData[bmData] = B || picData[bmData + 1] = M) return null

画像をロードします Image img = null try MemoryStream ms = new MemoryStream(picData bmData picDataLength - bmData) img = ImageFromStream(ms) catch

画像を返します return img

C

Private Function LoadImageMethod(ByVal picData As Byte()) As Image

VBNET

FlexGrid for WinForms

34 Copyright copy GrapeCity Inc All rights reserved

Private Shared Function LoadImage(ByVal picData As Byte()) As Image これが埋め込みオブジェクトであることを確認してください Const bmData As Integer = 78 If picData Is Nothing OrElse picDataLength lt bmData + 2 Then Return Nothing If picData(0) ltgt ampH15 OrElse picData(1) ltgt ampH1c Then Return Nothing

現在点ではビットマップのみを処理します If picData(bmData) ltgt Bc OrElse picData(bmData + 1) ltgt Mc Then Return Nothing

画像をロードします Dim img As Image = Nothing

Try Dim ms As MemoryStream = New MemoryStream(picData bmData picDataLength - bmData) img = ImageFromStream(ms) Catch End Try

画像を返します Return imgEnd Function

FlexGrid for WinForms

35 Copyright copy GrapeCity Inc All rights reserved

A grid control is a collection of rows and columns Columns generally contain a particular type of information through out while rows are used to recorddifferent types of information about a particular item

In FlexGrid the collection of columns is represented by the ColumnCollection class which can be accessed through Cols property of the C1FlexGrid class Thissection discusses the various operations that can be performed on columns

Topic Snapshot Content

BasicOperations

Discusses about how to perform basic column operations

Set Column CountAdd ColumnDelete ColumnInsert ColumnSet Data TypeSet Fixed ColumnSet Frozen Column

UserInteraction

Discusses about operations that can be performed by the end user at run time

Allow EditingAllow DraggingAllow FreezingAllow SortingAllow FilteringAllow Resizing

Editors Discusses about various built-in editors of FlexGrid and operations related to them Also discusses how to use customeditors in the FlexGrid

CheckBoxNumericDateComboBoxMaskMapped ListCell Button

Validation Discusses how to apply validation and show error information on FlexGrid cells

Sparkline Discusses about how to display Sparkline charts in FlexGrid cells

Header andFooter

Discusses about how to set column header and footer

Set Header TextMerge column headerWrap column header textStyle Column HeaderSet Column Footer

Sizing Discusses about various aspects of column sizing

Set Column WidthAuto-adjust Column WidthSet MinMax Column WidthStar Sizing

基本操作

This topic discusses various basic operations which can be performed on a column

FlexGrid for WinForms

36 Copyright copy GrapeCity Inc All rights reserved

Set Column CountWhen grid is bound to a data source the number of columns is determined by the number of fields available in thedata source However in the case of unbound mode you can set any arbitrary value in the Count property ofthe ColumnCollection class to set the number of columns to be displayed in the grid

Use the code below to set the number of columns to be added to WinForms FlexGrid in unbound mode

Add ColumnFlexGrid provides two ways to add a new column using the ColumnCollection class You can either use Add methodor increment the value of Count property provided by the class to add new columns Also note that if a new columnis added to a bound grid using these methods it is added as an unbound column only

Following are the two approaches to add column to a WinForms FlexGrid

Delete ColumnTo delete a particular column from the grid you can use Remove method of the ColumnCollection class and specifythe column you want to delete as its parameter In the unbound grid you can also reduce the number of columns bychanging the value of Count property This removes columns from the end of the column collection TheColumnCollection class also provides RemoveRange method which allows you to remove a range of columns

列数を設定します c1FlexGrid1ColsCount = 4

C

列数を設定しますc1FlexGrid1ColsCount = 4

VBNET

方法1 列コレクションのAddメソッドを使用します C1WinC1FlexGridColumn c c = c1FlexGrid1ColsAdd() cCaption = New Column

方法2 列コレクションのCountプロパティを変更します c1FlexGrid1ColsCount += 1 c1FlexGrid1Cols[c1FlexGrid1ColsCount - 1]Caption = New Column

C

方法1 列コレクションのAddメソッドを使用します Dim c As C1WinC1FlexGridColumn c = c1FlexGrid1ColsAdd() cCaption = New Column

方法2 列コレクションのCountプロパティを変更します c1FlexGrid1ColsCount += 1 c1FlexGrid1Cols(c1FlexGrid1ColsCount - 1)Caption = New Column

VBNET

FlexGrid for WinForms

37 Copyright copy GrapeCity Inc All rights reserved

Below code snippet shows all the three approaches to delete column from the WinForms FlexGrid

Insert ColumnTo insert a column in FlexGrid at a specific location you can use Insert method of the ColumnCollection class whichlets you specify the position where columns are to be inserted You can also insert multiple columns in the grid byusing the InsertRange method These methods add the unbound columns only even if the grid is a bound grid

Use any of the following approaches to insert a column in the WinForms FlexGrid at the specified location

方法1 列コレクションのRemoveメソッドを使用して2番目の列を削除します c1FlexGrid1ColsRemove(2)

方法2 Countプロパティを変更して最後の列を削除します c1FlexGrid1ColsCount -= 1

方法3 RemoveRangeメソッドを使用して2番目から始まる4つの列を削除します c1FlexGrid1ColsRemoveRange(2 4)

C

方法1 列コレクションのRemoveメソッドを使用して2番目の列を削除します c1FlexGrid1ColsRemove(2)

方法2 Countプロパティを変更して最後の列を削除します c1FlexGrid1ColsCount -= 1

方法3 RemoveRangeメソッドを使用して2番目から始まる4つの列を削除します c1FlexGrid1ColsRemoveRange(2 4)

VBNET

C1WinC1FlexGridColumn c

方法1 Insertメソッドを使用して2番目の位置に列を挿入します c = c1FlexGrid1ColsInsert(2) cCaption = Inserted Column

方法2 InsertRangeメソッドを使用して2番目の位置に3つの列を挿入します c1FlexGrid1ColsInsertRange(2 3)

C

Dim c As C1WinC1FlexGridColumn 方法1 Insertメソッドを使用して2番目の位置に列を挿入します c = c1FlexGrid1ColsInsert(2) cCaption = Inserted Column 方法2 InsertRangeメソッドを使用して2番目の位置に3つの列を挿入します c1FlexGrid1ColsInsertRange(2 3)

VBNET

FlexGrid for WinForms

38 Copyright copy GrapeCity Inc All rights reserved

Set Data TypeIn case of a bound FlexGrid data type of each bound column is automatically picked from the data source dependingon the data However in the case of unbound mode you can set the data type of columns by specifyingthe DataType property of Column class You can also set the Data Type property at design time by using theColumn Tasks menu For more information on tasks menus see Tasks Menus Note that when a particular data type isset to a FlexGrid column its cells accept the user input of keys accepted by the data type only For instance you cannot input alphabets in a Numeric type cell

Set the data type of an unbound column in WinForms FlexGrid as shown in the code below

Set Fixed ColumnFixed columns refer to the columns with non-editable cells which are always visible in the left hand side of the grideven if user scrolls the grid horizontally In FlexGrid fixed columns can be set using Fixed property ofthe ColumnCollection class This property accepts an integer value that specifies the number of columns to be fixed

Use the code below to set one column as fixed in the WinForms FlexGrid

Set Frozen ColumnFrozen columns similar to fixed columns are non-scrollable but can be edited by the user In FlexGrid frozen columnscan be set by using Frozen property provided by the ColumnCollection class

To set frozen columns in the WinForms FlexGrid use the code below

最初の列のデータ型を設定します c1FlexGrid1Cols[1]DataType = typeof(int)

C

最初の列のデータ型を設定しますc1FlexGrid1Cols(1)DataType = GetType(Integer)

VBNET

1つの列を固定列として設定しますc1FlexGrid1ColsFixed = 1

C

1つの列を固定列として設定しますc1FlexGrid1ColsFixed = 1

VBNET

最初の4列を静止として設定しますc1FlexGrid1ColsFrozen = 4

C

最初の4列を静止として設定しますc1FlexGrid1ColsFrozen = 4

VBNET

FlexGrid for WinForms

39 Copyright copy GrapeCity Inc All rights reserved

ユーザー操作

This topic discusses how you can let end users interact with the FlexGrid columns

Allow EditingBy default FlexGrid allows to edit all columns of the grid However you can choose to disable editing of a particularcolumn by setting AllowEditing property of the Column object to false You can also disable editing of the whole gridby setting the C1FlexGridAllowEditing property to false For more information on editing see Edit

Following code shows how to disable editing of WinForms FlexGrid while keeping only one column editable

Allow DraggingFlexGrid by default allows user to reorder columns by dragging a column header and dropping it to the targetposition However you can change this behavior by using the FlexGridAllowDragging propertyand ColumnAllowDragging property To disable dragging of a particular column you can set theColumnAllowDragging property of that column to false On the other hand setting the FlexGridAllowDraggingproperty to either Rows or None disables the column reordering at grid level This property accepts the valuesfrom AllowDraggingEnum You can also disable column reordering at design time by checking off the Enable ColumnReordering checkbox in the C1FlexGrid Tasks menu For more information on tasks menus see Tasks Menus

グリッド全体で編集を無効にしますc1FlexGrid1AllowEditing = false

3列目でのみ編集を有効にしますc1FlexGrid1Cols[3]AllowEditing = true

C

グリッド全体で編集を無効にしますc1FlexGrid1AllowEditing = False

3列目でのみ編集を有効にしますc1FlexGrid1Cols(3)AllowEditing = True

VBNET

FlexGrid for WinForms

40 Copyright copy GrapeCity Inc All rights reserved

Below code demonstrates how to enable dragging of columns in WinForms FlexGrid

Allow FreezingTo allow end user to freeze the columns at runtime you can use the AllowFreezing property of the C1FlexGrid classwhich accepts values from AllowFreezingEnum When this property is set to Columns or Both a lock sign appearswhen mouse is hovered over the edge of header column User can click and drag the lock sign to freeze the columns

Following code shows how to allow users to freeze the columns in WinForms FlexGrid

Allow PinningFlexGrid lets you allow your users to pin a particular column or column range at run time by using the AllowPinningproperty of the C1FlexGrid class Setting the property adds a Pin button( ) in the column header which allows usersto pin columns at run-time so they remain in view as the user scrolls the grid horizontally The property accepts itsvalues from AllowPinning enumeration which lets you set pinning for a single column or a column range Whenproperty is set to ColumnRange user can pin or unpin all the columns starting from left till the clicked column in onego

グリッド全体ですべての列のドラッグを許可します c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumColumns

特定の列のドラッグを無効にしますc1FlexGrid1Cols[3]AllowDragging = false

C

グリッド全体ですべての列のドラッグを許可します c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumColumns

特定の列のドラッグを無効にします c1FlexGrid1Cols(3)AllowDragging = False

VBNET

実行時に列のフリーズを許可します c1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumColumns

C

実行時に列のフリーズを許可しますc1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumColumns

VBNET

FlexGrid for WinForms

41 Copyright copy GrapeCity Inc All rights reserved

Use the code below to let user pin multiple columns in the WinForms FlexGrid

Allow SortingIn FlexGrid column sorting is enabled for the whole grid by default and value of AllowSorting property of theC1FlexGrid class is set to Auto In this mode user can sort a single column by clicking the column header andmultiple columns by holding the CTRL key while clicking the column headers On sorting multiple columns the gridshows sort index in the column header next to the sort direction glyph You can also choose to prevent sorting orsimply change the way the columns are sorted through AllowSortingEnum enumeration The AllowSortingEnumenumeration allows you to choose whether to auto sort columns sort single column multiple columns or columnrange or just prevent sorting

You can enable multi-column sorting in the WinForms FlexGrid using the code below When AllowSorting propertyis set to MultiColumn user may sort multiple columns by simply clicking on their headers one after the other

ユーザーが列範囲を固定できるようにしますc1FlexGrid1AllowPinning = C1WinC1FlexGridAllowPinningColumnRange

C

ユーザーが列範囲を固定できるようにしますc1FlexGrid1AllowPinning = C1WinC1FlexGridAllowPinningColumnRange

VBNET

グリッドで複数列の並べ替えを有効にしますc1FlexGrid1AllowSorting = C1WinC1FlexGridAllowSortingEnumMultiColumn

1列のみの並べ替えを無効にしますc1FlexGrid1Cols[1]AllowSorting = false

C

グリッドで複数列の並べ替えを有効にしますc1FlexGrid1AllowSorting = C1WinC1FlexGridAllowSortingEnumMultiColumn

1列のみの並べ替えを無効にしますc1FlexGrid1Cols(1)AllowSorting = False

VBNET

FlexGrid for WinForms

42 Copyright copy GrapeCity Inc All rights reserved

To disable sorting on a particular column you need to set the ColumnAllowSorting property of that column to falseFor more information on sorting see Sort

Allow FilteringFlexGrid doesnt allow filtering at runtime by default However you can enable it by settingthe C1FlexGridAllowFiltering property to true To define the type of filter you want to apply on a particularcolumn you can use the ColumnAllowFiltering property which accepts following values from the AllowFilteringenumeration

AllowFiltering Values Description

Default The grid automatically creates a filter of type ColumnFilter This filteris the combination of a value filter and a condition filter

ByValue The grid automatically creates a filter of type ValueFilter This filteroffers a checkbox list of values to choose from Values that are notchecked in the list are excluded from the filter output

ByCondition The grid automatically creates a filter of type ConditionFilter Thisfilter provides several options such as Equals is Greater thanContains Begins with etc to create conditions You can also combinetwo conditions by using the And and Or operators available in thefilter

Custom The grid does not create a filter automatically and allows you to defineyour own filter and then explicitly assign it to Filter property of theColumn class

None Filtering is disabled for the column

For more information on filtering see Filter

Following code shows how to enable filtering in the WinForms FlexGrid and how to apply filters

Allow ResizingBy default FlexGrid allows resizing of all columns of the grid To change this behavior you can use AllowResizingproperty of the C1FlexGrid class This property accepts values from the AllowResizingEnum enumeration which letsyou resize columns rows both or none The enumeration also gives you options to uniformly resize the rows columnsor both that is if you resize one of the columns or rows the grid automatically resizes rest of the columns or rows as

グリッドレベルでのフィルタリングを許可します c1FlexGrid1AllowFiltering = true

最初の列に条件フィルターを適用します c1FlexGrid1Cols[1]AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

C

グリッドレベルでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = True

最初の列に条件フィルターを適用しますc1FlexGrid1Cols(1)AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

VBNET

FlexGrid for WinForms

43 Copyright copy GrapeCity Inc All rights reserved

well FlexGrid also provides ColumnAllowResizing property which is a Boolean type property and lets you enable ordisable resizing of a particular row or column

Below code shows how to allow users to resize columns of WinForms FlexGrid

Enable Context MenuFlexGrid provides support for column context menu at run-time to facilitate quick actions related to columnoperations To enable the column context menu on right-click you need to set ColumnContextMenuEnabled propertyprovided by the C1FlexGrid class to true By default this property is set to false

The column context menu provides following options

Option Description

Sort Ascending Sorts the column in ascending order

Sort Descending Sorts the column in descending order

Group by This Groups the grid data based on column under mouse pointer

列と行のサイズを均一に変更できますc1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumBoth

最初の列のサイズ変更のみを無効にしますc1FlexGrid1Cols[1]AllowResizing = false

C

列と行のサイズを均一に変更できますc1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumBoth

最初の列のサイズ変更のみを無効にしますc1FlexGrid1Cols(1)AllowResizing = False

VBNET

FlexGrid for WinForms

44 Copyright copy GrapeCity Inc All rights reserved

Column

Ungroup Removes grouping from the grid data The option displays only when grid is in groupedstate

Hide this Column Hides the column under mouse pointer

Auto size Resizes the column according to the length of longest value

Auto size (allcolumns)

Resizes all columns according to the length of longest value in each of them

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = true

C

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = True

VBNET

Option Description

エディタ

This topic discusses various built-in editors of FlexGrid and operations related to them The topic also takes you through thesteps to apply custom editors in the FlexGrid columns

Built-in EditorsFlexGrid provides several built-in editors to enable efficient in-cell editing The grid uses TextBox control as its default editorHowever other built-in editors such as numeric date checkbox and combo box are also supported These editors areautomatically assigned generally based on the value of some specific properties such as DataType property of the column Thetable below summarizes the built-in editors provided by FlexGrid their brief description and the example codes demonstratingthem For more information about built-in editors and their customization click the corresponding hyperlink

Built-inEditor

Snapshot Description Sample Code

Checkbox Gets enabledautomatically whenDataType propertyof the Columnobject is set to

c1FlexGrid1Cols[colIndex]DataType =

typeof(Boolean)

FlexGrid for WinForms

45 Copyright copy GrapeCity Inc All rights reserved

Boolean

Numeric Gets enabledautomatically whenDataType propertyis set to a numericdata type such asInt or Decimal

c1FlexGrid1Cols[colIndex]DataType =

typeof(Int32)

Date Gets enabledautomatically if theDataType propertyof column is set toDate or DateTime

c1FlexGrid1Cols[colIndex]DataType =

typeof(DateTime)

ComboBox Gets enabled bysetting multiplevalues separated bypipe inthe ComboListproperty

c1FlexGrid1Cols[colIndex]ComboList =

Red|Green|Blue|Red|White

Mask Gets enabled whenthe EditMaskproperty of columnis set

c1FlexGrid1Cols[colIndex]EditMask =

(999) 999-9999

Mappedlist

Gets enabled whenthe DataMapproperty is set to anIDictionary objectwhich establishesmapping betweenvalues stored in thegrid and thosevisible to a user

ListDictionary customerNames = new

ListDictionary()

customerNamesAdd(AJK18F Sam

Anders)

customerNamesAdd(BBK21D Daneil)

customerNamesAdd(AEF25N Henry

Hussain)

customerNamesAdd(BZD42S Owen

Romanov)

customerNamesAdd(AKC16G Serena

Nguyen)

c1flexGrid1Cols[Name]DataMap =

customerNames

c1flexGrid1ShowButtons =

ShowButtonsEnumWithFocus

Cell Button Gets enabled whenthe ComboListproperty is set to anellipsis() whichautomaticallydisplays a cellbutton in editmode You can then

c1flexGrid1Cols[colIndex]ComboList

=

c1flexGrid1CellButtonClick +=

C1flexGrid1_CellButtonClick

FlexGrid for WinForms

46 Copyright copy GrapeCity Inc All rights reserved

capturethe CellButtonClickevent either toshow a dialog boxor to perform anyother operation

Custom EditorsFlexGrid control provides most of the commonly used editing options through the above-mentioned built-in editors However inaddition you can also use external controls as editors to meet the specialized editing needs Any control that derives from thebase Control class can be easily used as an editor This can be done at design time as well as through code In the examplebelow we are setting the C1ColorPicker control as a cell editor

At Design Time

1 Add the C1FlexGrid control and C1ColorPicker control to the form2 Select Designer option from the C1FlexGrid Tasks menu to open the C1FlexGrid Column Editor3 Select a column and switch to Properties pane on left hand side4 Navigate to the Editor property and set its value to instance of the C1ColorPicker control

At Run Time

To set an external control as editor through code create an instance of the control and assign it to the Editor property ofthe Column object

See the code below to know how to set an external control as editor in WinForms FlexGrid column

カスタムエディタとして使用するC1ColorPickerコントロールのインスタンスを作成します C1WinC1InputC1ColorPicker customeditor = new C1WinC1InputC1ColorPicker() カスタムエディタにEditorプロパティを割り当てます c1FlexGrid1Cols[1]Editor = customeditor

C

FlexGrid for WinForms

47 Copyright copy GrapeCity Inc All rights reserved

For controls which are not derived from the Control base class it is still possible to use them as editors usingIC1EmbeddedEditor interface You can even use the UITypeEditor classes as grid editors This way the FlexGrid control canuse virtually any control as a cell editor For more information about the implementation see the product sample named CustomEditors

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

カスタムエディタとして使用するC1ColorPickerコントロールのインスタンスを作成します Dim customeditor As C1WinC1InputC1ColorPicker = New C1WinC1InputC1ColorPicker()

カスタムエディタにEditorプロパティを割り当てます c1FlexGrid1Cols(1)Editor = customeditor

VBNET

チェックボックス

Display Checkbox for Boolean ValuesFlexGrid by default uses the checkbox editor for representing the Boolean values That is when the DataTypeproperty of a Row or Column object is set to Bool type a checkbox appears in the cells and user can toggle the valueof an editable cell simply by clicking it

To disable this default behavior and display text value instead of a checkbox in a Bool type you can set the Formatproperty of Row or Column object to string values

Default Checkbox Checkbox with Text Checkbox with Non-Boolean Value Three-state Checkbox

Use the code below to set checkbox type editor in a WinForms FlexGrid column and configure it further

データ型をブール値に設定します(チェックボックスを自動的に表示します)c1FlexGrid1Cols[Verified]DataType = typeof(Boolean)

チェックボックスを表示する代わりに文字列値を表示しますc1flexGrid1Cols[Verified]Format = YesNo ブール列のチェックボックスの横にあるテキストを有効にしますc1flexGrid1Cols[Verified]ImageAndText = true

C

データ型をブール値に設定します(チェックボックスを自動的に表示します)c1FlexGrid1Cols(Verified)DataType = GetType(Boolean)

チェックボックスを表示する代わりに文字列値を表示しますc1flexGrid1Cols(Verified)Format = YesNo

ブール列のチェックボックスの横にあるテキストを有効にしますc1flexGrid1Cols(Verified)ImageAndText = True

VBNET

FlexGrid for WinForms

48 Copyright copy GrapeCity Inc All rights reserved

Display Checkbox for Non-Boolean ValuesIn unbound mode you can display a checkbox along with any non-boolean text as well You can use the SetCellCheckmethod to add checkbox to any kind of cells Along with row and column index this method takes valueof CheckEnum enumeration as one of its parameters to specify the state of checkbox at the time of rendering

Following code demonstrates how you can display checkbox for non-boolean values

Set Checkbox AlignmentTo set position of checkbox in the cell you need to use ImageAlign property of the Row or Column object Thisproperty accepts values from the ImageAlignEnum enumeration which lets you hide tile stretch or position the image

Align the checkbox to display in center of a WinForms FlexGrid column using the code below

Change the Checkbox ImageTo change icon image of different states of checkbox you can use the GlyphEnum which can be accessed usingthe Glyphs property For more information about changing glyphs see Custom Glyphs

You can change the images to be used for various checkbox states in WinForms FlexGrid using the code below

チェックオン状態のセル(32)に2つの状態のチェックボックスを設定します c1flexGrid1SetCellCheck(3 2 CheckEnumChecked)

C

チェックオン状態のセル(32)に2つの状態のチェックボックスを設定しますc1flexGrid1SetCellCheck(3 2 CheckEnumChecked)

VBNET

チェックボックスをセルの右中央に揃えますc1flexGrid1Cols[Verified]ImageAlign = ImageAlignEnumRightCenter

C

チェックボックスをセルの右中央に揃えますc1flexGrid1Cols(Verified)ImageAlign = ImageAlignEnumRightCenter

VBNET

カスタム画像をチェックボックスアイコンとして設定します Image imgChk = new Bitmap(ResourcesImagescheckedpng) Image imgUnchk = new Bitmap(ResourcesImagesuncheckedpng) Image imgGray = new Bitmap(ResourcesImagesnullpng) c1flexGrid1Glyphs[GlyphEnumChecked] = imgChk c1flexGrid1Glyphs[GlyphEnumUnchecked] = imgUnchk c1flexGrid1Glyphs[GlyphEnumGrayed] = imgGray

C

カスタム画像をチェックボックスアイコンとして設定します Dim imgChk As Image = New Bitmap(ResourcesImagescheckedpng) Dim imgUnchk As Image = New Bitmap(ResourcesImagesuncheckedpng)

VBNET

FlexGrid for WinForms

49 Copyright copy GrapeCity Inc All rights reserved

Use Three State CheckboxIn addition to usual two state checkbox FlexGrid lets you create three state checkbox as well The simplest way ofenabling the third state is through the CheckEnum While a Boolean checkbox togglesbetween CheckEnumChecked and CheckEnumUnchecked states the three states of a three state checkbox arerepresented by CheckEnumTSChecked CheckEnumTSUnchecked and CheckEnumTSGrayed However in thiscase by default user can not go back to null after switching to checked or unchecked state once In order to cycle acheckbox between three states you need to handle the ValidateEdit event

Use the code below to create a three state checkbox in the WinForms FlexGrid

Dim imgGray As Image = New Bitmap(ResourcesImagesnullpng) c1flexGrid1Glyphs(GlyphEnumChecked) = imgChk c1flexGrid1Glyphs(GlyphEnumUnchecked) = imgUnchk c1flexGrid1Glyphs(GlyphEnumGrayed) = imgGray

private void c1FlexGrid1_ValidateEdit(object sender ValidateEditEventArgs e) if (c1FlexGrid1Cols[eCol]Name == Done) eCancel = true if (c1FlexGrid1[eRow eCol]Equals(false)) c1FlexGrid1[eRow eCol] = true else if (c1FlexGrid1[eRow eCol]Equals(true)) c1FlexGrid1[eRow eCol] = DBNullValue else if (c1FlexGrid1[eRow eCol]Equals(DBNullValue)) c1FlexGrid1[eRow eCol] = false

C

Private Sub c1FlexGrid1_ValidateEdit(ByVal sender As Object ByVal e As ValidateEditEventArgs) If c1FlexGrid1Cols(eCol)Name Is Done Then eCancel = True

If c1FlexGrid1(eRow eCol)Equals(False) Then c1FlexGrid1(eRow eCol) = True ElseIf c1FlexGrid1(eRow eCol)Equals(True) Then c1FlexGrid1(eRow eCol) = DBNullValue ElseIf c1FlexGrid1(eRow eCol)Equals(DBNullValue) Then c1FlexGrid1(eRow eCol) = False End If End IfEnd Sub

VBNET

数値

FlexGrid by default uses the numeric editor to edit the numeric data that is when the data type is set to any of the numeric types such as Int and Decimal Thisbehavior of FlexGrid is controlled by the EditOptions property which provides various editing options through the EditFlags enumeration One of the flagsprovided is UseNumericEditor As the default value of EditOptions property is All UseNumericEditor flag is always ON and hence grid automatically enablesthe numeric editor while editing the numeric data You can access the EditOptions property at design time as well as through code

FlexGrid for WinForms

50 Copyright copy GrapeCity Inc All rights reserved

Numeric Editor Numeric Editor with Format = C0 Numeric Editor with Spin Button Numeric Editor with Calculator

At Design Time

To enable or disable the numeric editor at design time you can access the EditOptions property from the Properties window

At Run Time

At run-time you need to set the UseNumericEditor flag On in the EditOptions property Use the code below to set EditOptions property in the WinFormsFlexGrid

Format Numeric CellTo format the data in a numeric cell FlexGrid provides the Format property of Column as well as Row object In case of the formats that support decimal valuessuch as numeric currency and exponential FlexGrid displays values up to two decimal places by default However you can specify the number of decimals todisplay by appending the value of Format property with that number For instance in order to display values up to three decimal places in a Number type cellyou specify value of Format property as N3 or n3

Note This property doesnt have any effect on the stored value but only on how value is displayed at the run time You can access the formatted valueof a cell using GetDataDisplay(Int32 Int32) method of the C1FlexGrid class

You can set the Format property at design time as well as through code Following table lists the commonly used formats for numeric cells

Format Value Description

Number N or n Specifies the formatting for simple numeric values

Currency C or c Specifies the formatting for monetary values

Exponential or Scientific E or e Specifies the formatting for values using scientific notations

Percentage P or p Specifies the formatting for percentage values

Custom User-defined Takes the value of format string from user

A custom string might require handling in the code

At Design Time

1 In design view click on the FlexGrid smart tag to open the C1FlexGrid Tasks menu2 Click the Column Tasks option and navigate to Format String property3 Click ellipsis button to open the Format String dialog

すべてのフラグをオンに設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsAll

UseNumericEditorフラグのみを設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsUseNumericEditor

C

すべてのフラグをオンに設定しますc1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsAll

UseNumericEditorフラグのみを設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsUseNumericEditor

VBNET

FlexGrid for WinForms

51 Copyright copy GrapeCity Inc All rights reserved

4 Select the required format from the list box on left say Currency5 Set the format specific properties on the right hand side of the dialog Decimal places in this case

At Run Time

To specify the format of a particular numeric type column set the Format property to any of the above mentioned values In this example we have set theformat of column 3 as currency without decimals

Following code shows how to set the format of a WinForms FlexGrid column

Input using Spin ButtonTo create a numeric editor which uses a spin button for input you need to assign instance of an external control such as NumericUpDown to the Editorproperty

Use the code below to create a numeric editor with spin button in the WinForms FlexGrid

Input using CalculatorTo allow user to give input using a calculator in a numeric editor you can use the C1NumericEdit control of C1Input library as an editor So just add thereference to C1WinC1Input and assign an instance of C1NumericEdit control to the Editor property For more information about using an external controlas editor see Custom Editors

To create a numeric editor with calculator use the code below

小数点なしの通貨形式を設定します c1FlexGrid1Cols[3]Format = C0

C

小数点なしの通貨形式を設定しますc1FlexGrid1Cols(3)Format = C0

VBNET

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols[2]Editor = new NumericUpDown()

C

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols(2)Editor = New NumericUpDown()

VBNET

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols[2]Editor = new C1NumericEdit()ShowUpDownButtons=false

C

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols(2)Editor = New C1NumericEdit() With ShowUpDownButtons = False

VBNET

日付

FlexGrid by default uses the Date editor for all the Date and DateTime type of data The Date editor consists of adropdown which opens a calendar when clicked and user can select the desired date by navigating through it Usercan also change the date month or year by simply selecting the corresponding part in the editor and pressing the upand down arrow keys

FlexGrid for WinForms

52 Copyright copy GrapeCity Inc All rights reserved

Default Date Editor Date Editor Without Calendar Date Editor with Spin Button

Use the code below to create a Date editor in a WinForms FlexGrid column

Input without Displaying CalendarAs mentioned earlier in FlexGrid a DateTime type cell automatically displays a dropdown calendar to receive theinput from user However in order to get a date input from user without displaying a calendar you can set a maskusing the EditMask property and then validate the input value using the ValidateEdit event

Following code demonstrates how to create a Date editor without calendar in WinForms FlexGrid

For more information about cell masks and validation see topics Mask and Validation respectively Another way ofhiding the calendar is to get user input using the spin buttons

Input using Spin ButtonBelow code shows how to create Date editor with spin button

To display spin buttons in a Date editor use the SetupEditor event to convert the editor into DateTimePicker and setits ShowUpDown property to true

Set the data type property to DateTime c1FlexGrid1Cols[1]DataType = typeof(DateTime)

C

Set the data type property to DateTimec1FlexGrid1Cols(1)DataType = GetType(Date)

VBNET

Set a mask on column c1flexGrid1Cols[3]EditMask = 00000000

C

Set a mask on columnc1flexGrid1Cols(3)EditMask = 00000000

VBNET

private void C1flexGrid1_SetupEditor(object sender RowColEventArgs e)

C

FlexGrid for WinForms

53 Copyright copy GrapeCity Inc All rights reserved

Set Date FormatTo set the format in a Date type column you need to set the Format property of the Column object

Following table lists the pre-defined formats

Format Value Example

Short Date d 11192003

Long Date D Friday November 19 2003

Short Time t 1215 AM

Long Time T 121530 AM

You can also create a custom format using the various custom format specifiers supported in the Net framework Fordetails see Custom date and time format strings on Microsoft website

Use the following code to create a custom date format in WinForms FlexGrid column

if (c1flexGrid1Cols[eCol]Name == DOB) Cast FlexGrids current cell editor var dateEditor = c1flexGrid1Editor as DateTimePicker

Show UpDown button (replacing the drop-down button for calendar) dateEditorShowUpDown = true

Private Sub C1flexGrid1_SetupEditor(ByVal sender As Object ByVal e As RowColEventArgs) If c1flexGrid1Cols(eCol)Name Is DOB Then Cast FlexGrids current cell editor Dim dateEditor = TryCast(c1flexGrid1Editor DateTimePicker)

Show UpDown button (replacing the drop-down button for calendar) dateEditorShowUpDown = True End IfEnd Sub

VBNET

Set a pre-defined format c1FlexGrid1Cols[DOB]Format = d Set a custom format c1FlexGrid1Cols[OrderDate]Format = ddMMyyyy

C

Set a pre-defined format c1FlexGrid1Cols(DOB)Format = d

Set a custom format c1FlexGrid1Cols(OrderDate)Format = ddMMyyyy

VBNET

FlexGrid for WinForms

54 Copyright copy GrapeCity Inc All rights reserved

Display Country-specific Date FormatAlthough abovementioned formats are the most commonly used date formats but there are cultures which preferusing their specific calendar and date formats in some cases such as Japan You can display those specific calendarsand date formats by using OwnerDrawCell event of the C1FlexGrid class and the SystemGlobalization namespaceThe namespace provides various classes to define culture related information including calendars and date formatsFor instance to display Japanese calendar and Japanese date format you can leveragethe SystemGlobalizationJapaneseCalendar class Similarly you can also display other calendars such as GregorianHebrew Hijri and Korean

Set the country specific date format in WinForms FlexGrid using the code below

Set MinMax DateTo set a range of valid values you can use the DateTimePicker control as editor and set its MinDate and MaxDate

c1flexGrid1Cols[DOB]Format = ddMMyyyy c1flexGrid1DrawMode = DrawModeEnumOwnerDraw c1flexGrid1OwnerDrawCell += C1flexGrid1_OwnerDrawCell private void C1flexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if (c1flexGrid1Cols[eCol]DataType == typeof(DateTime) ampamp eRow gt= c1flexGrid1RowsFixed) eText = DateTimeParse(eText)ToString(yyyy年MM月dd日(dddd) c)

C

C1FlexGrid1Cols(DOB)Format = ddMMyyyy C1FlexGrid1DrawMode = DrawModeEnumOwnerDraw

AddHandler C1FlexGrid1OwnerDrawCell AddressOf C1flexGrid1_OwnerDrawCell

Private Sub C1flexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If C1FlexGrid1Cols(eCol)DataType = GetType(DateTime) AndAlso eRow gt= C1FlexGrid1RowsFixed Then eText = DateTimeParse(eText)ToString(yyyy年MM月dd日(dddd) c) End If End Sub

VBNET

FlexGrid for WinForms

55 Copyright copy GrapeCity Inc All rights reserved

property

Use the code below to set a range of valid dates in WinForms FlexGrid

DateTimePicker dateTimePicker = new DateTimePicker() dateTimePickerFormat = DateTimePickerFormatShort

Sets Max and Min dates dateTimePickerMinDate = new DateTime(2015 05 01) dateTimePickerMaxDate = DateTimeToday

Assigns DateTimePicker control as editor for FirstOrderDate(date) column c1flexGrid1Cols[FirstOrderDate]Editor = dateTimePicker

C

Dim dateTimePicker As DateTimePicker = New DateTimePicker() dateTimePickerFormat = DateTimePickerFormat[Short]

Sets Max and Min dates dateTimePickerMinDate = New DateTime(2015 05 01) dateTimePickerMaxDate = DateToday

Assigns DateTimePicker control as editor for FirstOrderDate(date) column c1flexGrid1Cols(FirstOrderDate)Editor = dateTimePicker

VBNET

コンボボックス

ComboBox cell is a common way of providing the user with a well-defined list of possible values in the form of a drop-down list FlexGrid providesthis multi-option editor in various forms such as dropdown list dropdown combo ellipsis button or a textbox with ellipsis button

Default ComboBox Multi-column ComboBox ComboBox with custom BackColor ComboBox with Images

Display Dropdown List or ComboIn FlexGrid you can create a dropdown list by creating a string containing all the choices separated by pipe characters (for exampleTrue|False|Dont know) and assign it to the ComboList property of Row or Column object This causes the grid to display a drop-down buttonnext to the cell The user can click the dropdown button (or press F2) to display the list of choices available for that cell

Another common situation is where cells have a list of common values but users should be allowed to type a custom value as well This can beaccomplished with drop-down combos a combination of text box and drop-down list In FlexGrid you can create combos by starting the choicelist with a pipe character (for example |True|False|Dont know) and then assign it to the ComboList property

Following code shows how to create a dropdown list or combo editor in the WinForms FlexGrid

FlexGrid for WinForms

56 Copyright copy GrapeCity Inc All rights reserved

The ComboList property can also be set using the Combo List dialog at design time To access the Combo List dialog

1 Open the Column Tasks menu for column for which editor is to be set2 Go to the Combo List option and click the ellipsis button on the right hand side of the field3 Combo List dialog opens where you can specify the option values each in a new line4 You can also choose whether you want to display these values as a Dropdown List or Dropdown Combo Note that it also lets you create

cell button using Ellipsis Button or Textbox amp Ellipsis Button option

Display Multi-column ComboBoxIn FlexGrid you can also display multiple columns in a ComboBox using the MultiColumnDictionary class This class implementsthe IC1MultiColumnDictionary interface and has multiple overloads These overloads let you specify the data source object the key columncolumns that are to be displayed in multiple columns and the column to be displayed when ComboBox is closed

Display a multi-column combobox in a WinForms FlexGrid column using the code below

Note that the above code uses the data source object dt to supply data to the grid You can set up the data source as per your requirements

ドロップダウンリストとしてCustomerIDを割り当てますc1flexGrid1Cols[CustomerID]ComboList = AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

ドロップダウンコンボボックスとしてCustomerIDを割り当てパイプ文字|でリストを開始します c1flexGrid1Cols[CustomerID]ComboList = |AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

C

ドロップダウンリストとしてCustomerIDを割り当てますc1flexGrid1Cols(CustomerID)ComboList = AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

ドロップダウンコンボボックスとしてCustomerIDを割り当てパイプ文字|でリストを開始します c1flexGrid1Cols(CustomerID)ComboList = |AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

VBNET

string[] columnRange = new string[] City Country c1FlexGrid1Cols[City]DataMap = new MultiColumnDictionary(dt City columnRange 0)

C

Dim columnRange = New String() City Countryc1FlexGrid1Cols(City)DataMap = New MultiColumnDictionary(dt City columnRange 0)

VBNET

DataTable dt = new DataTable() dtColumnsAdd(CustomerID typeof(int)) dtColumnsAdd(ContactName typeof(string)) dtColumnsAdd(Designation typeof(string)) dtColumnsAdd(City typeof(string)) dtColumnsAdd(Country typeof(object))

サンプルデータ

C

FlexGrid for WinForms

57 Copyright copy GrapeCity Inc All rights reserved

Set Mapped Data in the ComboBoxTo set a ComboBox having display values different from the actual values you need to use the C1ComboBox as editor and leverageits ItemsDisplayMember and ItemsValueMember properties For instance the example below uses country names as display values while actualvalue is the dialing code of the corresponding country

Following code shows how to set the mapped data in combobox column of the WinForms FlexGrid

dtRowsAdd(1 Maria Anders Sales Representative Madrid Spain ) dtRowsAdd(2 Ana Trujillo Sales Associate Monterrey Mexico ) dtRowsAdd(3 Antonio Moreno Owner Dublin Ireland) dtRowsAdd(4 Thomas Hardy Sales Representative Bristol UK) dtRowsAdd(5 Patricio Simpson Marketing Manager Munich Germany) dtRowsAdd(6 Paolo Accorti Sales Representative Barcelona Spain) dtRowsAdd(7 Martine Ranceacute Owner Puebla Mexico) dtRowsAdd(8 Elizabeth Brown Marketing Manager London UK) dtRowsAdd(9 Jaime Yorres Order Administrator Vienna Austria) dtRowsAdd(10 Yvonne Moncada Marketing Manager Mexico Mexico) dtRowsAdd(11 Helen Bennett OwnerMarketing Cork Ireland) dtRowsAdd(12 Sergio Gutieacuterrezy Order Administrator Sao Paulo Brazil)

c1FlexGrid1DataSource = dt

Dim dt As DataTable = New DataTable()dtColumnsAdd(CustomerID GetType(Integer))dtColumnsAdd(ContactName GetType(String))dtColumnsAdd(Designation GetType(String))dtColumnsAdd(Country GetType(Object))dtColumnsAdd(City GetType(String))

サンプルデータdtRowsAdd(1 Maria Anders Sales Representative Spain Madrid)dtRowsAdd(2 Ana Trujillo Sales Associate Mexico Monterrey)dtRowsAdd(3 Antonio Moreno Owner Ireland Dublin)dtRowsAdd(4 Thomas Hardy Sales Representative UK Bristol)dtRowsAdd(5 Patricio Simpson Marketing Manager Germany Munich)dtRowsAdd(6 Paolo Accorti Sales Representative Spain Barcelona)dtRowsAdd(7 Martine Ranceacute Owner Mexico Puebla)dtRowsAdd(8 Elizabeth Brown Marketing Manager UK London)dtRowsAdd(9 Jaime Yorres Order Administrator Austria Vienna)dtRowsAdd(10 Yvonne Moncada Marketing Manager Mexico Mexico)dtRowsAdd(11 Helen Bennett OwnerMarketing Ireland Cork)dtRowsAdd(12 Sergio Gutieacuterrezy Order Administrator Brazil Sao Paulo)c1FlexGrid1DataSource = dt

VBNET

private void Form1_Load(object sender EventArgs e) 顧客データを取得します Customers = GetCustomers()

FlexGridにデータを入力します c1FlexGrid1DataSource = Customers

国とその国コードのコレクションを作成します ObservableCollectionltCountrygt countries = new ObservableCollectionltCountrygt() countriesAdd(new Country(1 USA)) countriesAdd(new Country(91 India)) countriesAdd(new Country(7 Russia))

C

FlexGrid for WinForms

58 Copyright copy GrapeCity Inc All rights reserved

Set ComboBox DimensionsTo set the height and width of combo box dropdown you need to assign an instance of ComboBox as an editor and then setthe DropDownHeight and DropDownWidth property of that instance

countriesAdd(new Country(54 Argentina)) countriesAdd(new Country(81 Japan)) countriesAdd(new Country(380 Ukraine)) countriesAdd(new Country(98 Iran)) countriesAdd(new Country(45 Denmark)) countriesAdd(new Country(84 Vietnam)) countriesAdd(new Country(49 Germany)) BindingSource countryBS = new BindingSource() countryBSDataSource = countries

C1Comboboxコントロールをインスタンス化して設定します C1ComboBox countryCodeCombo = new C1ComboBox() countryCodeComboItemsDataSource = countryBS

region Mapped Data using C1Combobox

国コードと国名をマッピングするためにプロパティを設定します countryCodeComboItemsDisplayMember = CountryName countryCodeComboItemsValueMember = CountryCode countryCodeComboTextDetached = true countryCodeComboTranslateValue = true

C1ComboboxをDiallingCode列のエディタとして設定します c1FlexGrid1Cols[DiallingCode]Editor = countryCodeCombo endregion

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) 顧客データを取得します Customers = GetCustomers()

FlexGridにデータを入力します c1FlexGrid1DataSource = Customers

国とその国コードのコレクションを作成します Dim countries As ObservableCollection(Of Country) = New ObservableCollection(Of Country)() countriesAdd(New Country(1 USA)) countriesAdd(New Country(91 India)) countriesAdd(New Country(7 Russia)) countriesAdd(New Country(54 Argentina)) countriesAdd(New Country(81 Japan)) countriesAdd(New Country(380 Ukraine)) countriesAdd(New Country(98 Iran)) countriesAdd(New Country(45 Denmark)) countriesAdd(New Country(84 Vietnam)) countriesAdd(New Country(49 Germany)) Dim countryBS As BindingSource = New BindingSource() countryBSDataSource = countries

C1Comboboxコントロールをインスタンス化して設定します Dim countryCodeCombo As C1ComboBox = New C1ComboBox() countryCodeComboItemsDataSource = countryBS

国コードと国名をマッピングするためにプロパティを設定します countryCodeComboItemsDisplayMember = CountryName countryCodeComboItemsValueMember = CountryCode countryCodeComboTextDetached = True countryCodeComboTranslateValue = True

C1ComboboxをDiallingCode列のエディタとして設定します c1FlexGrid1Cols(DiallingCode)Editor = countryCodeComboEnd Sub

VBNET

FlexGrid for WinForms

59 Copyright copy GrapeCity Inc All rights reserved

Use the code below to specify the height and width of the combobox to be displayed in the WinForms FlexGrid

Change Background Color or Font ColorTo change the background color or font color of the ComboBox list create an instance of ComboBox to assign it as editor Then set the BackColorand ForeColor property of that instance

Customize combobox in the WinForms FlexGrid by using the code below

Display Image in the ListTo display images in the ComboBox list you need to use the C1ComboBox as an editor and leverage its ItemsImageList property This property isof type ImageList class that acts as a container for the images which are stored in its Images collection First access the images stored in theproject resources through the ResourceManagerGetResourceSet method and create a collection of mapping between images and itscorresponding names The collection acts as a data source for ComboBox Now create an instance of the ImageList class add images to itsImages collection from data source and assign that instance of ImageList class to the ItemsImageList property to render images in the ComboBoxlist

Following code shows how to display images in the combobox lists of WinForms FlexGrid

ComboBox cb = (ComboBox)c1flexGrid1Editor cbDropDownWidth = 250 cbDropDownHeight = 200

C

Dim cb As ComboBox = CType(c1flexGrid1Editor ComboBox) cbDropDownWidth = 250 cbDropDownHeight = 200

VBNET

ComboBox comboBox = new ComboBox() comboBoxBackColor = ColorBlack comboBoxForeColor = ColorWhite

C

Dim comboBox As ComboBox = New ComboBox() comboBoxBackColor = ColorBlack comboBoxForeColor = ColorWhite

VBNET

コンボボックスに画像を入力します var itemsSource = new ListltFlaggt() ImageList imgFlag = new ImageList() imgFlagImagesClear() var rsrSet = ResourcesResourceManagerGetResourceSet(CultureInfoCurrentCulture true true)

foreach(DictionaryEntry entry in rsrSet) var img = entryValue as Image itemsSourceAdd(new Flag(entryKeyToString() img)) itemsSourceSort(new CompareFlag())

foreach (Flag entry in itemsSource) imgFlagImagesAdd(entryCountryName entryCountryFlag)

countryComboItemsImageList = imgFlag

C

FlexGrid for WinForms

60 Copyright copy GrapeCity Inc All rights reserved

Set Number of Displayed ItemsTo set the number of items to be displayed in a combo box you can use ComboBoxMaxDropDownItems property

Use the code below to limit the number of items to be displayed in combobox list of the WinForms FlexGrid

Sort the ComboBox ListTo sort the items in the ComboBox dropdown list you can use the C1ComboBox as editor and call the Sort method to sort the dropdown itemsgetting displayed in the ComboBox

To display sorted items in comboboxlist of the WinForms FlexGrid use the code below

countryComboItemMode = ComboItemModeHtmlPattern countryComboHtmlPattern = ltdiv ltdiv style=padding0pxgtltimg src=CountryName style=padding-right14pxgtCountryNameltdivgt

コンボボックスに画像を入力します Dim itemsSource = New List(Of Flag)()Dim imgFlag As ImageList = New ImageList()imgFlagImagesClear()Dim rsrSet = ResourcesResourceManagerGetResourceSet(CultureInfoCurrentCulture True True)

For Each entry As DictionaryEntry In rsrSet Dim img = TryCast(entryValue Image) itemsSourceAdd(New Flag(entryKeyToString() img))Next

itemsSourceSort(New CompareFlag())

For Each entry In itemsSource imgFlagImagesAdd(entryCountryName entryCountryFlag)Next

countryComboItemsImageList = imgFlagcountryComboItemMode = ComboItemModeHtmlPatterncountryComboHtmlPattern = ltdiv ltdiv style=padding0pxgtltimg src=CountryName style=padding-right14pxgtCountryNameltdivgt

VBNET

コンボボックスのドロップダウンに表示する国の数を設定します countryComboMaxDropDownItems = 10

C

コンボボックスのドロップダウンに表示する国の数を設定しますcountryComboMaxDropDownItems = 10

VBNET

C1ComboBox countryCombo = new C1ComboBox() countryComboDropDownStyle = DropDownStyleDropDownList Listltstringgt countries = new Listltstringgt USA Canada India Russia Japan Germany countriesSort() countryComboItemsDataSource = countries

C1ComboboxをCountry列のエディタとして設定します c1FlexGrid1Cols[Country]Editor = countryCombo

C

FlexGrid for WinForms

61 Copyright copy GrapeCity Inc All rights reserved

Get the Selected IndexTo get the selected index or value of the selected item you can use the SelectedIndex property or SelectedItem property of the ComboBoxEditorclass The example below uses the ComboCloseUp event to show a message box displaying the selected index and the selected item

Use the code below to fetch the index and value of selected item in combobox list of the WinForms FlexGrid

Dim countryCombo As C1ComboBox = New C1ComboBox() countryComboDropDownStyle = DropDownStyleDropDownList Dim countries As List(Of String) = New List(Of String) From USA Canada India Russia Japan Germany countriesSort() countryComboItemsDataSource = countries

C1ComboboxをCountry列のエディタとして設定します c1FlexGrid1Cols(Country)Editor = countryCombo

VBNET

private void C1FlexGrid1_ComboCloseUp(object sender C1WinC1FlexGridRowColEventArgs e) MessageBoxShow(Selected Index + c1FlexGrid1ComboBoxEditorSelectedIndex + n + Selected Item + c1FlexGrid1ComboBoxEditorSelectedItem)

C

Private Sub C1FlexGrid1_ComboCloseUp(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) MessageBoxShow(Selected Index amp c1FlexGrid1ComboBoxEditorSelectedIndex amp vbLf amp Selected Item + c1FlexGrid1ComboBoxEditorSelectedItem)End Sub

VBNET

マスク

Mask editor refers to pre-defined templates for getting input from users which also automatically validates the userinput as it is typed Mask strings have two types of characters literal characters and template characters While literalcharacters are the ones which become part of the input the template characters serve as placeholders for charactersbelonging to specific categories (for example digits or alphabets) For example the code below assigns a (999) 999-9999 editing mask to the first column which holds phone numbers Here special characters such as braces (()) andhyphen (-) are the literals and the digit 9 is a placeholder that stands for any digit

FlexGrid for WinForms

62 Copyright copy GrapeCity Inc All rights reserved

The FlexGrid control supports masked editing through the EditMask property which can be used with regular textfields and with drop-down combo fields To apply different masks within the same column you can trap the BeforEditevent and set the EditMask property to appropriate value

You can also set the EditMask property at design time using the Input Mask dialog You can access the dialog byclicking the ellipsis button against Edit Mask field in Column Tasks menu It also means that the Edit Mask field isspecific to the column selected at that time

Note that when the EditMask property is set to a non-empty string the grid uses the masked editor even if thecolumn contains DateTime values Usually grid uses the built-in Date editor to edit DateTime type cells

電話番号の編集マスクを設定します c1FlexGrid1Cols(1)EditMask = (999) 999-9999

C

電話番号の編集マスクを設定します c1FlexGrid1Cols(1)EditMask = (999) 999-9999

VBNET

マップリスト

Mapped lists refer to the mapping of data stored in the grid to the values visible to the user Such mapping is oftenused to display user-friendly values when actual data stored in the grid is either encoded or difficult to understand bythe user For instance in an employee record table it would be more convenient for administrative executive to seenames of the employees while database stores the employee IDs

FlexGrid for WinForms

63 Copyright copy GrapeCity Inc All rights reserved

Display Data MappingIn FlexGrid data mapping can be achieved by using the DataMap property This property contains reference to anIDictionary object that establishes mapping between database values and values to be displayed in the gridHashTable ListDictionary and SortedList are some examples of IDictionary objects which provide valid data maps

Following code demonstrates how to display the data mapped list in the WinForms FlexGrid

There is a difference in how HashTable ListDictionary and SortedList classes order the items So when these tables areused with editable columns the order of items rendering in the mapped list also differs depending upon the keys andclass used to create the list

Note that the keys in the data map must be of the same type as the cells being edited For example if a columncontains short integers (Int16) then any data maps associated with the column should have short integer keys

Display Image MappingTo display image mapping in a FlexGrid column you need to set the ImageMap property of Row or Column object toan IDictionary object that establishes mapping between images and the corresponding text values For example if acolumn contains country names you can use this property to display the corresponding flags You can controlwhether to show only images or images with text by using the ImageAndText property of the object

Create an image mapping in the WinForms FlexGrid using the code below

データマップを作成しますListDictionary customerNames = new ListDictionary()customerNamesAdd(AJK18F Sam Anders)customerNamesAdd(BBK21D Daneil)customerNamesAdd(AEF25N Henry Hussain)customerNamesAdd(BZD42S Owen Romanov)customerNamesAdd(AKC16G Serena Nguyen)

データマップをflexgrid列に割り当てますc1flexGrid1Cols[Name]DataMap = customerNames

C

データマップを作成しますDim customerNames As ListDictionary = New ListDictionary()customerNamesAdd(AJK18F Sam Anders)customerNamesAdd(BBK21D Daneil)customerNamesAdd(AEF25N Henry Hussain)customerNamesAdd(BZD42S Owen Romanov)customerNamesAdd(AKC16G Serena Nguyen)

データマップをflexgrid列に割り当てますc1flexGrid1Cols(Name)DataMap = customerNames

VBNET

Hashtable ht = new Hashtable() foreach (Row row in c1flexGrid1Rows) htAdd(row[CustomerID] LoadImage(row[Photo] as byte[])) ImageMapをPhoto列に割り当てます c1flexGrid1Cols[Photo]ImageMap = ht

C

FlexGrid for WinForms

64 Copyright copy GrapeCity Inc All rights reserved

アスペクト比を維持しながら画像をセルに合わせます c1flexGrid1Cols[Photo]ImageAlign = ImageAlignEnumScale c1flexGrid1Cols[Photo]Width = 80

Dim ht As Hashtable = New Hashtable()

For Each row As Row In c1flexGrid1Rows htAdd(row(CustomerID) LoadImage(TryCast(row(Photo) Byte()))) Next

ImageMapをPhoto列に割り当てます c1flexGrid1Cols(Photo)ImageMap = ht

アスペクト比を維持しながら画像をセルに合わせます c1flexGrid1Cols(Photo)ImageAlign = ImageAlignEnumScale c1flexGrid1Cols(Photo)Width = 80

VBNET

セルボタン

Cell button editor refers to a cell with an ellipsis button This editor comes to use when you need to get an operationdone or open a dialog on a button click Such dialogs generally contain multiple different options or settings for a userto choose from

Default Cell Button Cell Button with Text Cell Button with Custom Image

Display Cell ButtonIn FlexGrid you can display a cell button by setting the ComboList property to an ellipsis character You can alsouse a pipe character before ellipsis button to display an ellipsis with text box to let user enter his inputThe CellButtonClick event is fired when user clicks the cell button You can capture this event to implement thedesired operation or display a dialog of your choice

By default the cell button gets displayed when cell enters the edit mode However you can set the ShowButtonsproperty to Always to display the cell button even in non-edit mode

Use the code below to display cell button in a WinForms FlexGrid column

Mark列のComboListプロパティを設定してセルボタンを表示するようにします c1flexGrid1Cols[Mark]ComboList = セルボタンを常に表示できるようにします c1flexGrid1Cols[Mark]ShowButtons = ShowButtonsEnumAlways

エンドユーザーがセルボタンをクリックしたときに処理します c1flexGrid1CellButtonClick += C1flexGrid1_CellButtonClick

C

Mark列のComboListプロパティを設定してセルボタンを表示するようにしますc1flexGrid1Cols(Mark)ComboList =

VBNET

FlexGrid for WinForms

65 Copyright copy GrapeCity Inc All rights reserved

The ComboList property can also be set using the Combo List dialog at design time To access the Combo List dialog

1 Open the Column Tasks menu for column for which editor is to be set2 Go to the Combo List option and click the ellipsis button on the right hand side of the field3 Combo List dialog opens where you can specify the option values each in a new line4 You can also choose whether you want to display these values as an Ellipsis Button or Textbox amp Ellipsis

Button Note that it also gives you options to create Dropdown List and Dropdown Combo

The example below demonstrates change in back color and fore color of the current row on click of the cell buttonSimilarly you can perform the desired operation in the CellButtonClick event

セルボタンを常に表示できるようにしますc1flexGrid1Cols(Mark)ShowButtons = ShowButtonsEnumAlways

エンドユーザーがセルボタンをクリックしたときに処理しますc1flexGrid1CellButtonClick += C1flexGrid1_CellButtonClick

private void C1flexGrid1_CellButtonClick(object sender RowColEventArgs e) 次のコードは色を変更して現在の行をマークします if (c1flexGrid1Rows[eRow]StyleDisplayBackColor == ColorFromName(Window)) c1flexGrid1Rows[eRow]StyleNewBackColor = ColorGreen c1flexGrid1Rows[eRow]StyleNewForeColor = ColorWhite c1flexGrid1Rows[eRow]StyleNewBackColor = ColorFromName(Window) c1flexGrid1Rows[eRow]StyleNewForeColor = ColorFromName(WindowText)

C

FlexGrid for WinForms

66 Copyright copy GrapeCity Inc All rights reserved

Change Image of Cell ButtonBy default cell button displays an ellipsis However you can change the image of cell button usingthe CellButtonImage property

Set the image of cell button in the WinForms FlexGrid as shown in the code below

Private Sub C1flexGrid1_CellButtonClick(ByVal sender As Object ByVal e As RowColEventArgs) 次のコードは色を変更して現在の行をマークします If c1flexGrid1Rows(eRow)StyleDisplayBackColor Is ColorFromName(Window) Then c1flexGrid1Rows(eRow)StyleNewBackColor = ColorGreen c1flexGrid1Rows(eRow)StyleNewForeColor = ColorWhite End If

If True Then c1flexGrid1Rows(eRow)StyleNewBackColor = ColorFromName(Window) c1flexGrid1Rows(eRow)StyleNewForeColor = ColorFromName(WindowText) End IfEnd Sub

VBNET

CellButtonImageプロパティを設定してセルボタンの画像を定義しますImage imgCellBtn = new Bitmap(ResourcesImagesbuttonpng)c1flexGrid1CellButtonImage = imgCellBtn

C

CellButtonImageプロパティを設定してセルボタンの画像を定義しますDim imgCellBtn As Image = New Bitmap(ResourcesImagesbuttonpng)c1flexGrid1CellButtonImage = imgCellBtn

VBNET

検証

Data validation lets you control the data that a user can enter into a column cell There are various ways in which adata can be validated such as restricting invalid input keys showing the error or warning information or revert thevalue to original on getting an invalid input from the user

FlexGrid for WinForms

67 Copyright copy GrapeCity Inc All rights reserved

To implement validations such as specifying the range of acceptable values or defining the minimum string length ofinput FlexGrid provides EditorValidation property of the Column class The property is oftype ValidationRuleCollection class which consists of pre-defined rules for implementing enhanced data validation inFlexGrid columns For instance the sample code below demonstrates StringLength and Required validation rulesapplied to the Customer column using the EditorValidation property

Refer the code below to know how to add validation rules in WinForms FlexGrid columns

private void SetupGridColumns() var customerNameColumn = _flexCols[CustomerName] customerNameColumnCaption = Customer customerNameColumnEditorValidationAdd(new RequiredRule()) customerNameColumnEditorValidationAdd(new StringLengthRule() MinimumLength = 2 ) var customerIDColumn = _flexCols[CustomerID] customerIDColumnVisible = false var frequencyColumn = _flexCols[Frequency] frequencyColumnFormat = 0 frequencyColumnAllowEditing = false var ageColumn = _flexCols[Age] ageColumnEditorValidationAdd(new RequiredRule()) ageColumnEditorValidationAdd(new RangeRule() Minimum = 10 Maximum = 90 )

C

FlexGrid for WinForms

68 Copyright copy GrapeCity Inc All rights reserved

Another way of applying validation is by capturing the ValidateEdit event and checking the value of EditorTextproperty If value obtained is invalid set the Cancel parameter to true to keep the grid in editing mode until userenters a valid value Such validation can be used in scenarios such as setting the range of valid values validating thecurrent cell value based on another cell value For example the below sample code validates input into a currencycolumn to ensure that values entered are between 1000 and 10000

Use ValidateEdit event to check for valid values during edit mode of the WinForms FlexGrid cell as shown in the codebelow

Private Sub SetupGridColumns() Dim customerNameColumn = _flexCols(CustomerName) customerNameColumnCaption = Customer customerNameColumnEditorValidationAdd(New RequiredRule()) customerNameColumnEditorValidationAdd(New StringLengthRule() With MinimumLength = 2 ) Dim customerIDColumn = _flexCols(CustomerID) customerIDColumnVisible = False Dim frequencyColumn = _flexCols(Frequency) frequencyColumnFormat = 0 frequencyColumnAllowEditing = False Dim ageColumn = _flexCols(Age) ageColumnEditorValidationAdd(New RequiredRule()) ageColumnEditorValidationAdd(New RangeRule() With Minimum = 10 Maximum = 90 )End Sub

VBNET

private void _flex_ValidateEdit( object sender ValidateEditEventArgs e) 金額を検証します if (_flexCols[eCol]DataType == typeof(Decimal)) try Decimal dec = DecimalParse(_flexEditorText) if ( dec lt 1000 || dec gt 10000 ) MessageBoxShow(Value must be between 1000 and 10000) eCancel = true catch MessageBoxShow(Value not recognized as a Currency) eCancel = true

C

Private Sub _flex_ValidateEdit(ByVal sender As Object ByVal e As ValidateEditEventArgs)

VBNET

FlexGrid for WinForms

69 Copyright copy GrapeCity Inc All rights reserved

金額を検証します If _flexCols(eCol)DataType Is GetType(Decimal) Then

Try Dim dec As Decimal = DecimalParse(_flexEditorText)

If dec lt 1000 OrElse dec gt 10000 Then MessageBoxShow(Value must be between 1000 and 10000) eCancel = True End If

Catch MessageBoxShow(Value not recognized as a Currency) eCancel = True End Try End IfEnd Sub

データ注釈

Data annotation means adding meaningful metadata tags to the classes and other objects making it easier to bridgethe gap between models and views by performing data validation and displaying appropriate messages to the endusers For example you may use data annotations to specify how items should be formatted what their captionsshould be whether they should be editable or not

FlexGrid supports multiple data annotation attributes used for customizing data classes displaying data from sourceand setting validation rules To use the attributes in your project you need to add a reference to theSystemComponentModelDataAnnotations assembly and then add the attributes to your data objects in the code

Note The C1FlexGrid supports the annotations defined in NET 4SystemComponentModelDataAnnotations should be version 4000 or higher

Listed below are some of the major annotation attributes that are supported in FlexGrid control Cilck herefor complete list of DataAnnotation attributes

FlexGrid for WinForms

70 Copyright copy GrapeCity Inc All rights reserved

Attribute Name Functionality in FlexGrid

Association Specifies that an entity member represents a data relationship such as a foreignkey relationship

Display Provides a general-purpose attribute that lets you specify localizable strings fortypes and members of entity partial classes

DisplayFormat Specifies how data fields are displayed and formatted by ASPNET Dynamic Data

DisplayColumn Specifies the column that is displayed in the referred table as a foreign-keycolumn

Editable Indicates whether a data field is editable

Key Denotes one or more properties that uniquely identify an entity

Validation

RequiredAttributeStringLengthAttributeRangeAttributeRegularExpressionAttributeMinLengthAttributeMetaDataAttributeMaxLengthAttributeEmailAddressAttributeCompareAttributeDataTypeAttribute

The data annotation validation attributes are used as validation rules in FlexGridoperations

The following code example shows how data annotation feature works in WinForms FlexGrid control

自動生成されたCustomerName列ヘッダに「Customer」と表示されます この列には少なくとも2つの記号の長さが最小の空でない文字列も必要です[Display(Name = Customer)][Required][StringLength(intMaxValue MinimumLength = 2)]

public string CustomerName get set 自動生成されたCustomerID列は非表示になります[Display(AutoGenerateField = false)]public int CustomerID get set

自動生成された「Frequency」列にはパーセンテージで書式設定された値が表示されます また編集を許可しません[DisplayFormat(DataFormatString = 0)][Editable(false)]public double Frequency get set

自動生成された「Age」列は事前定義された範囲の値を許可します[Required][Range(10 90)]public int Age get set サンプルデータを作成しますpublic static BindingListltDatagt GetSampleData(int cnt) var list = new BindingListltDatagt() var rnd = new Random()

C

FlexGrid for WinForms

71 Copyright copy GrapeCity Inc All rights reserved

for (int i = 0 i lt cnt i++) var item = new Data() itemCustomerName = _firstNames[rndNext(0 _firstNamesLength)] + + _lastNames[rndNext(0 _lastNamesLength)] itemCustomerID = i itemFrequency = rndNextDouble() itemAge = rndNext(10 91) listAdd(item) return list

自動生成されたCustomerName列ヘッダに「Customer」と表示されます この列には少なくとも2つの記号の長さが最小の空でない文字列も必要です ltDisplay(Name=Customer)gt ltRequiredgt ltStringLength(IntegerMaxValue MinimumLength=2)gt Public Property CustomerName As String 自動生成されたCustomerID列は非表示になります ltDisplay(AutoGenerateField=False)gt Public Property CustomerID As Integer 自動生成された「Frequency」列にはパーセンテージで書式設定された値が表示されます また編集を許可しません ltDisplayFormat(DataFormatString=0)gt ltEditable(False)gt Public Property Frequency As Double 自動生成された「Age」列は事前定義された範囲の値を許可します ltRequiredgt ltRange(10 90)gt Public Property Age As Integer

サンプルデータを作成します Public Shared Function GetSampleData(ByVal cnt As Integer) As BindingList(Of Data) Dim list = New BindingList(Of Data)() Dim rnd = New Random()

For i As Integer = 0 To cnt - 1 Dim item = New Data() itemCustomerName = _firstNames(rnd[Next](0 _firstNamesLength)) amp + _lastNames(rnd[Next](0 _lastNamesLength)) itemCustomerID = i itemFrequency = rndNextDouble() itemAge = rnd[Next](10 91) listAdd(item) Next

Return list End Function

VBNET

スパークライン

Sparklines are the miniature charts visually representing a series of values to show trends such as periodic fluctuationsor to highlight maximum or minimum values of the data series In grids sparklines are specially useful as they easily fitin a single cell and can help identify the data patterns at a glance

FlexGrid for WinForms

72 Copyright copy GrapeCity Inc All rights reserved

FlexGrid for WinForms lets you display sparklines in columns by setting ShowSparkline property of the Column classto true You can also set the type of sparkline using SparklineType property of the Sparkline class FlexGrid supportsthree types of sparklines which are

Line Similar to line chart line sparkline indicates change in values over a period of time with the help of a lineColumn Similar to column charts column sparkline uses vertical columns to demonstrate pattern acrossdifferent categoriesWinLoss Similar to column sparkline winloss sparkline uses vertical columns to represent values However itdoes not indicate the magnitude and is generally used to indicate the binary data

To display the data markers on sparkline you can set the ShowMarkers property to true The Sparkline class alsoprovides properties to highlight the first last highest lowest or negative data points by displaying them in differentformat You can even style the sparklines using the Styles property

Below code shows how to add sparkline to the WinForms FlexGrid columns

WinLossSparklineを表示するようにプロパティを設定します c1FlexGrid1Cols[2]ShowSparkline = true c1FlexGrid1Cols[2]SparklineSparklineType = SparklineTypeWinLoss c1FlexGrid1Cols[2]SparklineStylesSeriesColor = ColorGreen c1FlexGrid1Cols[2]SparklineShowNegative = true

C

WinLossSparklineを表示するようにプロパティを設定します c1FlexGrid1Cols(2)ShowSparkline = True c1FlexGrid1Cols(2)SparklineSparklineType = SparklineTypeWinLoss c1FlexGrid1Cols(2)SparklineStylesSeriesColor = ColorGreen c1FlexGrid1Cols(2)SparklineShowNegative = True

VBNET

ヘッダとフッタ

Column header refers to the fixed rows on the top of the grid which contains a caption string sort glyph etc

In FlexGrid by default the top row with zero index is allocated for the column header However you can span the header to other rows aswell by specifying them as fixed To set more than one rows as fixed you need to set the Fixed property of RowCollection class to an integergreater than 1

FlexGrid for WinForms

73 Copyright copy GrapeCity Inc All rights reserved

Set Header TextFlexGrid when in bound mode reads the field names from the data source and renders them as column header text However youcan explicitly set Caption property of the Row class to overwrite field name string from the data source In case of unbound grid as well theCaption property specifies the header text Note that this property sets the value of cells in the default header row at zero index To setvalue in the other fixed row cells you need to use the usual value allocation ways of FlexGrid For more information on how to set cellvalues see Set Value in Cell

Specify the header rows and set the header text in WinForms FlexGrid using the code below

Merge Column HeaderFlexGrid provides the AllowMerging property for Row object which specifies whether it is allowed to merge cells in a particular row (in thiscase the header row) or not Once you have allowed merging in the header row set either AllowMerging or AllowMergingFixed propertyof C1FlexGrid class to FixedOnly Availability of these two properties in the FlexGrid control offers you more flexibility to implement multiplelogics related to merging For more information on merging cells see Merge

Use the code below to merge column headers in the WinForms FlexGrid

Wrap Column Header Text

2つの行を列ヘッダ行として設定しますc1FlexGrid1RowsFixed = 2 最初の列のヘッダとサブヘッダを設定しますc1FlexGrid1Cols [1] Caption = Column Header 1c1FlexGrid1 [11] = Column Sub-header 1

C

2つの行を列ヘッダー行として設定します c1FlexGrid1RowsFixed = 2

最初の列のヘッダとサブヘッダを設定します c1FlexGrid1Cols(1)Caption = Column Header 1 c1FlexGrid1(1 1) = Column Sub-header 1

VBNET

ヘッダ行でのマージを許可しますc1FlexGrid1Rows[0]AllowMerging = true

グリッドのAllowMergingまたはAllowMergingFixedプロパティを設定して固定行のみを結合します c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

ヘッダ行でのマージを許可しますc1FlexGrid1Rows(0)AllowMerging = True

グリッドのAllowMergingまたはAllowMergingFixedプロパティを設定して固定行のみを結合します c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

FlexGrid for WinForms

74 Copyright copy GrapeCity Inc All rights reserved

To wrap the text in column header access the CellStyle item Fixed of the CellStyleCollection class and set its WordWrap property totrue Note that to view the wrapped text properly you need to adjust the row height or just call the AutoSizeRow() method to automaticallyresize the row according to the text length

Use the code below to wrap header text of the WinForms FlexGrid columns

Style Column HeaderTo style the column header you can access the CellStyle item Fixed of the CellStyleCollection class and set various styling relatedproperties for same such as Font ForeColor and TextEffect

Customize column header of the WinForms FlexGrid using the code below

Set Column FooterColumn Footer refers to the last row of the grid which displays additional information about the whole column Most common use ofcolumn footer is to show the summary of column data

In FlexGrid you can create the column footer by using Footers property of the C1FlexGrid class FlexGrid lets you choose whether toscroll the footer along with rows or keep it fixed at the bottom of the grid by using Fixed property of the Footers class This class alsoprovides the Descriptions property which accesses the FooterDescription collection to set the additional information such as Caption Todisplay aggregate result in the column footer through various aggregate functions you must access the AggregateDefinition collection

列のキャプションを設定しますc1FlexGrid1Cols[3]Caption = Large Text for Column Header Text Wrapping

行の高さを設定しますc1FlexGrid1Rows[0]Height = 50

固定の行と列のワードラップを設定しますc1FlexGrid1Styles[Fixed]WordWrap = true

C

列のキャプションを設定しますc1FlexGrid1Cols(3)Caption = Large Text for Column Header Text Wrapping

行の高さを設定しますc1FlexGrid1Rows(0)Height = 50

固定の行と列のワードラップを設定しますc1FlexGrid1Styles(Fixed)WordWrap = True

VBNET

ヘッダテキストのフォントを設定しますc1FlexGrid1Styles[Fixed]Font = new Font(Tahoma 10 FontStyleBold) ヘッダテキストの前色を設定しますc1FlexGrid1Styles[Fixed]ForeColor = ColorAqua ヘッダーテキストの背景色を設定しますc1FlexGrid1Styles[Fixed]BackColor = ColorBlue

ヘッダテキストにテキスト効果を適用しますc1FlexGrid1Styles[Fixed]TextEffect = C1WinC1FlexGridTextEffectEnumRaised

C

ヘッダテキストのフォントを設定します c1FlexGrid1Styles(Fixed)Font = New Font(Tahoma 10 FontStyleBold)

ヘッダテキストの前色を設定します c1FlexGrid1Styles(Fixed)ForeColor = ColorAqua

ヘッダーテキストの背景色を設定します c1FlexGrid1Styles(Fixed)BackColor = ColorBlue

ヘッダテキストにテキスト効果を適用します c1FlexGrid1Styles(Fixed)TextEffect = C1WinC1FlexGridTextEffectEnumRaised

VBNET

FlexGrid for WinForms

75 Copyright copy GrapeCity Inc All rights reserved

using Aggregates property of the FooterDescription class Aggregate functions can be specified using the Aggregate property whichaccepts values from AggregateEnum enumeration

Following code shows how to add a column footer in the WinForms FlexGrid

列にフッタを追加しますc1FlexGrid1FootersDescriptionsAdd(new C1WinC1FlexGridFooterDescription() Caption = Total ) フッタに集計を適用しますc1FlexGrid1FootersDescriptions[0]AggregatesAdd(new C1WinC1FlexGridAggregateDefinition() Column = 4 Aggregate = C1WinC1FlexGridAggregateEnumSum )

C

列にフッタを追加しますc1FlexGrid1FootersDescriptionsAdd(New C1WinC1FlexGridFooterDescription() With Caption = Total )

フッタに集計を適用しますc1FlexGrid1FootersDescriptions(0)AggregatesAdd(New C1WinC1FlexGridAggregateDefinition() With Column = 4 Aggregate = C1WinC1FlexGridAggregateEnumSum )

VBNET

サイズ変更

Set Column WidthFlexGrid provides the DefaultSize property of ColumnCollection class to set the column width across the grid You canalso specify the width of a particular column by setting the Width property of the Column class Default value ofWidth property is -1 which indicates that the column is taking width specified by the DefaultSize property The Widthproperty is also available at design time through the C1FlexGrid Column Editor For more information on columneditor see Editors

Use the code below to set the default width of a column of the WinForms FlexGrid

Auto-adjust Column WidthTo adjust the column width according to the text length FlexGrid provides the AutoSizeCol() and AutoSizeCols()methods While AutoSizeCol() method automatically adjusts width of the specified column the AutoSizeCols()method is used for cell ranges

Following code shows how you can auto adjust the column widths according to the text length in the WinFormsFlexGrid

すべての列のデフォルト幅を設定しますc1FlexGrid1ColsDefaultSize = 110最初の列の幅を設定しますc1FlexGrid1Cols [1] Width = 30

C

すべての列のデフォルト幅を設定します c1FlexGrid1ColsDefaultSize = 110最初の列の幅を設定します c1FlexGrid1Cols(1)Width = 30

VBNET

FlexGrid for WinForms

76 Copyright copy GrapeCity Inc All rights reserved

Set MinMax Column WidthFlexGrid allows you to set bounds to the column width by using the MinSize and MaxSize propertiesof ColumnCollection This feature is especially useful in scenarios such as when AllowResizing property is set to trueor while using the AutoSizeCol or AutoSizeCols method

Specify the bounds of column width in the WinForms FlexGrid using the code below

Star SizingStar sizing refers to proportional sizing of grid columns to occupy the available space so that layout of grid remainssame even on resizing For instance consider a grid with 5 columns whose star sizes are specified as 3 2 and In this case first fourth and fifth column always take the same width and grid allocates thrice the width of firstcolumn to the second and twice the width to third column

テキストの長さに応じて最初の列の幅を自動調整しますc1FlexGrid1AutoSizeCol(1) 列の幅を1番目から4番目まで自動調整しますc1FlexGrid1AutoSizeCols(1 4 2)

すべての列の幅を自動調整します c1FlexGrid1AutoSizeCols()

C

テキストの長さに応じて最初の列の幅を自動調整しますc1FlexGrid1AutoSizeCol(1)

列の幅を1番目から4番目まで自動調整しますc1FlexGrid1AutoSizeCols(1 4 2)

すべての列の幅を自動調整します c1FlexGrid1AutoSizeCols()

VBNET

列コレクションの最小幅を設定します c1FlexGrid1ColsMinSize = 20 列コレクションの最大幅を設定します c1FlexGrid1ColsMaxSize = 60

C

列コレクションの最小幅を設定します c1FlexGrid1ColsMinSize = 20

列コレクションの最大幅を設定します c1FlexGrid1ColsMaxSize = 60

VBNET

FlexGrid for WinForms

77 Copyright copy GrapeCity Inc All rights reserved

FlexGrid provides the StarWidth property of Column class to specify the star sizes of columns To restrict the widthsfrom getting too narrow or too wide you can set the MinWidth and MaxWidth properties These properties are alsoavailable through the C1FlexGrid Column Editor For more information on column editor see Editors

Set star sizing or proportional sizing in the WinForms FlexGrid columns using the code below

列のスターサイズを設定しますc1FlexGrid1Cols[1]StarWidth = c1FlexGrid1Cols[2]StarWidth = 3c1FlexGrid1Cols[3]StarWidth = 2c1FlexGrid1Cols[4]StarWidth = c1FlexGrid1Cols[5]StarWidth =

列が狭くなりすぎないようにMinWidthプロパティを設定しますc1FlexGrid1Cols[1]MinWidth = 50

C

列のスターサイズを設定しますc1FlexGrid1Cols(1)StarWidth = c1FlexGrid1Cols(2)StarWidth = 3c1FlexGrid1Cols(3)StarWidth = 2c1FlexGrid1Cols(4)StarWidth = c1FlexGrid1Cols(5)StarWidth =

列が狭くなりすぎないようにMinWidthプロパティを設定しますc1FlexGrid1Cols(1)MinWidth = 50

VBNET

FlexGrid for WinForms

78 Copyright copy GrapeCity Inc All rights reserved

A grid control is a collection of rows and columns Columns generally contain a particular type of information through out while rows are used to recorddifferent types of information about a particular item

In FlexGrid the collection of rows is represented by the RowCollection class which can be accessed through Rows property of the C1FlexGrid class Thissection discusses the various operations that can be performed on rows

Topic Snapshot Content

Basic Operations Discusses about how to perform basic row operations

Set Row CountAdd RowDelete RowInsert RowSet Data TypeSet Fixed RowSet Frozen Row

User Interaction Discusses about operations that can be performed by the end-user at run time

Allow AddingAllow DeletingAllow DraggingAllow FreezingAllow Resizing

Header Discusses about how to set row header and perform other related operations

Set Header TextMerge Row HeaderWrap Row Header TextStyle Row Header

Row Detail Discusses how to display additional information using row detail feature

In-form EditingHierarchical ViewCustom Row Details

Sizing Discusses about various aspects of row sizing

Set Row HeightAuto-adjust Row HeightSet MinMax Row Height

基本操作

This topic discusses various basic operations which can be performed on a row

Set Row CountWhen grid is bound to a data source the number of rows is determined by the number of records available in thedata source However in the case of unbound mode you can set any integer value in Count property ofthe RowCollection class to set the number of rows to be displayed in the grid

Use the code below to set row count in the WinForms FlexGrid

Set row count c1FlexGrid1RowsCount = 15

C

VBNET

FlexGrid for WinForms

79 Copyright copy GrapeCity Inc All rights reserved

Add RowFlexGrid provides various ways to add a new row at runtime You can either use Add method of the RowCollectionclass or AddItem method of the C1FlexGrid class to add a new record In the unbound mode you can also incrementthe value of Count property to add new rows Note that all these ways add rows towards the end of the grid To inserta row at a specific location see Insert Row Also note that an exception is thrown if a new row is added to a boundgrid using Count property

Add a row to WinForms FlexGrid using any of these approaches shown in the code below

Delete RowTo delete a particular row from the grid you can use Remove method of the RowCollection class and specify the rowyou want to delete as its parameter The RowCollection class also provides RemoveRange method which allows you

Set row countc1FlexGrid1RowsCount = 15

Approach1 Use the RowCollectionAdd method to add row C1WinC1FlexGridRow r r = c1FlexGrid1RowsAdd() Set data r[1] = New Row 2

Approach2 Use AddItem method to add row and set data c1FlexGrid1AddItem( + t + New Row 1) Approach3 Use the RowCollectionCount property to add row c1FlexGrid1RowsCount += 1 Set data c1FlexGrid1[c1FlexGrid1RowsCount - 1 1] = New Row 3

C

Approach1 Use the RowCollectionAdd method to add row Dim r As C1WinC1FlexGridRow r = c1FlexGrid1RowsAdd()

Set data r(1) = New Row 2

Approach2 Use AddItem method to add row and set data c1FlexGrid1AddItem( amp vbTab amp New Row 1)

Approach3 Use the RowCollectionCount property to add row c1FlexGrid1RowsCount += 1

Set data c1FlexGrid1(c1FlexGrid1RowsCount - 1 1) = New Row 3

VBNET

FlexGrid for WinForms

80 Copyright copy GrapeCity Inc All rights reserved

to remove a range of rows using a single call Similarly you can also use RemoveItem method of the C1FlexGridclass to remove a specific row In the unbound grid you can reduce the number of rows by changing the value ofCount property

Following code gives different approaches to delete row from the WinForms FlexGrid

Insert RowTo insert a row in FlexGrid at a specific location you can use Insert method of the RowCollection class which lets youspecify the position where rows are to be inserted You can also insert multiple rows in the grid by usingthe InsertRange method

Below code demonstrates how to insert a row at a particular position in the WinForms FlexGrid

Approach1 Remove second row using RowCollectionRemove methodc1FlexGrid1RowsRemove(2)

Approach1 Remove second row using the RemoveItem methodc1FlexGrid1RemoveItem(2)

Approach3 Remove 3 rows starting from second using the RemoveRange methodc1FlexGrid1RowsRemoveRange(2 3) Approach4 Remove last row using the RowCollectionCount property c1FlexGrid1RowsCount -= 1

C

Approach1 Remove second row using RowCollectionRemove method c1FlexGrid1RowsRemove(2)

Approach1 Remove second row using the RemoveItem method c1FlexGrid1RemoveItem(2)

Approach3 Remove 3 rows starting from second using the RemoveRange method c1FlexGrid1RowsRemoveRange(2 3)

Approach4 Remove last row using the RowCollectionCount property c1FlexGrid1RowsCount -= 1

VBNET

C1WinC1FlexGridRow r Approach1 Use the Insert method to insert row at second position r = c1FlexGrid1RowsInsert(2) r[1] = Inserted row Approach2

C

FlexGrid for WinForms

81 Copyright copy GrapeCity Inc All rights reserved

Set Data TypeIn case of a bound FlexGrid data type of each bound column is automatically picked from the data source dependingon the data However in the case of unbound mode you can set the data type of rows or columns by specifyingthe DataType property of Row or Column class respectively Note that when data type is set for both rows andcolumns column settings take preference over row settings

Use the code below to set data type of a WinForms FlexGrid row

Set Fixed RowFixed rows refer to the rows with non-editable cells which are always visible on top of the grid even when user scrollsdown the grid In FlexGrid fixed rows can be set using Fixed property of the RowCollection class This propertyaccepts an integer value that specifies the number of rows to be fixed

Set fixed rows in the WinForms FlexGrid using the code below

Set Frozen RowFrozen rows similar to fixed rows are non-scrollable but can be edited by the user In FlexGrid frozen rows can be set

Use the InsertRange method to add three rows at second position c1FlexGrid1RowsInsertRange(2 3)

Dim r As C1WinC1FlexGridRow Approach1 Use the Insert method to insert row at second position r = c1FlexGrid1RowsInsert(2) r(1) = Inserted row

Approach2 Use the InsertRange method to add three rows at second position c1FlexGrid1RowsInsertRange(2 3)

VBNET

C1WinC1FlexGridRow r r = c1FlexGrid1RowsAdd() rDataType = typeof(int)

C

Dim r As C1WinC1FlexGridRow r = c1FlexGrid1RowsAdd() rDataType = GetType(int)

VBNET

Set three rows as fixed c1FlexGrid1RowsFixed = 3

C

Set three rows as fixedc1FlexGrid1RowsFixed = 3

VBNET

FlexGrid for WinForms

82 Copyright copy GrapeCity Inc All rights reserved

by using Frozen property provided by the RowCollection class

Use the code below to set frozen rows in the WinForms FlexGrid

Set first two rows as frozen c1FlexGrid1RowsFrozen = 2

C

Set first two rows as frozen c1FlexGrid1RowsFrozen = 2

VBNET

ユーザー操作

This topic discusses how you can let end-users interact with the FlexGrid rows

Allow AddingBy default FlexGrid does not allow end-user to add new row to the grid To provide an option to add rows at runtimeyou can set AllowAddNew property of the C1FlexGrid class to true FlexGrid also provides a design-time optionEnable Adding Rows in C1FlexGrid Tasks menu to allow adding new row by the end-user For more information ontask menus see Tasks Menus Moreover you can also set watermark text to be displayed in the new row templatethrough NewRowWatermark property

Use the code below to allow users to add rows in WinForms FlexGrid at run-time

Allow user to add rows c1FlexGrid1AllowAddNew = true Set watermark in the template new row c1FlexGrid1NewRowWatermark = Add new row

C

Allow user to add rows c1FlexGrid1AllowAddNew = True

Set watermark in the template new row

VBNET

FlexGrid for WinForms

83 Copyright copy GrapeCity Inc All rights reserved

Allow DeletingFlexGrid by default does not allow end-user to delete rows from the grid However if your application requires youcan let the end-user delete the selected rows through Delete key by setting AllowDelete property to true You canalso enable row deletion by checking ON the Enable Deleting Rows checkbox on the C1FlexGrid Tasks menu

Following code shows how to allow users to delete rows from WinForms FlexGrid at run-time

Allow DraggingFlexGrid by default does not allow user to rearrange rows by dragging However you can change this behavior inunbound grid by using the FlexGridAllowDragging property and RowAllowDragging property To enable dragging ofgrid rows you can set the FlexGridAllowDragging property to either Rows or Both This property accepts the valuesfrom AllowDraggingEnum You can also disable dragging of a particular row by setting the RowAllowDraggingproperty to false

Note As moving a row is not allowed in bound mode the bound grid throws an exception on dragging arow To implement dragging in bound mode see the blog Drag and Drop Rows in C1Flexgrid

Let users drag the rows in an unbound WinForms FlexGrid at run-time by using the code below

Allow FreezingTo allow end user to freeze the rows at runtime you can use AllowFreezing property of the C1FlexGrid class whichaccepts values from AllowFreezingEnum When this property is set to Rows or Both a lock sign appears when mouseis hovered over the edge of header row End-user can click and drag the lock sign to freeze the rows

Use the code below to allow your users to freeze the WinForms FlexGrid rows at run-time

c1FlexGrid1NewRowWatermark = Add new row

Allow user to delete rowsc1FlexGrid1AllowDelete = true

C

Allow user to delete rowsc1FlexGrid1AllowDelete = True

VBNET

Allow dragging of all rows across the grid c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumRows Disable dragging of a particular row c1FlexGrid1Rows[3]AllowDragging = false

C

Allow dragging of all rows across the grid c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumRows

Disable dragging of a particular row c1FlexGrid1Rows(3)AllowDragging = False

VBNET

FlexGrid for WinForms

84 Copyright copy GrapeCity Inc All rights reserved

Allow ResizingBy default FlexGrid does not give option to resize the rows To change this behavior you can use AllowResizingproperty of the C1FlexGrid class This property accepts values from the AllowResizingEnum enumerationwhich enables end-user to change size of columns rows or both The enumeration also gives you options touniformly resize the rows columns or both that is if you resize one of the columns or rows the grid automaticallyresizes rest of the columns or rows as well FlexGrid also provides RowAllowResizing property which is Boolean typeand lets you enable or disable resizing of a particular row

Following code shows how to allow users to resize the WinForms FlexGrid rows at run-time

Allow freezing of rows at runtimec1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumRows

C

Allow freezing of rows at runtimec1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumRows

VBNET

Allow user to resize rows c1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumRows Stop user from resizing second row c1FlexGrid1Rows[2]AllowResizing = false

C

Allow user to resize rows c1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumRows

Stop user from resizing second row c1FlexGrid1Rows(2)AllowResizing = False

VBNET

ヘッダ

Row header refers to the fixed rows on the left hand side of the grid which may or may not contain the caption string

In FlexGrid by default the left most column with zero index is allocated for the row header However you can span theheader to other columns as well by specifying them as fixed To set more than one column as fixed you need toset the Fixed property of ColumnCollection class to an integer greater than 1

FlexGrid for WinForms

85 Copyright copy GrapeCity Inc All rights reserved

Set Header TextTo set the row header text you can set Caption property of the Row class Note that this property sets the value of cellsin the default header column at zero index To set value in the other fixed column cells you need to use the usual valueallocation ways of FlexGrid For more information on how to set cell values see Set Value in Cell

Specify the header column and set the header text in WinForms FlexGrid using the code below

Merge Row HeaderFlexGrid provides AllowMerging property of the Column class which specifies whether it is allowed to merge cells in aparticular column (in this case the header column) or not Once you have allowed merging in the header columnset either AllowMerging or AllowMergingFixed property of the C1FlexGrid class to FixedOnly Availability of these twoproperties in the FlexGrid control offers you more flexibility to implement multiple logics related to merging For moreinformation on merging cells see Merge

Set header for first rowc1FlexGrid1Rows[1]Caption = Row 1

Set header for all rowsfor (int i = c1FlexGrid1RowsFixed i lt c1FlexGrid1RowsCount i++) c1FlexGrid1[i 0] = Row + iToString()

Set column widthc1FlexGrid1Cols[0]Width = 85

C

Set header for first row c1FlexGrid1Rows(1)Caption = Row 1

Set header for all rows For i As Integer = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 c1FlexGrid1(i 0) = Row amp iToString() Next

Set column width c1FlexGrid1Cols(0)Width = 85

VBNET

FlexGrid for WinForms

86 Copyright copy GrapeCity Inc All rights reserved

Use the code below to merge row headers in the WinForms FlexGrid

Wrap Row Header TextTo wrap the text in row header access the CellStyle item Fixed of the CellStyleCollection class and set its WordWrapproperty to true Note that to view the wrapped text properly you need to adjust height of FlexGrid rows or just callthe AutoSizeRow() method to automatically resize the rows according to the length of text

Use the code below to wrap header text of the WinForms FlexGrid rows

Style Row HeaderTo style the row header you can access the CellStyle item Fixed of the CellStyleCollection class and set variousstyling related properties for same such as Font ForeColor and TextEffect

Allow merging on the header columnc1FlexGrid1Cols[0]AllowMerging = true

Set AllowMerging or AllowMergingFixed property of the grid to merge fixed rowcolumns only c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

Allow merging on the header columnc1FlexGrid1Cols(0)AllowMerging = True

Set AllowMerging or AllowMergingFixed property of the grid to merge fixed rowcolumns only c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

Set row captionc1FlexGrid1Rows[3]Caption = Large text to display text wrapping and mergingc1FlexGrid1Rows[4]Caption = Large text to display text wrapping and merging Set row heightc1FlexGrid1Rows[3]Height = 35c1FlexGrid1Rows[4]Height = 35

Set word wrapping for fixed rows and columnsc1FlexGrid1Styles[Fixed]WordWrap = true

C

Set row captionc1FlexGrid1Rows(3)Caption = Large text to display text wrapping and mergingc1FlexGrid1Rows(4)Caption = Large text to display text wrapping and merging

Set row heightc1FlexGrid1Rows(3)Height = 35c1FlexGrid1Rows(4)Height = 35

Set word wrapping for fixed rows and columnsc1FlexGrid1Styles(Fixed)WordWrap = True

VBNET

FlexGrid for WinForms

87 Copyright copy GrapeCity Inc All rights reserved

Customize row header of the WinForms FlexGrid using the code below

Set font of the header textc1FlexGrid1Styles[Fixed]Font = new Font(Tahoma 10 FontStyleBold) Set forecolor of the header textc1FlexGrid1Styles[Fixed]ForeColor = ColorPaleVioletRed Set backcolor of the header textc1FlexGrid1Styles[Fixed]BackColor = ColorLemonChiffon Apply text effect on the header textc1FlexGrid1Styles[Fixed]TextEffect = C1WinC1FlexGridTextEffectEnumInset

C

Set font of the header text c1FlexGrid1Styles(Fixed)Font = New Font(Tahoma 10 FontStyleBold)

Set forecolor of the header text c1FlexGrid1Styles(Fixed)ForeColor = ColorPaleVioletRed

Set backcolor of the header text c1FlexGrid1Styles(Fixed)BackColor = ColorLemonChiffon

Apply text effect on the header text c1FlexGrid1Styles(Fixed)TextEffect = C1WinC1FlexGridTextEffectEnumInset

VBNET

行の詳細

Row detail is a feature to provide additional information related to a row or record in the form of another expandablelayer In such case row which is the first layer contains the basic information while the second layer contains the detailedinformation This feature is specially useful when the additional information is too large to be displayed in the availablescreen space or it is not consistent for every record

FlexGrid for WinForms

88 Copyright copy GrapeCity Inc All rights reserved

FlexGrid provides the row detail feature using IC1FlexGridRowDetail interface which is implemented by the detail controls tobe hosted on detail row In addition FlexGrid also provides a separate assembly C1WinC1FlexGridRowDetails452dllto provide template user controls InputPanel and FlexGrid ready to be used in detail row You can add details section toany row in FlexGrid which enables you to group data in a template which is visible optionally This allows users to viewadditional data related to a row by simply selecting the row The grid also provides built-in expand or collapse buttons tocontrol the visibility of data within the expandable row

Some common use case scenarios of row detail feature are

1 In-form editing where an InputPanel control is hosted to get input from the user to fill information in a record2 Hierarchical grid which contains a master grid and a detail grid to show additional information about the record3 Custom row details where any control can be used to create row detail template

Detailed implementation of these scenarios is given in their respective sections below

In-form EditingFlexGrid supports in-form editing by hosting InputPanel control in detail row The InputPanel control contains data fieldswhere user can enter or edit the values like a form Once user finishes editing fields those values get reflected in theselected row

FlexGrid for WinForms

89 Copyright copy GrapeCity Inc All rights reserved

In FlexGrid you can implement in-form editing by adding reference to C1WinC1FlexGridRowDetails452dll and usingthe C1InputPanelRowDetail class which already implements the IC1FlexGridRowDetail interface The instance of this classis then assigned to RowDetailProvider property of the C1FlexGrid class which adds the InputPanel control to detail rowand enables the in-form editing

Hierarchical ViewHierarchical view refers to master-detail model where top level grid is the master grid and nested grid is the detail gridwhich displays additional information about expanded row of the master grid For instance example below demonstratesthe master-detail structure using Customer and Order tables respectively with CustomerID as common data element todefine a relation

flexGridRowDetailProvider = (g r) =gt new C1InputPanelRowDetail()flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected

C

flexGridRowDetailProvider = Function(g r) New C1InputPanelRowDetail()flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected

VBNET

FlexGrid for WinForms

90 Copyright copy GrapeCity Inc All rights reserved

In FlexGrid you can implement hierarchical grid by adding reference to C1WinC1FlexGridRowDetails452dll and usingthe C1FlexGridRowDetail class which already implements the IC1FlexGridRowDetail interface The instance of this class isthen assigned to RowDetailProvider property of the C1FlexGrid class to nest another grid in the detail row which enablesthe hierarchical grid interface

private void FlexGrid_Load(object sender EventArgs e) string conn = UtilGetConnectionString() var ds = new DataSet() string[] tables = Customers OrdersSplit() foreach (string tableName in tables) UtilFillTable(ds tableName conn) Defining relation between master and detail grid dsRelationsAdd(Customers_Orders dsTables[Customers]Columns[CustomerID] dsTables[Orders]Columns[CustomerID]) flexGridDataSource = ds flexGridDataMember = Customers flexGridRowDetailProvider = (g r) =gt new C1FlexGridRowDetail() flexGridAreRowDetailsFrozen = false

C

Private Sub FlexGrid_Load(ByVal sender As Object ByVal e As EventArgs) Dim conn As String = UtilGetConnectionString() Dim ds = New DataSet() Dim tables As String() = Customers OrdersSplit(c)

For Each tableName As String In tables UtilFillTable(ds tableName conn) Next Defining relation between master and detail grid dsRelationsAdd(Customers_Orders dsTables(Customers)Columns(CustomerID) dsTables(Orders)Columns(CustomerID))

VBNET

FlexGrid for WinForms

91 Copyright copy GrapeCity Inc All rights reserved

Custom Row DetailsIn addition to the InputPanel and FlexGrid control you can also host a custom control in the detail row of a grid Forinstance in the example below a text label control is attached to the row to enlist the additional information withoutaffecting the dimensions of the grid

To implement the custom row details in FlexGrid you need to create a user control which implementsthe IC1FlexGridRowDetail interface For instance here we have created a class named CustomRowDetail which representsthe text label control to be hosted in the detail row You then need to assign an object of this class to RowDetailProviderproperty of the C1FlexGrid class to enable the custom control to display additional information in the detail row

flexGridDataSource = ds flexGridDataMember = Customers flexGridRowDetailProvider = Function(g r) New C1FlexGridRowDetail() flexGridAreRowDetailsFrozen = False End Sub

private void CustomSample_Load(object sender EventArgs e) flexGridDataSource = DemoDataSource(Employees) flexGridRowDetailProvider = (g r) =gt new CustomRowDetail() flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected flexGridCols[Notes]Visible = false

Custom row detail class which shows label with notes about employee public class CustomRowDetail C1Label IC1FlexGridRowDetail Used to setup control before showing the FlexGrid detail control void IC1FlexGridRowDetailSetup(C1FlexGrid parentGrid int rowIndex) var bs = new BindingSource(parentGridDataSource parentGridDataMember) bsPosition = parentGridRows[rowIndex]DataIndex DataField = Notes DataSource = bs

C

FlexGrid for WinForms

92 Copyright copy GrapeCity Inc All rights reserved

Used to update size of the FlexGrid detail control void IC1FlexGridRowDetailUpdateSize(C1FlexGrid parentGrid int rowIndex Size proposedSize) var srSz = parentGridScrollableRectangleSize var sz = TextRendererMeasureText(Text Font srSz TextFormatFlagsWordBreak) szWidth = MathMax(szWidth srSzWidth) Size = sz

Private Sub CustomSample_Load(ByVal sender As Object ByVal e As EventArgs) flexGridDataSource = DemoDataSource(Employees) flexGridRowDetailProvider = Function(g r) New CustomRowDetail() flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected flexGridCols(Notes)Visible = False End Sub

Custom row detail class which shows label with notes about employee Public Class CustomRowDetail Inherits C1Label Implements IC1FlexGridRowDetail

Used to setup control before showing the FlexGrid detail control Private Sub Setup(ByVal parentGrid As C1FlexGrid ByVal rowIndex As Integer) Dim bs = New BindingSource(parentGridDataSource parentGridDataMember) bsPosition = parentGridRows(rowIndex)DataIndex DataField = Notes DataSource = bs End Sub

Used to update size of the FlexGrid detail control Private Sub UpdateSize(ByVal parentGrid As C1FlexGrid ByVal rowIndex As Integer ByVal proposedSize As Size) Dim srSz = parentGridScrollableRectangleSize Dim sz = TextRendererMeasureText(Text Font srSz TextFormatFlagsWordBreak) szWidth = MathMax(szWidth srSzWidth) Size = sz End Sub End Class

VBNET

サイズ変更

Set Row HeightFlexGrid provides DefaultSize property of the RowCollection class to set row height across the grid You can alsospecify the height of a particular row by setting Height property of the Row class Default value of the Heightproperty is -1 which indicates that the row is taking height specified by the DefaultSize property

Use the code below to set the default height of a row of the WinForms FlexGrid

Set the default size of all rowsc1FlexGrid1RowsDefaultSize = 50

C

FlexGrid for WinForms

93 Copyright copy GrapeCity Inc All rights reserved

Auto-adjust Row HeightTo adjust the row height according to text length and word wrapping options FlexGrid provides the AutoSizeRow()and AutoSizeRows() methods While AutoSizeRow() method automatically adjusts height of the specified row theAutoSizeRows() method is used for cell ranges

Following code shows how you can auto adjust the row height according to the text length in the WinForms FlexGrid

Set MinMax Row HeightFlexGrid allows you to set bounds to the row height by using the MinSize and MaxSize propertiesof the RowCollection class This feature is especially useful in scenarios such as when AllowResizing property is set totrue or while using the AutoSizeRow() or AutoSizeRows() method

Specify the bounds of row height in the WinForms FlexGrid using the code below

Set the height of a particular rowc1FlexGrid1Rows[1]Height = 55

Set the default size of all rowsc1FlexGrid1RowsDefaultSize = 50

Set the height of a particular rowc1FlexGrid1Rows(1)Height = 55

VBNET

Adjust the height of fourth row automaticallyc1FlexGrid1AutoSizeRow(4) Adjust the height of all rows automatically c1FlexGrid1AutoSizeRows() Adjust the height of cell range automaticallyc1FlexGrid1AutoSizeRows(2 4 5 6 10 C1WinC1FlexGridAutoSizeFlagsNone)

C

Adjust the height of fourth row automatically c1FlexGrid1AutoSizeRow(4)

Adjust the height of all rows automatically c1FlexGrid1AutoSizeRows()

Adjust the height of cell range automatically c1FlexGrid1AutoSizeRows(2 4 5 6 10 C1WinC1FlexGridAutoSizeFlagsNone)

VBNET

Set the maximum height of rowc1FlexGrid1RowsMaxSize = 50 Set the minimum height of rowc1FlexGrid1RowsMinSize = 20

C

FlexGrid for WinForms

94 Copyright copy GrapeCity Inc All rights reserved

Set the maximum height of rowc1FlexGrid1RowsMaxSize = 50

Set the minimum height of row c1FlexGrid1RowsMinSize = 20

VBNET

FlexGrid for WinForms

95 Copyright copy GrapeCity Inc All rights reserved

セル

Cell is the smallest unit of a grid Although in most common scenarios we prefer working on row or column levelthere are some operations which are required to be carried out on the cell level Getting setting or removing data arefew to name

Topic Snapshot Content

Basic Operations Discusses how to perform basic operations related to a cell

Set Value in CellSet Values in Cell RangeClear Value from Cell (Range)Set Image in CellDisplay Tooltip in CellRetrieve Cell Values

Cell Format Discusses how to format cell or cell data in various scenarios

Cell ContentCell AppearanceConditional FormattingOwner Drawn Cell

基本操作

Set Value in CellFlexGrid provides two ways to set values in cell You can either use Item property (indexer) or SetData method of the C1FlexGrid class

Use the code below to set a value in the WinForms FlexGrid cell

Set Values in Cell RangeTo set values in a cell range you can either use Data property of the CellRange class or SetData method of the C1FlexGrid class

Following code shows how to set values in a cell range in WinForms FlexGrid

インデックスを使用してデータを設定しますc1FlexGrid1[2 3] = 2nd col 3rd row SetDataメソッドを使用してデータを設定しますc1FlexGrid1SetData(2 4 2nd col 4th row)

C

インデックスを使用してデータを設定します c1FlexGrid1(2 3) = 2nd col 3rd row

SetDataメソッドを使用してデータを設定します c1FlexGrid1SetData(2 4 2nd col 4th row)

VBNET

セル範囲を取得しますC1WinC1FlexGridCellRange cr = c1FlexGrid1GetCellRange(2 3 5 6) 方法1dataプロパティを使用してセル範囲にデータを設定しますcrData = Cell Range

C

FlexGrid for WinForms

96 Copyright copy GrapeCity Inc All rights reserved

Clear Value from Cell (Range)There are two ways by which contents of cell or cell range can be cleared You can either chose to do it programmatically by setting thecontent of cell to an empty string using indexer or SetData method Or you can set the AutoClipboard property to true so that user candelete the values by pressing the Delete key

Below code demonstrates how to allow keyboard operations so that user can clear values from WinForms FlexGrid cells

Set Image in CellTo set image in a cell you can use SetCellImage method of the C1FlexGrid class You can also set an image in a cell range by using Imageproperty of the CellRange class By default text and image both are displayed in the cell However you can choose to display only image bysetting the ImageAndText property to false

Use the code below to set image in a WinForms FlexGrid cell

方法2SetDataメソッドを使用してセル範囲にデータを設定します c1FlexGrid1SetData(cr Cell Range)

セル範囲を取得します Dim cr As C1WinC1FlexGridCellRange = c1FlexGrid1GetCellRange(2 3 5 6)

方法1dataプロパティを使用してセル範囲にデータを設定します crData = Cell Range

方法2SetDataメソッドを使用してセル範囲にデータを設定します c1FlexGrid1SetData(cr Cell Range)

VBNET

ユーザーがDeleteキーを押してセルの内容をクリアするなどのキーボード操作を実行できるようにしますc1FlexGrid1AutoClipboard = true

コードを介して特定のセルのデータをクリアしますc1FlexGrid1SetData(3 4 )

C

ユーザーがDeleteキーを押してセルの内容をクリアするなどのキーボード操作を実行できるようにします c1FlexGrid1AutoClipboard = True

コードを介して特定のセルのデータをクリアします c1FlexGrid1SetData(3 4 )

VBNET

セル(36)に画像を設定しますc1FlexGrid1SetCellImage(3 6 ImageFromFile(masterpng))

C

FlexGrid for WinForms

97 Copyright copy GrapeCity Inc All rights reserved

Display Tooltip in CellTo display partially hidden content of cells as tooltip FlexGrid provides ShowCellLabels property of the C1FlexGrid class You can also showadditional information in the form of a tooltip by using the MouseEnterCell and MouseLeaveCell event

Below code shows how to display a tooltip on a WinForms FlexGrid cell

セル範囲(126)から(146)に画像を設定しますC1WinC1FlexGridCellRange crcr = c1FlexGrid1GetCellRange(12 6 14 6)crImage = ImageFromFile(amexjpg)

テキストなしで画像を表示しますc1FlexGrid1Rows[3]ImageAndText = false

セル(36)に画像を設定します c1FlexGrid1SetCellImage(3 6 ImageFromFile(masterpng))

セル範囲(126)から(146)に画像を設定します Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1GetCellRange(12 6 14 6) crImage = ImageFromFile(amexjpg)

テキストなしで画像を表示します c1FlexGrid1Rows(3)ImageAndText = False

VBNET

private void Form1_Load(object sender EventArgs e) このコードはデータを「c1NWindDataSetEmployees」テーブルにロードします 必要に応じて移動または削除できます thisemployeesTableAdapterFill(thisc1NWindDataSetEmployees) for (int i = c1FlexGrid1RowsFixed i lt c1FlexGrid1RowsCount i++) c1FlexGrid1Rows[i]UserData = Employee + c1FlexGrid1[i 2] + + c1FlexGrid1[i 3] private void C1FlexGrid1_MouseEnterCell(object sender C1WinC1FlexGridRowColEventArgs e) if (eRow gt= c1FlexGrid1RowsFixed) string tip tip = c1FlexGrid1Rows[eRow]UserDataToString() ツールチップを表示します toolTip1SetToolTip(c1FlexGrid1 tip)

private void C1FlexGrid1_MouseLeaveCell(object sender C1WinC1FlexGridRowColEventArgs e) ツールチップを非表示にします toolTip1SetToolTip(c1FlexGrid1 )

C

FlexGrid for WinForms

98 Copyright copy GrapeCity Inc All rights reserved

Retrieve Cell ValuesThere are numerous ways using which you can fetch the value of FlexGrid cells depending on your requirement Below tablediscusses several scenarios such as fetching the raw data or formatted data from a single cell or a cell range

Requirement MethodProperty Usage

Get the raw data Item property (indexer) ExampleCode

var data = c1FlexGrid1[1 1] SystemDiagnosticsDebugWriteLine($Cell data data)

GetData() method ExampleCode

var data1 = c1FlexGrid1GetData(1 1) SystemDiagnosticsDebugWriteLine($Cell data data1)

Get the formatted data GetDataDisplay() method ExampleCode

var data2 = c1FlexGrid1GetDataDisplay(1 1) SystemDiagnosticsDebugWriteLine($Display data data2)

Get values of a cell range Clip property ExampleCode

var data3 = c1FlexGrid1Clip SystemDiagnosticsDebugWriteLine($Clip data data3)

GetCellRange method ExampleCode

var data4 = c1FlexGrid1GetCellRange(1 1) SystemDiagnosticsDebugWriteLine($Cell Range data data4Clip)

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) このコードはデータを「c1NWindDataSetEmployees」テーブルにロードします 必要に応じて移動または削除できます MeemployeesTableAdapterFill(Mec1NWindDataSetEmployees)

For i As Integer = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 c1FlexGrid1Rows(i)UserData = Employee amp c1FlexGrid1(i 2) amp + c1FlexGrid1(i 3) Next End Sub

Private Sub C1FlexGrid1_MouseEnterCell(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) If eRow gt= c1FlexGrid1RowsFixed Then Dim tip As String tip = c1FlexGrid1Rows(eRow)UserDataToString() ツールチップを表示します toolTip1SetToolTip(c1FlexGrid1 tip) End If End Sub

Private Sub C1FlexGrid1_MouseLeaveCell(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) ツールチップを非表示にします toolTip1SetToolTip(c1FlexGrid1 ) End Sub

VBNET

FlexGrid for WinForms

99 Copyright copy GrapeCity Inc All rights reserved

セルの書式設定

Cell ContentTo control how content of the cells is formatted and displayed set the Format property of Row or Column object toformat string similar to the ones that are used with StringFormat property in the NET framework For instance thesample code below formats the third column as Date and fourth column as Currency

FlexGrid also provides design time option to set the Format property through the Format String dialog You canaccess the Format String dialog by clicking Ellipsis button against the Format String field in Column Tasks menu Oryou can also use the Format property in C1FlexGrid Column Editor

短い日付形式を設定しますc1FlexGrid1Cols[3]Format = D 通貨形式を設定しますc1FlexGrid1Cols[4]Format = c

C

短い日付形式を設定しますc1FlexGrid1Cols(3)Format = D

通貨形式を設定しますc1FlexGrid1Cols(4)Format = c

VBNET

FlexGrid for WinForms

100 Copyright copy GrapeCity Inc All rights reserved

Note that Format String dialog is specific to column and changes the Format property of the selected column only

Cell AppearanceFlexGrid provides CellStyle objects to handle the appearance aspects of cells such as alignment font colors bordersand so on The grid has Styles property that holds the collection of styles used to format the grid This collection hassome built-in members that define the appearance of grid elements such as fixed and scrollable cells selection focuscell and so on You can change these styles to modify the appearance of grid

Although changing the built-in styles is the simplest way to change appearance of the grid you can also create yourown custom styles and assign them to cells rows or columns

Use the code below to change appearance of the WinForms FlexGrid cells

組み込みのスタイルをカスタマイズしますCellStyle cs = c1FlexGrid1StylesFocus

C

FlexGrid for WinForms

101 Copyright copy GrapeCity Inc All rights reserved

Conditional FormattingTo format a cell according to its content you need to create a new style and apply it to the cells satisfying a particularcondition using SetCellStyle() method For instance to highlight the values greater than a specified value you canformat the cells containing them using different style

Following code shows how to apply conditional formatting on WinForms FlexGrid cells

csFont = new Font(c1FlexGrid1Font FontStyleBold)csForeColor = ColorGreencsBackColor = ColorRed

カスタムスタイルを作成します CellStyle cs1 = c1FlexGrid1StylesAdd(NewStyle)cs1BackColor = ColorAquacs1ForeColor = ColorBlue

カスタムスタイルを割り当てますc1FlexGrid1Cols[3]Style = cs1

Dim cs As CellStyle = c1FlexGrid1StylesFocus csFont = New Font(c1FlexGrid1Font FontStyleBold) csForeColor = ColorGreen csBackColor = ColorRed

Dim cs1 As CellStyle = c1FlexGrid1StylesAdd(NewStyle) cs1BackColor = ColorAqua cs1ForeColor = ColorBlue

c1FlexGrid1Cols(3)Style = cs1

VBNET

CellStyle cs 大きな値のカスタムスタイルを作成しますcs = c1FlexGrid1StylesAdd(LargeValue)csFont = new Font(Font FontStyleItalic)

C

FlexGrid for WinForms

102 Copyright copy GrapeCity Inc All rights reserved

Owner Drawn CellThe above sections explain how you can customize FlexGrid cells to change the appearance of grid using CellStyleobjects However for further customization of grid cells such as rendering gradient background custom graphics etcyou can use DrawMode property and OwnerDrawCell event of the C1FlexGrid class

The DrawMode property determines whether or not the OwnerDrawCell event is fired The event allows you tooverride every visual aspect of the cell You can change the text and image to be displayed in the cell by setting theeText and eImage parameters in the event handler You can also change the style that is used to display the cell bysetting the eStyle property

Note that you should not modify properties of the Style parameter as it might affect other cells Instead assign a newCellStyle object to the Style parameter For example instead of setting eStyleForeColor = ColorRed assign a wholenew style to the parameter using eStyle = c1FlexGrid1Styles[RedStyle]

You can also use your own drawing code to draw into the cell and even combine your custom code with calls to theeDrawCell method For example you can paint the cell background using GDI calls and then call eDrawCell todisplay the cell borders and content

In the example below WinForms FlexGrid uses a gradient brush to paint the background of the selected cell rangeFirst the sample code sets the DrawMode property to OwnerDraw and then declares a LinearGradientBrushobject

csBackColor = ColorGold

for (int row = 1 row lt c1FlexGrid1RowsCount row++)if (ConvertToDouble(c1FlexGrid1[row 4]) gt 80000)c1FlexGrid1SetCellStyle(row 4 cs)

Dim cs As CellStyle

cs = c1FlexGrid1StylesAdd(LargeValue) csFont = New Font(Font FontStyleItalic) csBackColor = ColorGold

For row As Integer = 1 To c1FlexGrid1RowsCount - 1

If ConvertToDouble(c1FlexGrid1(row 4)) gt 80000 Then c1FlexGrid1SetCellStyle(row 4 cs) End If Next

VBNET

SystemDrawingDrawing2DLinearGradientBrush m_GradientBrushprivate void Form1_Load(object sender EventArgs e)

C

FlexGrid for WinForms

103 Copyright copy GrapeCity Inc All rights reserved

所有者描画セルで使用するブラシ m_GradientBrush = new SystemDrawingDrawing2DLinearGradientBrush(ClientRectangle ColorSteelBlue ColorWhite 45)

グラデーションを追加するにはowner-drawを使用します c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw

private void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) グラデーションブラシを使用して選択したセルの背景を描画します if (c1FlexGrid1SelectionContains(eRow eCol)) 背景を描きますeGraphicsFillRectangle(m_GradientBrush eBounds)

グリッドにコンテンツを描画させますeDrawCell(C1WinC1FlexGridDrawCellFlagsContent)

このセルの描画は完了ですeHandled = true

Private m_GradientBrush As DrawingDrawing2DLinearGradientBrush

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) 所有者描画セルで使用するブラシ m_GradientBrush = New DrawingDrawing2DLinearGradientBrush(ClientRectangle ColorSteelBlue ColorWhite 45)

グラデーションを追加するにはowner-drawを使用します c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDrawEnd Sub

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) グラデーションブラシを使用して選択したセルの背景を描画します If c1FlexGrid1SelectionContains(eRow eCol) Then 背景を描きます eGraphicsFillRectangle(m_GradientBrush eBounds)

グリッドにコンテンツを描画させます eDrawCell(C1WinC1FlexGridDrawCellFlagsContent)

このセルの描画は完了です eHandled = True End IfEnd SubEnd IfEnd Sub

VBNET

FlexGrid for WinForms

104 Copyright copy GrapeCity Inc All rights reserved

グリッド

This section discusses about various operations that can be performed on the grid

Topic Snapshot Content

Basic Operations Discusses about basic operations that can be performed on the grid

Transpose Data in GridDisplay Context Menu

Keyboard Navigation Discusses about supperted keys and their operations in

Non-edit ModeEdit Mode

Improve Performance Provides tips and tricks to get best out of your grid by improving its performance

Use Data VirtualizationUse BeginUpdate and EndUpdate MethodsKeep AutoResize Property to False (default)Assign Styles DynamicallyAvoid Modifying Styles in the OwnerDrawCell EventShow Ellipses in a Single ColumnShow Multi-line Text in a CellRetrieve Data Sorting When Bound to a Data TableSpecify Character Limit for Column

基本操作

This topic discusses about various operations that require handling at the grid level

Transpose Data in GridTransposing data refers to swapping column data and row data In WinForms FlexGrid this can be achieved usingTranspose() method of the C1FlexGrid class as shown in the code below

Note that data can be transposed only in the case of unbound grid Also if grid has sorting applied on a column theTranspose() method removes sorting before transposing the data

Display Context MenuContext menus can be helpful to user as they provide shortcuts for actions that are frequently used In FlexGrid therecan be two scenarios to display a context menu

Display context menu in non-edit modeDisplay context menu in edit mode

Display Context Menu in Non-edit Mode

To display context menu when grid is in non-edit mode you need to create an instance of ContextMenuStrip controladd the menu items and assign the instance to ContextMenuStrip property of the Control class

c1FlexGrid1Transpose()

C

C1FlexGrid1Transpose()

VBNET

FlexGrid for WinForms

105 Copyright copy GrapeCity Inc All rights reserved

Refer to the code below to see how to display a context menu in WinForms FlexGrid in non-edit mode

Display Context Menu in Edit Mode

To display context menu in edit mode you need to display the context menu on editor by using StartEdit event ofthe C1FlexGrid class In the StartEdit event instantiate the editor and the ContextMenuStrip add menu items andthen assign it to ContextMenuStrip property of the editor

Create an instance of ContextMenuStrip controlContextMenuStrip cm = new ContextMenuStrip()

Add menu items to the context menucmItemsAdd(Add Above)cmItemsAdd(Add Below)cmItemsAdd(Add Left)cmItemsAdd(Add Right)

Assign the instance to ContextMenuStrip property c1FlexGrid1ContextMenuStrip = cm

C

Create an instance of ContextMenuStrip controlDim cm As ContextMenuStrip = New ContextMenuStrip()

Add menu items to the context menucmItemsAdd(Add Above)cmItemsAdd(Add Below)cmItemsAdd(Add Left)cmItemsAdd(Add Right)

Assign the instance to ContextMenuStrip property c1FlexGrid1ContextMenuStrip = cm

VBNET

FlexGrid for WinForms

106 Copyright copy GrapeCity Inc All rights reserved

Use the code below to display context menu in WinForms FlexGrid in edit mode

private void C1FlexGrid1_StartEdit(object sender C1WinC1FlexGridRowColEventArgs e) TextBox tb = (TextBox)c1FlexGrid1Editor

Create context menu ContextMenuStrip cm2 = new ContextMenuStrip() cm2ItemsAdd(Cut) cm2ItemsAdd(Copy) cm2ItemsAdd(Paste) Set context menu tbContextMenuStrip = cm2

C

Private Sub C1FlexGrid1_StartEdit(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) Dim tb As TextBox = CType(c1FlexGrid1Editor TextBox)

Create context menu Dim cm2 As ContextMenuStrip = New ContextMenuStrip() cm2ItemsAdd(Cut) cm2ItemsAdd(Copy) cm2ItemsAdd(Paste)

Set context menu tbContextMenuStrip = cm2End Sub

VBNET

キーボードによる移動

With built-in keyboard support FlexGrid lets you perform the basic navigation operations such as moving the focusentering or exiting the edit mode etc with a perfect ease just by using keys Below tables list the supported keys andtheir corresponding operations in non-edit as well as in edit mode of the cell

Non-edit Mode

Key Sequence Key Action

FlexGrid for WinForms

107 Copyright copy GrapeCity Inc All rights reserved

uarr

larr rarr

darr

Moves focus to the adjacent cell in direction indicated by the arrow key

Shift + ArrowSelects adjacent cells in direction indicated by the arrow key

F2Grid is editable Toggles the cell to edit mode If a value exists in the cell it getsselected Else the grid simply displays a cursor in the cell

Grid is not editable No action

EnterGrid is editable Toggles the cell to edit mode If a value exists in the cell it getsselected Else the grid simply displays a cursor in the cell

Grid is not editable Moves the selection down to the next visible row

You can also change default behavior of Enter key press by using the KeyActionEnterproperty

HomeMoves focus to the first cell of row

EndMoves focus to the last cell of row

Ctrl + HomeMoves focus to the first cell of column

Ctrl + EndMoves focus to the last cell of column

TabBy default grid ignores the Tab key press and lets it cycle through the controls on theform However you can define the action to be performed on Tab key press by usingthe KeyActionTab property

Ctrl + C

Ctrl + X

Ctrl + V

Performs usual clipboard operations that is copy(Ctrl+C) cut(Ctrl+X) and paste(Ctrl+V)when AutoClipboard property is set to true (Default value is false)

Edit Mode

Key Sequence Key Action

uarr

darr

Moves focus to the adjacent cell in the direction indicated by arrow key

FlexGrid for WinForms

108 Copyright copy GrapeCity Inc All rights reserved

larr rarrMoves cursor by one character in the direction indicated by arrow key When cursor is onthe first or last character moves focus to the adjacent cell in the direction of arrow key

EnterToggles the cell to non-edit mode and moves focus to the cell below You can also changedefault behavior of Enter key press by using the KeyActionEnter property

EscCancels editing and exits the edit mode

TabBy default grid ignores the Tab key press and lets it cycle through the controls on theform However you can define the action to be performed on Tab key press by usingthe KeyActionTab property

パフォーマンスの向上

Use Data VirtualizationTo efficiently render large data sets FlexGrid supports data vitualization in which data is fetched in pages as the user scrolls down The gridknows the total number of rows but only loads and displays those that are visible to the user For instance you can use C1DataCollectionpackage to implement virtualizable data source Create a class inherited from the C1VirtualDataCollection and implement GetPageAsyncmethod which returns one page of data from data source you have assigned The following GIF shows how FlexGrid appears in the virtualscrolling mode

public class VirtualModeCollectionView C1VirtualDataCollectionltCustomergt public int TotalCount get set = 1_000 protected override async TaskltTupleltint IReadOnlyListltCustomergtgtgt GetPageAsync(int pageIndex int startingIndex int count IReadOnlyListltSortDescriptiongt sortDescriptions = null FilterExpression filterExpression = null CancellationToken cancellationToken = default(CancellationToken)) await TaskDelay(500 cancellationToken)Simulates network traffic return new Tupleltint IReadOnlyListltCustomergtgt(TotalCount EnumerableRange(startingIndex count)Select(i =gt new Customer(i))ToList())

C

Public Class VirtualModeCollectionView

VBNET

FlexGrid for WinForms

109 Copyright copy GrapeCity Inc All rights reserved

Use BeginUpdate and EndUpdate MethodsThe BeginUpdate and EndUpdate methods are used to optimize the performance of the grid Call BeginUpdate before making extensivechanges and call EndUpdate when done to suspend repainting This reduces flicker and increases performance This optimization is especiallyeffective when adding large number of rows to the grid because it needs to recalculate ranges and update scrollbars each time a row is added

The code below shows how to add a large number of rows to the WinForms FlexGrid efficiently Note how the EndUpdate method is calledinside a finally block to ensure repainting is properly restored

Keep AutoResize Property to False (default)In case of bound grid if AutoResize property is set to true the control automatically resizes its columns to fit the widest entry every time newdata is read from the data source If the data source contains a large number of rows and columns the automatic resizing may take a relativelylong time In such cases you should consider setting AutoResize to false and setting the column widths directly in code

Assign Styles DynamicallyFlexGrid allows you to create cell styles and assign them to rows columns and arbitrary cell ranges You can use this feature to format the gridcells conditionally Usually you do this by using the SetCellStyle() method However in that case you have to update the style whenever the cellvalue changes Also if the grid is bound to a data source styles are lost whenever data source is reset after operations such as sorting andfiltering A better alternative in these cases is to use the OwnerDraw feature and select styles dynamically based on the cell values For example

Inherits C1VirtualDataCollection(Of Customer)

Public Property TotalCount As Integer = 1_000

Protected Overrides Async Function GetPageAsync(ByVal pageIndex As Integer ByVal startingIndex As Integer ByVal count As Integer ByVal Optional sortDescriptions As IReadOnlyList(Of SortDescription) = Nothing ByVal Optional filterExpression As FilterExpression = Nothing ByVal Optional cancellationToken As CancellationToken = DirectCast(Nothing CancellationToken)) As Task(Of Tuple(Of Integer IReadOnlyList(Of Customer))) Await TaskDelay(500 cancellationToken) Simulates network traffic Return New Tuple(Of Integer IReadOnlyList(Of Customer))(TotalCount EnumerableRange(CInt(startingIndex) CInt(count))[Select](Function(i) New Customer(i))ToList()) End FunctionEnd Class

void UpdateGrid(C1FlexGrid c1FlexGrid1) try c1FlexGrid1BeginUpdate() suspend painting to avoid flicker c1FlexGrid1RowsCount = 1 for (int i = 1 i lt 10000 i++) c1FlexGrid1AddItem(Row + iToString()) finally c1FlexGrid1EndUpdate() always restore painting

C

Private Sub UpdateGrid(ByVal c1FlexGrid1 As C1FlexGrid) Try c1FlexGrid1BeginUpdate() suspend painting to avoid flicker c1FlexGrid1RowsCount = 1

For i As Integer = 1 To 10000 - 1 c1FlexGrid1AddItem(Row amp iToString()) Next

Finally c1FlexGrid1EndUpdate() always restore painting End TryEnd Sub

VBNET

FlexGrid for WinForms

110 Copyright copy GrapeCity Inc All rights reserved

the sample code shows how to display negative values in red color and values above 1000 in green color in the WinForms FlexGrid

Avoid Modifying Styles in the OwnerDrawCell EventAnother way to improve performance is not to modify the CellStyle object passed as a parameter in the OwnerDrawCell event Instead assign anew value to the eStyle parameter This is important because the CellStyle passed to the event handler is often used by other cells Forexample you could unintentionally change a normal style of the WinForms FlexGrid which would affect other similar cells as well in the grid

private void Form1_Load(object sender EventArgs e) Fill a column with random values c1FlexGrid1Cols[1]DataType = typeof(int) Random rnd = new Random() for (int r = 1 r lt c1FlexGrid1RowsCount r++) c1FlexGrid1[r 1] = rndNext(-10000 10000) Create style used to show negative values c1FlexGrid1StylesAdd(Red)ForeColor = ColorRed Enable OwnerDraw by setting the DrawMode property c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw c1FlexGrid1OwnerDrawCell += new C1WinC1FlexGridOwnerDrawCellEventHandler(C1FlexGrid1_OwnerDrawCell)

private void C1FlexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if(eMeasuring) Check that the row and column contain integer data if (eRow gt 0 ampamp c1FlexGrid1Cols[eCol]DataType == typeof(int)) Apply the style Red eStyle = c1FlexGrid1Styles[Red]

C

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) Fill a column with random values c1FlexGrid1Cols(1)DataType = GetType(Integer) Dim rnd As Random = New Random()

For r As Integer = 1 To c1FlexGrid1RowsCount - 1 c1FlexGrid1(r 1) = rnd[Next](-10000 10000) Next

Create style used to show negative values c1FlexGrid1StylesAdd(Red)ForeColor = ColorRed

Enable OwnerDraw by setting the DrawMode property c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw c1FlexGrid1OwnerDrawCell += New C1WinC1FlexGridOwnerDrawCellEventHandler(AddressOf C1FlexGrid1_OwnerDrawCell) End Sub

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If Not eMeasuring Then

Check that the row and column contain integer data If eRow gt 0 AndAlso c1FlexGrid1Cols(eCol)DataType Is GetType(Integer) Then Apply the style Red eStyle = c1FlexGrid1Styles(Red) End If End If End Sub

VBNET

FlexGrid for WinForms

111 Copyright copy GrapeCity Inc All rights reserved

Show Ellipses in a Single ColumnThe Trimming property should be used to show ellipses in a single column of the grid To determine how long strings are trimmed to fit the cellthe Trimming property can be set to either None Character Word EllipsisCharacter EllipsisWord or EllipsisPath For more information ontrimming see Display Trimmed Text

The following code sets the Trimming property to show ellipses at the end of the second WinForms Flexgrid column with the text trimmed tothe nearest character

Show Multi-line Text in a CellWhen showing multiple lines of text in a cell use the WordWrap and Height properties The WordWrap property determines whether the gridshould automatically break long strings that contain spaces and display them in multiple lines Strings that contain hard line breaks (vbCrLf ornr) are always displayed in multiple lines Multiple line text can be displayed in both fixed and scrollable cells For more information on wordwrapping see Wrap Text

Refer to code below to see how a multi-line text should be effectively displayed in the WinForms FlexGrid

CORRECT APPROACHprivate void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) Select style to use when painting this cell eStyle = MyStyleSelector(eRow eCol) WRONG APPROACHprivate void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) Select style to use when painting this cell This is wrong because changing any CellStyle objects invalidates the grid which would cause this event handler to be called over and over again eStyleColor = MyColorSelector(eRow eCol)

C

CORRECT APPROACHPrivate Sub C1FlexGrid1_OwnerDrawCellMethod(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) Select style to use when painting this celleStyle = MyStyleSelector(eRow eCol)End Sub

WRONG APPROACHPrivate Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) Select style to use when painting this cell This is wrong because changing any CellStyle objects invalidates the grid which would cause this event handler to be called over and over againeStyleColor = MyColorSelector(eRow eCol)End Sub

VBNET

c1FlexGrid1Cols[1]StyleNewTrimming =StringTrimmingEllipsisCharacter

C

c1FlexGrid1Cols(1)StyleNewTrimming = StringTrimmingEllipsisCharacter

VBNET

Set the WordWrap property

C

FlexGrid for WinForms

112 Copyright copy GrapeCity Inc All rights reserved

Retrieve Data Sorting When Bound to a Data TableTo maintain the way the grid is sorted when data is refreshed you can use the default views Sort property and a sort expression The Sortproperty uses a string containing the column name followed by ASC(default) or DESC to sort the column in ascending or descending orderrespectively Multiple columns can be sorted by specifying each column name separated by a comma A sort expression can include names ofgrid columns or a calculation Setting the sort expression at run time immediately reflects the changes in the data view

Below code shows how to use the sort expression with Sort property in the WinForms FlexGrid

Specify Character Limit for ColumnTo set the maximum number of characters a user can enter for any given column use the SetupEditor event You must declare an externaleditor such as C1TextBox in the StartEdit event of the C1FlexGrid class Then in the SetupEditor event you can set the maximum number ofcharacters that are allowed in a column cell

Use the code below to set the character limit for a WinForms FlexGrid column

c1FlexGrid1Styles[Normal]WordWrap = true Set the row heightc1FlexGrid1Rows[1]Height = 2 fgRowsDefaultSize Add text to the cellc1FlexGrid1[1 2] = This is the first line rn This is the second line

Set the WordWrap property c1FlexGrid1Styles(Normal)WordWrap = True

Set the row height c1FlexGrid1Rows(1)Height = 2 fgRowsDefaultSize

Add text to the cell c1FlexGrid1(1 2) = This is the first line amp vbCrLf amp This is the second line

VBNET

Sort the data by the UnitsInStock column then by the ProductID column thisproductsBindingSourceSort = UnitsInStock ASC ProductID ASC

C

Sort the data by the UnitsInStock column then by the ProductID columnMeproductsBindingSourceSort = UnitsInStock ASC ProductID ASC

VBNET

private void C1FlexGrid1_StartEdit(object sender C1WinC1FlexGridRowColEventArgs e) c1FlexGrid1Editor = c1TextBox private void C1FlexGrid1_SetupEditor(object sender RowColEventArgs e) Set the 3rd column to allow 20 characters and the rest only 10 if (eCol == 2) c1TextBoxMaxLength = 20 else c1TextBoxMaxLength = 10

C

Private Sub C1FlexGrid1_StartEdit(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs)

VBNET

FlexGrid for WinForms

113 Copyright copy GrapeCity Inc All rights reserved

c1FlexGrid1Editor = c1TextBox End Sub

Private Sub C1FlexGrid1_SetupEditor(ByVal sender As Object ByVal e As RowColEventArgs)

Set the 3rd column to allow 20 characters and the rest only 10 If eCol = 2 Then c1TextBoxMaxLength = 20 Else c1TextBoxMaxLength = 10 End If End Sub

FlexGrid for WinForms

114 Copyright copy GrapeCity Inc All rights reserved

スクロールバー

Display or Hide the Scroll BarIn FlexGrid you can manage the display of scroll bars using the ScrollBars property which lets you choose whether todisplay horizontal vertical both or no scroll bar through the ScrollBars enumeration

Below code shows how to always display both the scrollbars in the WinForms FlexGrid

Set Scroll PositionTo scroll FlexGrid to a specified location you can set TopRow and LeftCol property of the C1FlexGrid class TopRowproperty scrolls the grid vertically while LeftCol sets the horizontal scroll position of the grid The maximum value ofthese properties depends on the total number of rows or columns and the count that can be displayed in the gridThis feature is really useful in scenarios like synchronized scrolling of multiple grids

Use the code below to set scroll position of the WinForms FlexGrid

水平および垂直スクロールバーを表示しますc1FlexGrid1ScrollBars = ScrollBarsBoth 常にスクロールバーを表示しますc1FlexGrid1ScrollOptions = ScrollFlagsAlwaysVisible

C

水平および垂直スクロールバーを表示しますc1FlexGrid1ScrollBars = ScrollBarsBoth

常にスクロールバーを表示しますc1FlexGrid1ScrollOptions = ScrollFlagsAlwaysVisible

VBNET

スクロール位置を設定しますc1FlexGrid1TopRow = 3c1FlexGrid1LeftCol = 2

C

スクロール位置を設定しますc1FlexGrid1TopRow = 3

VBNET

FlexGrid for WinForms

115 Copyright copy GrapeCity Inc All rights reserved

Other Scroll OptionsFlexGrid also provides more options to handle various aspects of displaying a scroll bar through ScrollOptionsproperty This property accepts the values from ScrollFlags enumeration which lets you customize the scroll baroptions as described in the table below

Value Scroll Operation

AlwaysVisible Displays the scroll bar even when they are disable or there is no scrollable area

DelayedScroll Scrolls the content only after user has released the scrollbar thumb

KeepMergedRangePosition Can not set scroll position to the first cell of a merged range

None Uses the default scrolling behavior

ScrollByRowColumn Scrolls the content in units of rows or columns instead of scrolling by pixels

ShowScrollTips Fires the ShowScrollTip event and displays a tooltip next to the vertical scrollbarwhile scrolling vertically

Following code shows how to scroll the WinForms FlexGrid by rows or columns only

c1FlexGrid1LeftCol = 2

行や列単位でスクロールします c1FlexGrid1ScrollOptions = ScrollFlagsScrollByRowColumn

C

行や列単位でスクロールしますc1FlexGrid1ScrollOptions = ScrollFlagsScrollByRowColumn

VBNET

FlexGrid for WinForms

116 Copyright copy GrapeCity Inc All rights reserved

選択

Selection ModesFlexGrid by default allows to select a continuous batch of cells using mouse or keyboard and entire row or column by clicking thecorresponding header However the default behavior can be changed to allow selection in units of cell row column etc byusing SelectionMode property of the C1FlexGrid class The property accepts values from the SelectionModeEnumenumeration Below table gives a quick snapshot of how selection looks like in each of these modes

Value Description Snapshot

Default Allows selection of continuous batch of cells using mouse orkeyboard Also lets the user select entire row or column onclicking the respective header

Cell Allows selection of single cell at a time

CellRange Allows selection of continuous batch of cells using mouse orkeyboard

Column Allows selection of single column at a time

ColumnRange Allows selection of multiple contiguous columns at a time

ListBox Allows selection of multiple non-contiguous rows using the Ctrlkey

FlexGrid for WinForms

117 Copyright copy GrapeCity Inc All rights reserved

Row Allows selection of single row at a time

RowRange Allows selection of multiple contiguous rows at a time

Set SelectionFlexGrid provides various ways to set the selection through code You can use any of these methods depending on the requirementsuch as selecting the single cell cell range or rows

Selection MethodProperty Sample code

Single cell Set the Row and Col property Default value of both of theseproperties is 1 Hence by default selection is set to the firstscrollable cell on top left of the grid

Example Title

c1FlexGrid1Row = 2c1FlexGrid1Col = 1

Call the Select(rowIndex colIndex) method to select a singlecell

Example Title

c1FlexGrid1Select(2 1)

Cell range Set the RowSel and ColSel property These properties set theselection starting from value set in Row and Col property tothe specified row and column Note that to specify a blockselection you must set Row and before setting RowSel andColSel

Example Title

c1FlexGrid1Row = 2c1FlexGrid1Col = 1c1FlexGrid1RowSel = 4c1FlexGrid1ColSel = 3

Call the Select(CellRange Boolean) method to select a cellrange in a single call

Example Title

CellRange cellRange = new CellRange()cellRanger1 = 2cellRanger2 = 4cellRangec1 = 1cellRangec2 = 3c1FlexGrid1Select(cellRange)

Rows

(If SelectionModes =

SelectionModesEnum

ListBox)

Set the RowSelected property to true for individual rowobjects to select the non-continuous rows

Example Title

c1FlexGrid1SelectionMode = SelectionModeEnumListBoxc1FlexGrid1Rows[1]Selected = truec1FlexGrid1Rows[4]Selected =

Value Description Snapshot

FlexGrid for WinForms

118 Copyright copy GrapeCity Inc All rights reserved

true

Get Selection To get selected range of the WinForms FlexGrid you can use Selection property of the C1FlexGrid class

Select Text on Double ClickBy default double click on a grid cell changes the cell state to edit mode and shows the cursor at position of the mouse pointerHowever you can change this behavior and select the cell value on double click of a cell This can be done by detecting anddisabling the double click in BeforeDoubleClick event Then call the StartEditing method to enter the edit mode change theeditor to a TextBox and call the SelectAll method to select the cell value

Following code shows how you can select text of the WinForms FlexGrid cell on a double click

private void Button1_Click(object sender EventArgs e) C1WinC1FlexGridCellRange cr cr = c1FlexGrid1Selection MessageBoxShow(Selected rangen + crr1 + + crc1 + to + crr2 + + crc2)

C

Private Sub Button1_Click(ByVal sender As Object ByVal e As EventArgs) Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1Selection MessageBoxShow(Selected range amp vbLf amp crr1 amp + crc1 amp to + crr2 amp + crc2)End Sub

VBNET

private void C1FlexGrid1_BeforeDoubleClick(object sender BeforeMouseDownEventArgs e) デフォルトのダブルクリックを無効にします eCancel = true 編集モードに入ります c1FlexGrid1StartEditing() TextBoxクラスに変換しSelectAllメソッドを使用して選択します TextBox tb = (TextBox)c1FlexGrid1Editor tbSelectAll()

C

Private Sub C1FlexGrid1_BeforeDoubleClick(ByVal sender As Object ByVal e As BeforeMouseDownEventArgs) デフォルトのダブルクリックを無効にします eCancel = True 編集モードに入ります c1FlexGrid1StartEditing() TextBoxクラスに変換しSelectAllメソッドを使用して選択します Dim tb As TextBox = CType(c1FlexGrid1Editor TextBox) tbSelectAll()End Sub

VBNET

Selection MethodProperty Sample code

FlexGrid for WinForms

119 Copyright copy GrapeCity Inc All rights reserved

編集

This topic discusses about various events and methods which are related to editing and also about how to disableediting

Topic Content

Edit Mode Discusses various events and methods related to editing

Disable Editing Discusses how to disable editing in grid at various levels

Disable Grid EditingDisable Row or Column EditingDisable Cell Editing

編集モード

In FlexGrid edit mode can be invoked at runtime using mouse click or even keyboard To determineprogrammatically whether the grid is in edit mode you can read the value of Editor property If the grid is in editmode the property returns a reference to the control that is being used as editor such as TextBox or ComboBoxHowever if the grid is not in edit mode the property returns null

To put the grid in edit mode programmatically you can use the StartEditing method and to finish editing you can callthe FinishEditing method You can also retain the state of edit mode in grid while navigating through the cells byusing the PreserveEditMode property

In addition FlexGrid fires various events to facilitate better control on the editing process Below table lists thesequence of events which are fired by the grid during the editing process

Event Name Description

BeforeEdit The event fires whenever an editable cell is selected It allows you to prevent the cell from beingedited by setting the events Cancel parameter to true You can also modify the ComboList propertyso the appropriate drop-down button gets painted in the cell Note that the user might not actuallystart editing after this he could simply move the selection to a different cell or control

StartEdit The event is similar to BeforeEdit except the user has actually typed a key or clicked the dropdownbutton in the cell and really is about to start editing You can still cancel the editing at this point Notethat the Editor property is still null at this point because the control hasnt yet determined the typeof editor that should be used You can assign custom editors to the Editor property at this point

ChangeEdit The event is a wrapper of editorTextChanged event The event fires when the contents of the editorchange You can use this event to keep track of the current content in editor

SetupEditor The event fires after the editor control has been created and configured to edit the cell but before itis displayed You can change the editor properties at this point (for example set the maximum lengthor password character to be used in a TextBox editor) You can also attach your own event handlers tothe editor

ValidateEdit The event fires when the user is done editing before the editor value gets copied back into the gridYou can examine the original value by retrieving it from the grid (the event provides the coordinatesof the cell) You can examine the new value about to be assigned to the grid through the Editorproperties (for example EditorText) If the new value is not valid for the cell set the Cancel parameterto true and the grid remains in edit mode If instead of keeping the cell in edit mode you wouldrather restore the original value and leave edit mode set Cancel parameter to true and then call theFinishEditing method

LeaveEdit This event fires after the grid control leaves edit mode You can use this event to approve or deny the

FlexGrid for WinForms

120 Copyright copy GrapeCity Inc All rights reserved

new cell content or to change the editor content about to be committed

AfterEdit This event fires after the new value has been applied to the cell and the editor has been deactivatedYou can use this event to update anything that depends on the cell value (for example subtotals orsorting)

Also there are few events which are related to keyboard operations and are fired when a key is pressed They aresimilar to their counterparts from SystemWindowsFormsControl class apart from the fact that they occur when thegrid is in edit mode

Event Description

KeyDownEdit This event fires when grid is in edit mode and a key is pressed You can use this event toperform an action once or even multiple times while the key is held down such as movinga cursor

KeyPressEdit This event fires when grid is in edit mode and a character key is pressed You can use thisevent to perform any operation related to typing such as handling input in the cell editor

KeyUpEdit This event fires when grid is in edit mode and key is released You can use this event toplace a logic that executes after KeypressEdit logic has taken effect

Event Name Description

編集の無効化

FlexGrid by default allows end-user to edit the cell values at runtime However with FlexGrid you can easily managehow much control you want to give to the end-users using various properties provided by the FlexGrid

Disable Grid EditingTo disable editing of the whole WinForms FlexGrid you need to set AllowEditing property of the C1FlexGrid class tofalse as shown in the code below

Disable Row or Column EditingTo disable the editing of a particular row or column of the WinForms FlexGrid you can set the AllowEditing propertyof Row or Column object to false as shown in the code below

グリッドで編集を無効にします c1FlexGrid1AllowEditing = false

C

グリッドで編集を無効にしますc1FlexGrid1AllowEditing = False

VBNET

3行目の編集を無効にしますc1FlexGrid1Rows[3]AllowEditing = false 3列目の編集を無効にしますc1FlexGrid1Cols[3]AllowEditing = false

C

FlexGrid for WinForms

121 Copyright copy GrapeCity Inc All rights reserved

Disable Cell EditingTo disable editing of a particular cell you can use the BeforeEdit event and set the Cancel parameter for thatparticular cell to true

3行目の編集を無効にしますc1FlexGrid1Rows(3)AllowEditing = False

3列目の編集を無効にしますc1FlexGrid1Cols(3)AllowEditing = False

VBNET

セル編集を無効にしますprivate void C1FlexGrid1_BeforeEdit(object sender RowColEventArgs e) if ((eCol == 4) ampamp (eRow == 2)) eCancel = true

C

セル編集を無効にしますPrivate Sub C1FlexGrid1_BeforeEdit(ByVal sender As Object ByVal e As RowColEventArgs) If eCol = 4 AndAlso eRow = 2 Then eCancel = True End IfEnd Sub

VBNET

FlexGrid for WinForms

122 Copyright copy GrapeCity Inc All rights reserved

並べ替え

Sorting is one of the basic features a grid must have and FlexGrid provides you complete control on how data can besorted in ascending or descending order for easier data analysis This topic discusses about sorting in FlexGrid andother related operations

Topic Snapshot Content

Sort Operations Discusses various operations related to sorting

Sorting through CodeSort Multiple ColumnsRevertUndo SortingDisable Sort on a Particular ColumnSort OrderCustom Sorting

Sort Indicator Discusses how to hide position and customize sort indicator

HideDisplay Sort IndicatorPosition Sort IndicatorCustomize Sort Indicator

並べ替えの操作

FlexGrid by default allows end-users to apply sorting on a single column by clicking the column header in ascending ordescending order However the grid also provides you flexibility so that you can sort your data according to yourrequirement Below sections take you through the ways to perform various operations related to sorting

Sorting through CodeYou can apply sorting through code by calling Sort method of the C1FlexGrid class The method takes SortFlagsenumeration as its parameter which lets you provide the various sort options such as setting the sort order and ignorecasing The method has various overloads which gives you flexibility to apply sorting either on a column or a range ofcells rows or columns

Use the code below to sort columns and apply sorting options through code in the WinForms FlexGrid

FlexGrid for WinForms

123 Copyright copy GrapeCity Inc All rights reserved

Sort Multiple ColumnsTo apply sorting on multiple columns through code you can use the Sort property of Column class and then call theSort() method with SortFlags set to UseColSort The Sort property accepts values from SortFlags enumeration

Following code shows how to sort multiple columns of the WinForms FlexGrid through code

To allow user to sort multiple columns at runtime set AllowSorting property of the C1FlexGrid class to MultiColumn Theproperty accepts values from the AllowSortingEnum enumeration

Following code shows how to let user sort multiple columns of the WinForms FlexGrid at run-time

方法1 2番目の列を降順で並べ替えますc1FlexGrid1Sort(C1WinC1FlexGridSortFlagsDescending 2) 方法 2SortFlagを使用して複数の並べ替えオプションを指定しますC1WinC1FlexGridSortFlags order = C1WinC1FlexGridSortFlagsAscending | C1WinC1FlexGridSortFlagsIgnoreCase Sortメソッドを呼び出しますc1FlexGrid1Sort(order 2)

C

方法1 2番目の列を降順で並べ替えますc1FlexGrid1Sort(C1WinC1FlexGridSortFlagsDescending 2)

方法2 SortFlagを使用して複数の並べ替えオプションを指定しますDim order As C1WinC1FlexGridSortFlags = C1WinC1FlexGridSortFlagsAscending Or C1WinC1FlexGridSortFlagsIgnoreCase

Sortメソッドを呼び出しますc1FlexGrid1Sort(order 2)

VBNET

複数列を並べ替えますc1FlexGrid1Cols[2]Sort = SortFlagsAscendingc1FlexGrid1Cols[3]Sort = SortFlagsDescending Sortメソッドを呼び出しますc1FlexGrid1Sort(SortFlagsUseColSort 2 3)

C

複数列を並べ替えますc1FlexGrid1Cols(2)Sort = SortFlagsAscendingc1FlexGrid1Cols(3)Sort = SortFlagsDescending

Sortメソッドを呼び出しますc1FlexGrid1Sort(SortFlagsUseColSort 2 3)

VBNET

グリッドの複数の列での並べ替えを許可します c1FlexGrid1AllowSorting = AllowSortingEnumMultiColumn

C

FlexGrid for WinForms

124 Copyright copy GrapeCity Inc All rights reserved

RevertUndo SortingTo remove sorting from the grid you can set SortDefinition property of the C1FlexGrid class to an empty string

Below code how to remove sorting from the WinForms FlexGrid

Disable Sort on a Particular ColumnTo disable sorting on a particular column you need to set the AllowSorting property of that Column object to false

Use the code below to disable sorting on a particular column of the WinForms FlexGrid

Sort OrderOrder of sorting usually varies in case of bound and unbound mode When a column header is clicked in case of boundmode sorting is done same as DefaultViewSort property of the data table However in case of unbound mode columnis sorted either according to StringCompare method or by differentiating the lower and upper case according to theculture

Refer to the code below to specify sorting order of a WinForms FlexGrid column

グリッドの複数の列での並べ替えを許可しますc1FlexGrid1AllowSorting = AllowSortingEnumMultiColumn

VBNET

並べ替えを削除します c1FlexGrid1SortDefinition = stringEmpty

C

並べ替えを削除しますc1FlexGrid1SortDefinition = StringEmpty

VBNET

グリッドの特定の列での並べ替えを無効にしますc1FlexGrid1Cols[2]AllowSorting = false

C

グリッドの特定の列での並べ替えを無効にしますc1FlexGrid1Cols(2)AllowSorting = False

VBNET

C1WinC1FlexGridSortFlags order = C1WinC1FlexGridSortFlagsAscending | C1WinC1FlexGridSortFlagsIgnoreCase c1FlexGrid1Sort(order 2)

C

Dim order As C1WinC1FlexGridSortFlags = C1WinC1FlexGridSortFlagsAscending Or C1WinC1FlexGridSortFlagsIgnoreCasec1FlexGrid1Sort(order 2)

VBNET

FlexGrid for WinForms

125 Copyright copy GrapeCity Inc All rights reserved

Custom SortingFlexGrid provides several sorting options which are required for most commonly used scenarios such as ignore case usethe display value etc However if you need to have more flexibility and control over sort operation you can even writeyour own custom logic using the IComparer class For instance the example below sorts the Name column by fileextensions In the sample code custom logic to sort by file extension is implemented in the FileNameComparer class whichis then passed as parameter to Sort() method of the C1FlexGrid class

The code below demonstrates how to apply custom sorting on the WinForms FlexGrid columns

c1FlexGrid1Sort(new FileNameComparer(c1FlexGrid1 eOrder)) class FileNameComparer IComparer C1FlexGrid c1FlexGrid1 bool _desc

ctor public FileNameComparer(C1FlexGrid flex SortFlags order) c1FlexGrid1 = flex _desc = ((order amp SortFlagsDescending) = 0) IComparer public int Compare(object r1 object r2) ファイル名を取得します string s1 = (string)c1FlexGrid1[((Row)r1)Index Name] string s2 = (string)c1FlexGrid1[((Row)r2)Index Name]

拡張機能を比較します int icmp = stringCompare(PathGetExtension(s1) PathGetExtension(s2) true)

並べ替え順(昇順または降順)を返します return (_desc) -icmp icmp

C

C1FlexGrid1Sort(New FileNameComparer(C1FlexGrid1 SortFlagsAscending))

Public Class FileNameComparer Implements IComparer

Private c1FlexGrid1 As C1FlexGrid Private _desc As Boolean

Public Sub New(ByVal flex As C1FlexGrid ByVal order As SortFlags) c1FlexGrid1 = flex _desc = ((order And SortFlagsDescending) ltgt 0) End Sub

Public Function Compare(r1 As Object r2 As Object) As Integer Implements IComparerCompare Dim s1 As String = CStr(c1FlexGrid1((CType(r1 Row))Index Name)) Dim s2 As String = CStr(c1FlexGrid1((CType(r2 Row))Index Name)) Dim icmp As Integer = StringCompare(PathGetExtension(s1) PathGetExtension(s2) True) Return If((_desc) -icmp icmp) End Function

VBNET

FlexGrid for WinForms

126 Copyright copy GrapeCity Inc All rights reserved

For detailed implementation of custom sorting see the product sample named Custom Sort

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing WinFormsEdition using ComponentOneControlPanelexe

並べ替えのインジケータ

FlexGrid displays sort indicator a small triangular arrow sign to indicate the direction of sorting The grid alsoprovides flexibility to hide display position or customize the indicator

Hide or Display Sort IndicatorFlexGrid by default displays the sort indicator when a column header is clicked to sort the columns However you canhide the indicator by setting the ShowSortPosition property to None The property accepts valuesfrom ShowSortPositionEnum enumeration

Use the code below to hide the sort indicator displayed on the sorted WinForms FlexGrid column

Position Sort IndicatorSort indicator by default gets displayed towards the right side of the header cell However when the filtering isapplied on a column the sort indicator displays on top of the header cell to give place to the filtering icon You can fixthe position of sort indicator by setting value of ShowSortPosition property to Top or Right

Customize the position of column sort indicator in WinForms FlexGrid using the code below

Customize Sort IndicatorFlexGrid provides the GlyphEnum enumeration which lets you specify the image to be used for sort indicator Formore information on the GlyphEnum and glyph customization see Custom Glyphs

並べ替えインジケータを非表示にしますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumNone

C

並べ替えインジケータを非表示にしますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumNone

VBNET

並べ替えインジケータの位置を上に変更しますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumTop

C

並べ替えインジケータの位置を上に変更しますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumTop

VBNET

FlexGrid for WinForms

127 Copyright copy GrapeCity Inc All rights reserved

フィルタ

Grid filtering lets you narrow down display records according to a specified condition applied on a column It is especially useful in case of large data sets asit lets you easily analyze data by displaying a specific type of records only

This section discusses about the process types and customization of filters

Topic Snapshot Content

Filter Operations Discusses about how to enable or apply filtering and other related operations

Allow FilteringFiltering through CodeCustom FilteringRemove FilteringTypes of Filters

Filter UI Discusses about filtering icon its customization and how to set the filter language

Show Filter IconUse Custom IconsChange Filter Language

フィルタの操作

Data filtering in a grid can be performed in two ways

Header-based Filter

In header-based filtering an icon is displayed in the header cell of column which gives you options to specify the filter in a drop-down and alsoindicates if the filter is applied on a particular column In FlexGrid this behavior can be achieved by simply using AllowFiltering property of the gridIn this case filter does not require any extra real estate on the screen This approach also gives you flexibility to customize and create better filtereditors More details about same is given in the sections below

Filter Row

Filter row is a row dedicated for displaying the filtering criteria and appears just below the column header So in this case user can always see thefiltered columns and their current filtering criteria But this added advantage comes at the cost of extra screen real estate that a filter row needs InFlexGrid you can easily achieve filter row using the custom implementation For implementation see the product sample named Filter Row

Note The Filter Row sample is located at DocumentsComponentOne SamplesWinFormsv452C1FlexGridCS on your system if you haveinstalled the samples while installing WinForms Edition using ComponentOneControlPanelexe

Allow FilteringIn FlexGrid filtering can be enabled by setting the C1FlexGridAllowFiltering property to true This enables the default ColumnFilter on allcolumns of the grid The ColumnFilter lets the users choose from ValueFilter and ConditionFilter at runtime

FlexGrid for WinForms

128 Copyright copy GrapeCity Inc All rights reserved

You can also specify the filter types for each column by setting the AllowFiltering property of each Column object AllowFiltering property ofcolumn lets you choose from any of the following values

Value Description

Default Enables the ColumnFilter which is a combination of ValueFilter and ConditionFilter and gives user a runtime option to choose eitherof them

ByValue Enables ValueFilter which contains a checkbox list of values present in that column User can check off the values that should not bedisplayed in the filtered output

ByCondition Enables ConditionFilter which lets you specify combination of two conditions such as equals greater than contains etc Youcan combine the specified conditions using And and Or operator

Custom Lets you instantiate a custom filter and explicitly assign it to Filter property of the column

None Disables filtering for that column

Use the following code snippet to enable a condition filter on first column of the WinForms FlexGrid

For more details regarding abovementioned filter types see Types of Filters

Filtering through CodeAlthough AllowFiltering property of grid enables grid filtering and can be used in most common scenarios there may be cases where you need tofurther fine tune the filter options This can be achieved by modifying AllowFiltering and Filter properties of individual columns For example thecode below enables filtering in the WinForms FlexGrid but restricts the filtering to columns of type string

You can also customize the filtering process further by creating filters and assigning them to columns or by retrieving existing filters and modifyingtheir properties For example the code below creates a ConditionFilter in the WinForms FlexGrid configures it to select all items that are equal toGermany and then assigns the new filter to the ShipCountry column

グリッドでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = true 列1に対してフィルタを指定しますc1FlexGrid1Cols[1]AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

C

グリッドでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = True

列1に対してフィルタを指定しますc1FlexGrid1Cols(1)AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

VBNET

文字列型の列にフィルタリングを制限します foreach (Column c in c1FlexGrid1Cols) cAllowFiltering = cDataType == typeof(string) AllowFilteringDefault AllowFilteringNone

C

文字列型の列にフィルタリングを制限しますFor Each c As Column In c1FlexGrid1Cols cAllowFiltering = If(cDataType Is GetType(String) AllowFilteringDefault AllowFilteringNone)Next

VBNET

グリッドでフィルタリングを有効にします c1FlexGrid1AllowFiltering = true 新しいConditionFilterを作成します C1WinC1FlexGridConditionFilter Filter Filter = new C1WinC1FlexGridConditionFilter()

C

FlexGrid for WinForms

129 Copyright copy GrapeCity Inc All rights reserved

Custom FilteringWhen filtering is applied to FlexGrid it hides the rows that do not qualify the filtering criteria by setting their Visible property to false However insome cases you may want to customize this behavior For such scenarios you can use the BeforeFilter and AfterFilter events fired by FlexGridThe below example customizes the filtering behavior of WinForms FlexGrid by applying a different style to non-qualifying rows instead of hidingthem

Germanyのアイテムを絞り込むためのフィルタを作成します FilterCondition1Operator = C1WinC1FlexGridConditionOperatorEquals FilterCondition1Parameter = Germany 「ShipCountry」列に新しいフィルタを割り当てます c1FlexGrid1Cols[ShipCountry]Filter = Filter フィルタを適用します c1FlexGrid1ApplyFilters()

グリッドでフィルタリングを有効にしますc1FlexGrid1AllowFiltering = True

新しいConditionFilterを作成しますDim Filter As C1WinC1FlexGridConditionFilterFilter = New C1WinC1FlexGridConditionFilter()

Germanyのアイテムを絞り込むためのフィルタを作成しますFilterCondition1[Operator] = C1WinC1FlexGridConditionOperatorEqualsFilterCondition1Parameter = Germany

「ShipCountry」列に新しいフィルタを割り当てますc1FlexGrid1Cols(ShipCountry)Filter = Filter

フィルタを適用しますc1FlexGrid1ApplyFilters()

VBNET

private void c1FlexGrid1_BeforeFilter(object sender CancelEventArgs e) c1FlexGrid1BeginUpdate()

private void c1FlexGrid1_AfterFilter(object sender EventArgs e) フィルタリングされた行を表示するために使用されるスタイルを取得します var cs = c1FlexGrid1Styles[filteredOut]

すべての行にスタイルを適用します

C

FlexGrid for WinForms

130 Copyright copy GrapeCity Inc All rights reserved

The above code uses a custom style named filteredout which can be defined as shown in the code below

Remove FilteringUser can remove column filtering at runtime by using Clear option given in the filter UI of each column You can also remove filtering of the wholegrid programmatically by passing the empty string in FilterDefinition property of FlexGrid

Below code demonstrates how to clear all the filters from the WinForms FlexGrid

for (int r = c1FlexGrid1RowsFixed r lt c1FlexGrid1RowsCount r++) var row = c1FlexGrid1Rows[r] if (rowVisible) 通常の行スタイルをリセットします rowStyle = null else フィルタリングされた行 見えるようにしスタイルを適用します rowVisible = true rowStyle = cs

更新を再開します c1FlexGrid1EndUpdate()

Private Sub c1FlexGrid1_BeforeFilter(ByVal sender As Object ByVal e As CancelEventArgs) c1FlexGrid1BeginUpdate()End Sub

Private Sub c1FlexGrid1_AfterFilter(ByVal sender As Object ByVal e As EventArgs) フィルタリングされた行を表示するために使用されるスタイルを取得します Dim cs = c1FlexGrid1Styles(filteredOut)

すべての行にスタイルを適用します For r = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 Dim row = c1FlexGrid1Rows(r)

If rowVisible Then 通常の行スタイルをリセットします rowStyle = Nothing Else フィルタリングされた行 見えるようにしスタイルを適用します rowVisible = True rowStyle = cs End If Next

更新を再開します c1FlexGrid1EndUpdate()End Sub

VBNET

フィルタによって除外された行のスタイルを作成しますvar cs = c1FlexGrid1StylesAdd(filteredOut)csBackColor = ColorLightGraycsForeColor = ColorDarkGray

C

フィルタによって除外された行のスタイルを作成しますDim cs = c1FlexGrid1StylesAdd(filteredOut)csBackColor = ColorLightGraycsForeColor = ColorDarkGray

VBNET

フィルタ定義を空の文字列に設定してフィルタリングを削除しますc1FlexGrid1FilterDefinition = stringEmpty

C

FlexGrid for WinForms

131 Copyright copy GrapeCity Inc All rights reserved

フィルタ定義を空の文字列に設定してフィルタリングを削除しますc1FlexGrid1FilterDefinition = StringEmpty

VBNET

フィルタの種類

FlexGrid not only provides built-in filters such as Column filter Value filter and Condition Filter but also lets youcreate your own custom filter The built-in filters are provided through AllowFiltering property of Column class whichlets you set the type of filter to be applied on a particular column On the other hand the custom filters make use ofthe IC1ColumnFilter interface and the IC1ColumnFilterEditor interface This topic discusses the implementation ofbuilt-in and custom filters in detail

Column FilterColumn filter is the default filter that is applied to all the columns automatically when AllowFiltering property of thegrid is set to true The ColumnFilter is a combination of ValueFilter and ConditionFilter (discussed below) and givesuser an option to choose either of them at runtime While working with code you can use its ValueFilterand ConditionFilter properties to access the two types of filters The filter also provides Apply method to apply filterto a value and Reset method to reset the filter and hence making it inactive

Use the below code to apply column filter on ProductName column of the WinForms FlexGrid

列フィルタ(ProductNameが「C」で始まる製品をフィルター処理します)ColumnFilter colFilter = new ColumnFilter()colFilterConditionFilterCondition1Parameter = CcolFilterConditionFilterCondition1Operator = ConditionOperatorBeginsWithc1FlexGrid1Cols[ProductName]Filter = colFilter

C

列フィルタ(ProductNameが「C」で始まる製品をフィルター処理します) Dim colFilter As ColumnFilter = New ColumnFilter()

VBNET

FlexGrid for WinForms

132 Copyright copy GrapeCity Inc All rights reserved

Value FilterValue filter refers to the value based filter which gets enabled on setting the AllowFiltering property of column toByValue The ValueFilter provides the dropdown list of all values with checkbox which lets the user select the valueswhich are to be displayed in the output These values can be get or set through the ShowValues property You canalso set a limit on number of values to be displayed in the dropdown list by setting the ValuesLimit property Just likecolumn filter value filter also provides Apply method to apply filter to a value and Reset method to reset the filter

Below code shows how to apply ValueFilter on a column of the WinForms FlexGrid

Condition FilterCondition filter refers to a filter based on one or two logical conditions which can be enabled by setting theAllowFiltering property to ByCondition The ConditionFilter gives user an option to set the conditionsthrough Condition1 and Condition2 properties which can be combined using ANDOR operator by settingthe AndConditions property to filter the records Similar to other filters this class also provides Apply and Resetmethod

colFilterConditionFilterCondition1Parameter = C colFilterConditionFilterCondition1[Operator] = ConditionOperatorBeginsWith c1FlexGrid1Cols(ProductName)Filter = colFilter

値フィルタ(CategoryIdが12358である製品をフィルタ処理します)ValueFilter valueFilter = new ValueFilter()valueFilterShowValues = new object[] 1 2 3 5 8 c1FlexGrid1Cols[CategoryId]Filter = valueFilter

C

値フィルタ(CategoryIdが12358である製品をフィルタ処理します) Dim valueFilter As ValueFilter = New ValueFilter() valueFilterShowValues = New Object() 1 2 3 5 8 c1FlexGrid1Cols(CategoryId)Filter = valueFilter

VBNET

FlexGrid for WinForms

133 Copyright copy GrapeCity Inc All rights reserved

Below code demonstrates how to apply a ConditionFilter on a WinForms FlexGrid column

Custom FilterThe abovementioned filters provide you enough flexibility to implement most common filtering scenarios efficientlyIn addition custom filter option also lets you create your own filter to meet any other specialized requirements ofyour application To create a custom filter you need to create a filter class that implements the IC1ColumnFilterinterface and an editor class that implements the IC1ColumnFilterEditor interface Below example shows theimplementation of a custom string filter which lets you filter based on ranges

条件フィルタ(UnitPricegt = 50およびlt= 100の製品をフィルタ処理します)ConditionFilter conditionFilter = new ConditionFilter()conditionFilterCondition1Parameter = 50conditionFilterCondition1Operator = ConditionOperatorGreaterThanOrEqualToconditionFilterCondition2Parameter = 100conditionFilterCondition2Operator = ConditionOperatorLessThanOrEqualToconditionFilterAndConditions = truec1FlexGrid1Cols[UnitPrice]Filter = conditionFilter

C

条件フィルタ(UnitPricegt = 50およびlt= 100の製品をフィルタ処理します) Dim conditionFilter As ConditionFilter = New ConditionFilter() conditionFilterCondition1Parameter = 50 conditionFilterCondition1[Operator] = ConditionOperatorGreaterThanOrEqualTo conditionFilterCondition2Parameter = 100 conditionFilterCondition2[Operator] = ConditionOperatorLessThanOrEqualTo conditionFilterAndConditions = True c1FlexGrid1Cols(UnitPrice)Filter = conditionFilter

VBNET

FlexGrid for WinForms

134 Copyright copy GrapeCity Inc All rights reserved

Following is the code of a custom filter created for the WinForms FlexGrid Note that the class implementsIC1CustomFilter interface

StringFiltercs

class StringFilter C1WinC1FlexGridIC1ColumnFilter

ListltPointgt _ranges = new ListltPointgt()

ltsummarygt このフィッタが受け入れる文字列を定義するポイントのリストを取得します ltsummarygt public ListltPointgt Ranges get return _ranges

範囲リストが空でない場合フィルタはアクティブです public bool IsActive get return _rangesCount gt 0

フィルタをリセットします public void Reset() _rangesClear()

指定された日付にフィルタを適用します public bool Apply(object value) if (value = null)

C

FlexGrid for WinForms

135 Copyright copy GrapeCity Inc All rights reserved

var s = valueToString() if (sLength gt 0) int c = charToUpperInvariant(s[0]) foreach (var cr in _ranges) if (c gt= charToUpperInvariant((char)crX) ampamp c lt= charToUpperInvariant((char)crY)) return true return false

このフィルタのエディタコントロールを返します public C1WinC1FlexGridIC1ColumnFilterEditor GetEditor() return new StringFilterEditor()

Friend Class StringFilter Implements C1WinC1FlexGridIC1ColumnFilter Private _ranges As List(Of Point) = New List(Of Point)()

ltsummarygt このフィッタが受け入れる文字列を定義するポイントのリストを取得します ltsummarygt Public ReadOnly Property Ranges As List(Of Point) Get Return _ranges End Get End Property

範囲リストが空でない場合フィルタはアクティブです Public ReadOnly Property IsActive As Boolean Implements C1WinC1FlexGridIC1ColumnFilterIsActive Get Return _rangesCount gt 0 End Get End Property

フィルタをリセットします Public Sub Reset() Implements C1WinC1FlexGridIC1ColumnFilterReset _rangesClear() End Sub

指定された日付にフィルタを適用します Public Function Apply(ByVal value As Object) As Boolean Implements C1WinC1FlexGridIC1ColumnFilterApply If value IsNot Nothing Then Dim s = valueToString()

If sLength gt 0 Then Dim c As Integer = AscW(CharToUpperInvariant(s(0)))

VBNET

FlexGrid for WinForms

136 Copyright copy GrapeCity Inc All rights reserved

Following is the code of a custom class that implements IC1CustomFilterEditor interface

StringFilterEditorcs

For Each cr In _ranges

If c gt= AscW(CharToUpperInvariant(MicrosoftVisualBasicChrW(crX))) AndAlso c lt= AscW(CharToUpperInvariant(MicrosoftVisualBasicChrW(crY))) Then Return True End If Next End If End If

Return False End Function

このフィルタのエディタコントロールを返します Public Function GetEditor() As C1WinC1FlexGridIC1ColumnFilterEditor Implements C1WinC1FlexGridIC1ColumnFilterGetEditor Return New StringFilterEditor() End Function

End Class

public partial class StringFilterEditor UserControl C1WinC1FlexGridIC1ColumnFilterEditor StringFilter _filter

public StringFilterEditor() InitializeComponent()

public void Initialize(C1WinC1FlexGridC1FlexGridBase grid int columnIndex C1WinC1FlexGridIC1ColumnFilter filter) _filter = (StringFilter)filter

チェックボックスの値を初期化します foreach (var pt in _filterRanges) switch ((char)ptX) case A _chkAEChecked = true break case F _chkFJChecked = true break case K _chkKOChecked = true break case P _chkPTChecked = true

C

FlexGrid for WinForms

137 Copyright copy GrapeCity Inc All rights reserved

break case U _chkUZChecked = true break public void ApplyChanges() フィルタをリセットします _filterRangesClear()

選択した範囲を追加します foreach (Control ctl in thisControls) var cb = ctl as CheckBox if (cb = null ampamp cbChecked) var pt = new Point((int)cbText[0] (int)cbText[cbTextLength - 1]) _filterRangesAdd(pt) public bool KeepFormOpen get return false void _chkAE_CheckedChanged(object sender EventArgs e) var cb = sender as CheckBox cbFont = new Font(Font cbChecked FontStyleBold FontStyleRegular)

Public Partial Class StringFilterEditor Inherits UserControl Implements C1WinC1FlexGridIC1ColumnFilterEditor

Private _filter As StringFilter Public Sub New() InitializeComponent() End Sub

Public Sub Initialize(ByVal grid As C1WinC1FlexGridC1FlexGridBase ByVal columnIndex As Integer ByVal filter As C1WinC1FlexGridIC1ColumnFilter) Implements C1WinC1FlexGridIC1ColumnFilterEditorInitialize _filter = CType(filter StringFilter)

チェックボックスの値を初期化します For Each pt In _filterRanges

Select Case MicrosoftVisualBasicChrW(ptX) Case Ac _chkAEChecked = True Case Fc _chkFJChecked = True Case Kc _chkKOChecked = True Case Pc

VBNET

FlexGrid for WinForms

138 Copyright copy GrapeCity Inc All rights reserved

_chkPTChecked = True Case Uc _chkUZChecked = True End Select Next End Sub

Public Sub ApplyChanges() Implements C1WinC1FlexGridIC1ColumnFilterEditorApplyChanges フィルタをリセットします _filterRangesClear()

選択した範囲を追加します For Each ctl As Control In Controls Dim cb = TryCast(ctl CheckBox)

If cb IsNot Nothing AndAlso cbChecked Then Dim pt = New Point(MicrosoftVisualBasicAscW(cbText(0)) MicrosoftVisualBasicAscW(cbText(cbTextLength - 1))) _filterRangesAdd(pt) End If Next End Sub

Public ReadOnly Property KeepFormOpen As Boolean Implements C1WinC1FlexGridIC1ColumnFilterEditorKeepFormOpen Get Return False End Get End Property

Private Sub _chkAE_CheckedChanged(ByVal sender As Object ByVal e As EventArgs) Dim cb = TryCast(sender CheckBox) cbFont = New Font(MyBaseFont If(cbChecked FontStyleBold FontStyleRegular)) End Sub

End Class

フィルタUI

FlexGrid provides several options to flexibly customize the filtering UI and lets you create your own unique filter for yourapplication The control allows you to show hide and customize the filtering icon You can even change the language displaying infilter to meet your localization requirements

Show Filter Icon

FlexGrid by default shows the filtering icon( ) when mouse hovers over the filterable column header However you can chooseto display the filtering icon always by setting ShowFilterIcon property of the C1FlexGrid class to Always The property accepts thevalues from FilterIconVisibility enumeration

FlexGrid for WinForms

139 Copyright copy GrapeCity Inc All rights reserved

Use the code below to always display the filter icon on filtered columns of the WinForms FlexGrid

Use Custom IconsFlexGrid also lets you customize the filtering icon by using Glyphs property of the C1FlexGrid class which accepts an imagethrough GlyphEnum enumeration You can also change icon displayed on the current filtered column using the same enumerationFor more information about custom glyphs see Custom Glyphs

常にフィルタのアイコンを表示しますc1FlexGrid1ShowFilterIcon = C1WinC1FlexGridFilterIconVisibilityAlways

C

常にフィルタのアイコンを表示しますc1FlexGrid1ShowFilterIcon = C1WinC1FlexGridFilterIconVisibilityAlways

VBNET

FlexGrid for WinForms

140 Copyright copy GrapeCity Inc All rights reserved

Following code displays how to apply custom icons on filtered columns of the WinForms FlexGrid

Change Filter LanguageBy default FlexGrid localizes the column filter editor to use language specified by the CurrentUICulture setting However you canuse the Language property to override the default and specify the language to be used when grid displays the column filter editor

Use the below code to change the display language of filter in the WinForms FlexGrid

フィルタのアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilterEditor] = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilteredColumn] = ImageFromFile(filterico)

C

フィルタのアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilterEditor) = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilteredColumn) = ImageFromFile(filterico)

VBNET

フィルタ言語を日本語に設定しますc1FlexGrid1Language = C1UtilLocalizationLanguageJapanese

C

フィルタ言語を日本語に設定しますc1FlexGrid1Language = C1UtilLocalizationLanguageJapanese

VBNET

FlexGrid for WinForms

141 Copyright copy GrapeCity Inc All rights reserved

検索

With FlexGrid you can easily perform search either on the entire grid or just a specific column This topic discusseshow you can enable search in FlexGrid

Search in Entire GridTo search the entire FlexGrid you need to add the C1FlexGridSearchPanel control to the form and associate it with thegrid to be searched using SetC1FlexGridSearchPanel method The C1FlexGridSearchPanel control highlights thesearch results and filters the records having search results automatically However you can choose not to highlight theresults by setting the HighlightSearchResults to false It also provides a SearchMode property to set whether tostart the search automatically or on hitting the Search button or Enter key You can also set the watermark in searchbox as well as a time delay in search

Use the code below to search the entire WinForms FlexGrid using SearchPanel

検索パネルを検索対象のFlexGridに関連付けますc1FlexGridSearchPanel1SetC1FlexGridSearchPanel(c1FlexGrid1 c1FlexGridSearchPanel1)

検索を構成しますc1FlexGridSearchPanel1HighlightSearchResults = truec1FlexGridSearchPanel1SearchMode = C1WinC1FlexGridSearchModeAlways c1FlexGridSearchPanel1Watermark = Search productsc1FlexGridSearchPanel1SearchDelay = 2

C

検索パネルを検索対象のFlexGridに関連付けます

VBNET

FlexGrid for WinForms

142 Copyright copy GrapeCity Inc All rights reserved

Search in ColumnTo enable column-wise search FlexGrid provides AutoSearch property of the C1FlexGrid class which accepts valuesfrom AutoSearchEnum enumeration The enumeration lets you start downward column search from the first scrollablerow or from the current cursor position To search a value in a particular column you need to keep the cursor in thatcolumn and type the value to be searched and grid automatically jumps to the search result in that column You canalso set delay in search by setting the AutoSearchDelay property

Following code enables column-wise search in the WinForms FlexGrid

c1FlexGridSearchPanel1SetC1FlexGridSearchPanel(c1FlexGrid1 c1FlexGridSearchPanel1)

検索を構成しますc1FlexGridSearchPanel1HighlightSearchResults = Truec1FlexGridSearchPanel1SearchMode = C1WinC1FlexGridSearchModeAlwaysc1FlexGridSearchPanel1Watermark = Search productsc1FlexGridSearchPanel1SearchDelay = 2

一番上の行からの列単位の検索を有効にしますc1FlexGrid1AutoSearch = C1WinC1FlexGridAutoSearchEnumFromTopc1FlexGrid1AutoSearchDelay = 2

C

一番上の行からの列単位の検索を有効にしますc1FlexGrid1AutoSearch = C1WinC1FlexGridAutoSearchEnumFromTopc1FlexGrid1AutoSearchDelay = 2

VBNET

FlexGrid for WinForms

143 Copyright copy GrapeCity Inc All rights reserved

マージ

FlexGrid allows you to merge cells with same values making them span multiple rows or columns This capability is useful for enhancing appearance andclarity of data displayed in the grid The effect of these settings is similar to the HTML ltROWSPANgt and ltCOLSPANgt tags

Cell merging has several possible uses For example you can use it to create merged table headers merged data views or grids where the text spills intoadjacent columns This section discusses these scenarios in the topics below

Topic Snapshot Content

Auto-merge Discusses about how to enable automatic merging in grid

Free auto-mergeRestricted auto-mergeMerge table headers

Handle Spilling Text Discusses how to display long texts in normal and node rows

Handle Spill in Normal CellsHandle Text in Node Rows

Custom Merge Discusses about ways to customize the default merging behavior

Method 1 Use IComparer interfaceMethod 2 Override the GetMergedRange method

自動マージ

FlexGrid lets you enable automatic cell merging in the grid by setting the AllowMerging property to a value other than None Inaddition you need to set the AllowMerging property of each target row or column to true Merging occurs only if adjacent cellscontain the same non-empty string There is no method to force a pair of cells to merge The merging is done automaticallybased on the cell contents This feature makes it easy to provide merged views of sorted data where values in adjacent rowspresent repeated data

Free Auto-mergeFree auto-merge refers to merging of cells with just one pre-condition of having same values in adjacent cells To automaticallymerge the cells in a row or a column you simply need to set AllowMerging property of the C1FlexGrid class to Free and setAllowMerging property of the target row or column object to true

FlexGrid for WinForms

144 Copyright copy GrapeCity Inc All rights reserved

Below code shows how to apply free merging on a WinForms FlexGrid column

Restricted Auto-mergeIn most of the scenarios you would want the grid to merge the grid cells with same values only if cells above or in left directionare also merged This behavior is called restricted auto-merge and can be achieved by setting the C1FlexGridAllowMergingproperty to RestrictAll RestrictRows or RestrictCols This is required in addition to setting the AllowMerging property oftarget row or column to true

Use the code below to allow restricted auto-merging on a WinForms FlexGrid column

Merge Table HeadersMerging the header cells specially in case of multi-row header is another very common scenario used in grids and tables Tomerge the header cells you must set the C1FlexGridAllowMerging property to FixedOnly You must also set theAllowMerging property of designated row and columns to true In this case headers cells with same value merge together togive a simplified appearance

許可される結合の種類を指定しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFree 結合を許可する列を指定しますc1FlexGrid1Cols[2]AllowMerging = true

C

許可される結合の種類を指定しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFree

結合を許可する列を指定しますc1FlexGrid1Cols(2)AllowMerging = True

VBNET

結合を許可する列を指定しますc1FlexGrid1Cols[3]AllowMerging = true 左側のセルが結合されている場合にのみ列を結合しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumRestrictCols

C

結合を許可する列を指定しますc1FlexGrid1Cols(3)AllowMerging = True

左側のセルが結合されている場合にのみ列を結合しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumRestrictCols

VBNET

FlexGrid for WinForms

145 Copyright copy GrapeCity Inc All rights reserved

Following code demonstrates how to apply merging only on table headers of the WinForms FlexGrid

Custom Auto-mergeFlexGrid also provides a Custom option through AllowMerging enumeration In this case auto-merge is performed on cellrange collection provided using MergedRanges property of the C1FlexGrid class The custom auto-merge is performedindependent of cell content For instance below image shows the merging of two specified cell ranges despite of the differentcell values

固定の行と列の結合を許可しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

固定の行と列の結合を許可しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

FlexGrid for WinForms

146 Copyright copy GrapeCity Inc All rights reserved

Use the following code snippet to apply custom merge on the WinForms FlexGrid

結合のモードをアクティブにしますthisc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumCustom

いくつかのマージされた範囲を定義します 2つのセルは幅が広く1つのセルは高いですthisc1FlexGrid1MergedRangesAdd(2 2 2 3)

3つのセルは幅が広く3つのセルは高さですthisc1FlexGrid1MergedRangesAdd(5 2 7 4)

C

結合のモードをアクティブにしますMec1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumCustom

いくつかのマージされた範囲を定義します 2つのセルは幅が広く1つのセルは高いですMec1FlexGrid1MergedRangesAdd(2 2 2 3)

3つのセルは幅が広く3つのセルは高さですMec1FlexGrid1MergedRangesAdd(5 2 7 4)

VBNET

はみ出して表示されるセルの処理

In FlexGrid you can create the same behavior as excel for handling long text entries by spilling them into emptyadjacent cells This behavior not only helps you in handling long text entries of usual cells but also in displayingoutline nodes which are different from data rows This topic discusses these two scenarios in the following sectionsThese settings work on the grid level and does not need you to set AllowMerging property of specific row or column

Handle Spill in Normal CellsThis FlexGrid setting causes text that is too long to fit in a cell to spill into empty adjacent cells If you have a longentry in a cell and the adjacent cell is empty the entry spills onto the adjacent cells to occupy as much room as

FlexGrid for WinForms

147 Copyright copy GrapeCity Inc All rights reserved

needed This behavior can be achieved by setting the AllowMerging property to Spill For instance in the imagebelow long data strings from TestGroup column cells spill to the empty Flag column cells giving a better visibility ofdata while using the available space on the grid

Following code enables spilling of long text to adjacent empty cell in the WinForms FlexGrid

Handle Text in Node RowsThe Nodes setting is similar to Spill but only applies to outline nodes This setting is useful when data is organizedinto groups and the node rows contain information in a format different from the data rows For this you must setthe C1FlexGridAllowMerging property to Nodes

長いテキストを隣接する空のセルにこぼしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumSpill

C

長いテキストを隣接する空のセルにこぼしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumSpill

VBNET

FlexGrid for WinForms

148 Copyright copy GrapeCity Inc All rights reserved

Following code shows how to handle long text in node rows of the WinForms FlexGrid

ノード行の長いテキストを隣接する空のセルにスピルします c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumNodes

C

ノード行の長いテキストを隣接する空のセルにスピルしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumNodes

VBNET

カスタムのマージ

FlexGrid by default gives you enough options to merge in most common scenarios using AllowMerging propertyHowever there may be instances where you want to customize the merging options to get more out of your grid Youcan customize the default merging behavior in two ways

Method 1 Use IComparer InterfaceBy default the grid merges adjacent cells containing same non-null value In default scenario string comparisons arecase-sensitive and blanks are included However you can also merge cells using a case-insensitive comparison andtrimming blanks by writing a custom class that implements IComparer interface and assign it to CustomComparerproperty of the C1FlexGrid class

Method 2 Override the GetMergedRange MethodAnother way is to create a new class that derives from the C1FlexGrid class and overrides the GetMergedRangeand GetData methods to provide your own custom merging logic It merges the cells based on contextual

FlexGrid for WinForms

149 Copyright copy GrapeCity Inc All rights reserved

understanding of data in FlexGrid which is implemented through the overridden methods in the sample The belowexample demonstrates custom merging in timetable of each lecturer using the WinForms FlexGrid

public override CellRange GetMergedRange(int row int col bool clip) 結合のロジックで使用するID列のインデックスを保存します _colIndex = ColsIndexOf(LecturerID)

結合する時にカスタムデータを使用するようにフラグを設定します _doingMerge = true

基本クラスの結合のロジックを呼び出します(GetDataメソッドを使用してデータを取得します) CellRange cellRange = baseGetMergedRange(row col clip)

GetDataが通常どおりに動作するようにフラグをリセットします _doingMerge = false

結合された範囲を返します return cellRange

public override Object GetData(int row int col) 結合範囲を決定するためのデータを取得します ID列のコンテンツを追加して異なるIDの行のセルがマージされないようにします if (_doingMerge ampamp _colIndex gt -1 ampamp col = _colIndex) SystemDiagnosticsDebugWriteLine($rowcol) return baseGetDataDisplay(row col) + baseGetDataDisplay(row _colIndex)

C

FlexGrid for WinForms

150 Copyright copy GrapeCity Inc All rights reserved

For detailed implementation of more scenarios of custom merging see the product Projects named CustomMergeCustomMerge2 CustomMerge3 CustomMerge4

Note The abovementioned product samples are located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installingWinForms Edition using ComponentOneControlPanelexe

表示測定編集などするデータを取得します 基本クラスに通常どおり処理させます return baseGetData(row col)

Public Overrides Function GetMergedRange(ByVal row As Integer ByVal col As Integer ByVal clip As Boolean) As CellRange 結合のロジックで使用するID列のインデックスを保存します _colIndex = ColsIndexOf(LecturerID)

結合する時にカスタムデータを使用するようにフラグを設定します _doingMerge = True

基本クラスの結合のロジックを呼び出します(GetDataメソッドを使用してデータを取得します) Dim cellRange As CellRange = MyBaseGetMergedRange(row col clip)

GetDataが通常どおりに動作するようにフラグをリセットします _doingMerge = False

結合された範囲を返します Return cellRangeEnd Function

Public Overrides Function GetData(ByVal row As Integer ByVal col As Integer) As Object 結合範囲を決定するためのデータを取得します ID列のコンテンツを追加して異なるIDの行のセルがマージされないようにします If _doingMerge AndAlso _colIndex gt -1 AndAlso col ltgt _colIndex Then DebugWriteLine($rowcol) Return MyBaseGetDataDisplay(row col) + MyBaseGetDataDisplay(row _colIndex) End If

表示測定編集などするデータを取得します 基本クラスに通常どおり処理させます Return MyBaseGetData(row col)End Function

VBNET

FlexGrid for WinForms

151 Copyright copy GrapeCity Inc All rights reserved

グループ

Grouping refers to organizing the grid data into a hierarchical structure where rows with common column value aredisplayed as a group The feature also lets you expand or collapse the groups to facilitate easier analysis of grid data

In FlexGrid grouping can be achieved through code as well as through user interaction via column context menuand FlexGridGroupPanel control This topic discusses these ways and additional operations related to grouping

Grouping through CodeFlexGrid provides GroupDescriptions property to describe how data source items are grouped in the grid Thisproperty accepts the instance of any collection which implements IList interface (eg List) as its value The items of thecollection describe grouping using a property name as the criterion

Following code shows how to apply grouping in the WinForms FlexGrid through code

Grouping through Group Panel

CustomerIDでデータをグループ化しますc1FlexGrid1GroupDescriptions = new ListltGroupDescriptiongt() new GroupDescription(CustomerID)

C

CustomerIDでデータをグループ化しますc1FlexGrid1GroupDescriptions = New List(Of GroupDescription)() From New GroupDescription(CustomerID)

VBNET

FlexGrid for WinForms

152 Copyright copy GrapeCity Inc All rights reserved

FlexGrid also lets you create groups at runtime using an extension control named C1FlexGridGroupPanel which isprovided by the C1WinC1FlexGridGroupPanel assembly

To achieve grouping in FlexGrid at runtime add the C1FlexGridGroupPanel control to the form and bind it with thegrid to be bound using FlexGrid property of the C1FlexGridGroupPanel class Once a grid is bound to the grouppanel control you can drag and drop the columns to panel in order to group the grid by that column To create anested hierarchy of dragged columns you can drag multiple columns in the desired order You can also set themaximum number of groups allowed within FlexGrid using MaxGroups property of the C1FlexGridGroupPanel classBy default all the created groups appear in the expanded state To change this setting and display the groups incollapsed state by default you can set the AutoExpandAllGroups property to false The group panel control alsoprovides the Text property to display a string when no columns are dropped on the panel

Use the code below to apply grouping in WinForms FlexGrid through the FlexGridGroupPanel control

C1FlexGridGroupPanel c1FlexGridGroupPanel = new C1FlexGridGroupPanel()c1FlexGridGroupPanelBounds = new SystemDrawingRectangle(00 650 150)thisControlsAdd(c1FlexGridGroupPanel) C1FlexGridGroupPanelの一般プロパティを設定しますc1FlexGridGroupPanelFlexGrid = c1FlexGrid1c1FlexGridGroupPanelText = Drag the columns herec1FlexGridGroupPanelMaxGroups = 5c1FlexGridGroupPanelAutoExpandAllGroups = true

C

Dim c1FlexGridGroupPanel As C1FlexGridGroupPanel = New C1FlexGridGroupPanel() c1FlexGridGroupPanelBounds = New DrawingRectangle(0 0 650 150) MeControlsAdd(c1FlexGridGroupPanel)

VBNET

FlexGrid for WinForms

153 Copyright copy GrapeCity Inc All rights reserved

Grouping through Context MenuFlexGrid provides support for column context menu at run-time to facilitate quick actions related to columnoperations One of these context menu options is Group By This Column You can use this context menu option togroup the grid data by any of the columns at run-time Once grouping is applied you also get the Ungroup option toremove grouping To enable the column context menu you need to set ColumnContextMenuEnabled propertyprovided by the C1FlexGrid class to true By default this property is set to false

Grouping and MoreApart from the default features grouping in FlexGrid comes with many other options to give you ample flexibility tomeet your requirements

Use the SubtotalPosition property to change the position of group row which gets displayed above the groupby defaultSet the HideGroupedColumns property to true to hide the columns by which grid is groupedChange the format of group header by using the GroupHeaderFormat property By default the group row

C1FlexGridGroupPanelの一般プロパティを設定します c1FlexGridGroupPanelFlexGrid = c1FlexGrid1 c1FlexGridGroupPanelText = Drag the columns here c1FlexGridGroupPanelMaxGroups = 5 c1FlexGridGroupPanelAutoExpandAllGroups = True

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = true

C

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = True

VBNET

FlexGrid for WinForms

154 Copyright copy GrapeCity Inc All rights reserved

displays a string of namevalue formatSet the C1FlexGridAllowMerging property to AllowMergingEnumNodes to spill the long group headercontent into the adjacent empty cells For more information see Handle Text in Node RowsDisplay aggregate value of columns in group header by using Aggregate property of the Column classUse AllowSorting property to sort the groups based on their valuesUse the GridTreeStyle property to customize the appearance of outline tree that shows the grouping inFlexGrid For more information see Style the Tree Grid

FlexGrid for WinForms

155 Copyright copy GrapeCity Inc All rights reserved

集計

Summarizing data is one of the most important features of the grid where you can easily group the similar data andcalculate various types of aggregates such as Sum Average Count Max Min and more

In FlexGrid you can easily summarize data by using SubTotal method of the C1FlexGrid class It adds subtotal rows thatcontain aggregate data for the regular (non-subtotal) rows and also supports the hierarchical aggregates The method hasvarious overloads which gives you enough flexibility to deal with multiple summarizing related scenarios All theseoverloads have one parameter in common that is AggregateEnum which lets you set the type of aggregate you want toimplement Other parameters in various overloads let you set the outline level start and end column and column thatcontains values to be aggregated

Create SubtotalsBelow example demonstrates the use of SubTotal method in the WinForms FlexGrid for calculation of average aggregatebased on Score column

Style SubtotalsWhen the Subtotal method adds the rows with the aggregate information it automatically assigns in-built subtotal styles

グリッドに存在する既存の小計をすべてクリアしますc1FlexGrid1Subtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加しますc1FlexGrid1Subtotal(AggregateEnumAverage 1 3 3 4 Average for 0)

C

グリッドに存在する既存の小計をすべてクリアしますc1FlexGrid1Subtotal(AggregateEnumClear)

レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加しますc1FlexGrid1Subtotal(AggregateEnumAverage 1 3 3 4 Average for 0)

VBNET

FlexGrid for WinForms

156 Copyright copy GrapeCity Inc All rights reserved

to the new rows You can customize the appearance of the subtotal rows by changing the properties of the outline stylesin the designer with the Style Editor or using the code Below example demonstrates styling of subtotals at three levels inthe WinForms FlexGrid

Customize SubtotalsFlexGrid in addition to built-in aggregate options lets you create custom expressions in bound mode and use them assubtotals in groups along with aggregates You can specify the custom expressions for a column using GroupExpressionproperty of the Column class Below example demonstrates how to create a custom expression as a subtotal for Qualifiedcolumn of the WinForms FlexGrid

小計をレベル0でスタイル設定しますCellStyle s = c1FlexGrid1Styles[CellStyleEnumSubtotal0]sBackColor = ColorBlacksForeColor = ColorWhitesFont = new Font(c1FlexGrid1Font FontStyleBold) 小計をレベル1でスタイル設定しますs = c1FlexGrid1Styles[CellStyleEnumSubtotal1]sBackColor = ColorDarkBluesForeColor = ColorWhite

小計をレベル2でスタイル設定しますs = c1FlexGrid1Styles[CellStyleEnumSubtotal2]sBackColor = ColorDarkRedsForeColor = ColorWhitec1FlexGrid1AutoSizeCols()

C

Dim s As CellStyle = c1FlexGrid1Styles(CellStyleEnumSubtotal0) sBackColor = ColorBlack sForeColor = ColorWhite sFont = New Font(c1FlexGrid1Font FontStyleBold)

s = c1FlexGrid1Styles(CellStyleEnumSubtotal1) sBackColor = ColorDarkBlue sForeColor = ColorWhite

s = c1FlexGrid1Styles(CellStyleEnumSubtotal2) sBackColor = ColorDarkRed sForeColor = ColorWhite c1FlexGrid1AutoSizeCols()

VBNET

FlexGrid for WinForms

157 Copyright copy GrapeCity Inc All rights reserved

public void CustomizeSubTotal(C1FlexGrid c1FlexGrid1) ListltGroupDescriptiongt grps = new ListltGroupDescriptiongt() 列「Course」のグループを作成します GroupDescription grp = new GroupDescription(Course ListSortDirectionDescending true) grpsAdd(grp) 上記のグループに従ってFlexGridをグループ化します c1FlexGrid1GroupDescriptions = grps カスタムの計算式を使用してFlexGridに新しい列を追加します var column = c1FlexGrid1ColsAdd() columnName = Qualified columnDataType = typeof(object) columnCaption = Qualified(gt5000) columnAllowEditing = false columnExpression = [Attendance] [Score] GroupExpression の実装 c1FlexGrid1Cols[Score]GroupExpression = =Average([Score]) c1FlexGrid1Cols[Attendance]GroupExpression = =Average([Attendance]) c1FlexGrid1Cols[Qualified]GroupExpression = =iif(Average([Score][Attendance])lt5000falsetrue) c1FlexGrid1AutoSizeCols()

C

Public Sub CustomizeSubTotal(ByVal c1FlexGrid1 As C1FlexGrid) Dim grps As List(Of GroupDescription) = New List(Of GroupDescription)() 列「Course」のグループを作成します Dim grp As GroupDescription = New GroupDescription(Course ListSortDirectionDescending True) grpsAdd(grp)

上記のグループに従ってFlexGridをグループ化します c1FlexGrid1GroupDescriptions = grps

カスタムの計算式を使用してFlexGridに新しい列を追加します Dim column = c1FlexGrid1ColsAdd()

VBNET

FlexGrid for WinForms

158 Copyright copy GrapeCity Inc All rights reserved

columnName = Qualified columnDataType = GetType(Object) columnCaption = Qualified(gt5000) columnAllowEditing = False columnExpression = [Attendance] [Score]

GroupExpression の実装 c1FlexGrid1Cols(Score)GroupExpression = =Average([Score]) c1FlexGrid1Cols(Attendance)GroupExpression = =Average([Attendance]) c1FlexGrid1Cols(Qualified)GroupExpression = =iif(Average([Score][Attendance])lt5000falsetrue) c1FlexGrid1AutoSizeCols()End Sub

FlexGrid for WinForms

159 Copyright copy GrapeCity Inc All rights reserved

ツリーグリッド

OverviewOne of the unique and popular features of the FlexGrid control is the ability to add hierarchical grouping to regulardata grid and display it in a tree like structure called Tree Grid The Tree Grid control is very similar to the one you seein a TreeView control It shows an indented structure with collapse or expand icon next to each node row so the usercan expand and collapse the outline to see the desired level of detail by clicking on the nodes

Although you can create simple outline trees using FlexGrid grouping Tree Grid helps you implement more advanceduse cases such as displaying customer and order details In a usual grid showing such data it is difficult to see thedetails of each customer and order In such case you can create a Tree Grid to group the data in a hierarchicalstructure for better view and accessibility of information

Quick BindingLoading data in a Tree Grid is exactly the same as loading in a regular grid If the data source is available at designtime you can use the Visual Studio Property Window to set the grids DataSource property of the C1FlexGrid class andbind the grid to the data without writing even a single line of code For detailed steps see Bound Mode

You can also set the DataSource property through code Following code shows how to use the DataSource propertyto populate data in the WinForms Tree Grid

private void Bound_Node_Load(object sender EventArgs e) FlexGridを連結します BindGrid(_gridBound)

public void BindGrid(C1FlexGrid grid) DataTable _dt = new DataTable() データを取得します var fields = Country City SalesPerson Quantity ExtendedPrice var sql = stringFormat(SELECT 0 FROM Invoices ORDER BY 0 fields)

C

FlexGrid for WinForms

160 Copyright copy GrapeCity Inc All rights reserved

The code uses an OleDbDataAdapter to fill a DataTable with data then assigns datatable to DataSource property ofthe grid To turn this regular grid in a Tree grid you need to insert the node rows which is discussed in the sectionbelow

Create Nodes (Bound and Unbound Mode)To create a Tree Grid FlexGrid introduces a concept of Node rows These rows do not contain regular data and aresimply header rows under which similar data is grouped just like nodes in a usual TreeView control You can alsodefine the hierarchy of these nodes by setting the Level property These nodes can be collapsed and expanded to hideor show the data they contain The Tree Grid can be displayed in any column defined by the GridTreeColumnproperty By default this property is set to -1 which causes the tree not to be displayed at all

Bound Mode (Using InsertNode Method)

You can create node rows using InsertNode method of the RowCollection class which inserts a new node row at a

var da = new OleDbDataAdapter(sql GetConnectionString()) daFill(_dt) グリッドにデータを連結します gridDataSource = _dt ExtendedPrice 列を書式設定します gridCols[ExtendedPrice]Format = n2

static string GetConnectionString() string path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) + ComponentOne SamplesCommon string conn = provider=microsoftjetoledb40data source=0c1nwindmdb return stringFormat(conn path)

Private Sub Bound_Node_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを連結します BindGrid(_gridBound) End Sub

Public Sub BindGrid(ByVal grid As C1FlexGrid) Dim _dt As DataTable = New DataTable() データを取得します Dim fields = Country City SalesPerson Quantity ExtendedPrice Dim sql = StringFormat(SELECT 0 FROM Invoices ORDER BY 0 fields) Dim da = New OleDbDataAdapter(sql GetConnectionString()) daFill(_dt) グリッドにデータを連結します gridDataSource = _dt ExtendedPrice 列を書式設定します gridCols(ExtendedPrice)Format = n2 End Sub

Private Shared Function GetConnectionString() As String Dim path As String = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) amp ComponentOne SamplesCommon Dim conn As String = provider=microsoftjetoledb40data source=0c1nwindmdb Return StringFormat(conn path) End Function

VBNET

FlexGrid for WinForms

161 Copyright copy GrapeCity Inc All rights reserved

specified index This is the low-level way of inserting totals and building outlines

The GroupBy method used here inserts node rows by grouping identical values To obtain a Node object you caneither use return value of the InsertNode method or retrieve the node for an existing row using the IsNode property

Use the following code to create nodes using InsertNode method in the bound WinForms Tree Grid

private void Bound_Node_Load(object sender EventArgs e) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) GroupBy(_gridBound Country 0) GroupBy(_gridBound City 1) public void CreateTree(C1FlexGrid grid) gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)

void GroupBy(C1FlexGrid grid string columnName int level) レベル0でグループのスタイル設定します CellStyle s0 = gridStylesAdd(Group0) s0BackColor = ColorGray s0ForeColor = ColorWhite s0Font = new Font(gridFont FontStyleBold) レベル1でグループのスタイル設定します CellStyle s1 = gridStylesAdd(Group1) s1BackColor = ColorLightGray s1ForeColor = ColorBlack object current = null for (int r = gridRowsFixed r lt gridRowsCount r++)

C

FlexGrid for WinForms

162 Copyright copy GrapeCity Inc All rights reserved

if (gridRows[r]IsNode) var value = grid[r columnName] if (objectEquals(value current)) 値が変更されました ノードを挿入します gridRowsInsertNode(r level) if (level == 0) gridRows[r]Style = s0 else if (level == 1) gridRows[r]Style = s1 最初のスクロール可能な列にグループ名を表示します grid[r gridColsFixed] = value 現在の値を更新します current = value gridAutoSizeCols()

Private Sub Bound_Node_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) GroupBy(_gridBound Country 0) GroupBy(_gridBound City 1)End Sub

Public Sub CreateTree(ByVal grid As C1FlexGrid) gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)End Sub

Private Sub GroupBy(ByVal grid As C1FlexGrid ByVal columnName As String ByVal level As Integer) レベル0でグループのスタイル設定します Dim s0 As CellStyle = gridStylesAdd(Group0) s0BackColor = ColorGray s0ForeColor = ColorWhite s0Font = New Font(gridFont FontStyleBold) レベル1でグループのスタイル設定します Dim s1 As CellStyle = gridStylesAdd(Group1) s1BackColor = ColorLightGray s1ForeColor = ColorBlack Dim current As Object = Nothing Dim r As Integer = gridRowsFixed

While r And lt gridRowsCount End While

r += 1

If True Then

If Not gridRows(r)IsNode Then Dim value = grid(r columnName)

VBNET

FlexGrid for WinForms

163 Copyright copy GrapeCity Inc All rights reserved

The code also calls the AutoSizeCols method to ensure that the column is wide enough to accommodate the TreeGrid Finally it calls the GridTreeShow method to display the nodes

Also the Node class provides following methods and properties based on TreeView object model which can be usedto manage the Tree Grid

Checked Gets or sets the check state of cell defined by NodeRow and GridTreeColumnCollapsedExpanded Gets or sets collapsed or expanded state of the nodeData Gets or sets value in the cell defined by NodeRow and GridTreeColumnImage Gets or sets image in the cell defined by NodeRow and GridTreeColumnLevel Gets or sets node level in the Tree Grid

You can also explore the outline structure using the following properties and methods

Children Gets number of child nodes under this nodeGetCellRange Gets the CellRange object that described range of rows that belong to this nodeGetNode Gets the node that has a given relationship to this node (parent first child next sibling and so on)Nodes Gets a node array containing child nodes of this node

Bound Mode (Using Subtotal Method)

In bound mode another way to create nodes is using the Subtotal method To make the Tree Grid really useful thenode rows must include summary information for the data they contain

If you create Tree Grid using the Subtotal method the subtotals are added automatically The method scans theentire grid and automatically inserts node rows with optional subtotals at locations where the grid data changes

This is the high-level way of inserting totals and building outlines

If Not ObjectEquals(value current) Then 値が変更されました ノードを挿入します gridRowsInsertNode(r level)

If level = 0 Then gridRows(r)Style = s0 ElseIf level = 1 Then gridRows(r)Style = s1 End If

最初のスクロール可能な列にグループ名を表示します grid(r gridColsFixed) = value 現在の値を更新します current = value End If End IfEnd If gridAutoSizeCols()End Sub

FlexGrid for WinForms

164 Copyright copy GrapeCity Inc All rights reserved

The first parameter of the Subtotal method is AggregateEnum enumeration which calculates various types ofaggregates like Sum Average Count Max Min and others In the code below Subtotal method of the C1FlexGridclass is used for creating nodes in a bound WinForms Tree Grid

private void SubtotalNode_Bound_Load(object sender EventArgs e) FlexGridを取得します BindGrid(_gridBound) shows Tree in Bound FlexGrid CreateTree(_gridBound) 連結されたFlexGridに小計を作成します CreateSubTotal(_gridBound)public void BindGrid(C1FlexGrid grid) DataTable dt = new DataTable() dtColumnsAdd(ID typeof(int)) dtColumnsAdd(Name typeof(string)) dtColumnsAdd(Course typeof(string)) dtColumnsAdd(Score typeof(int)) dtColumnsAdd(Attendance typeof(int)) dtColumnsAdd(Country typeof(string)) サンプルデータ dtRowsAdd(1 Helen Bennett ComputerScience 79 84 Spain) dtRowsAdd(2 Ana Trujillo Biology 78 87 Mexico) dtRowsAdd(3 Antonio Moreno Aeronautics 71 70 Spain) dtRowsAdd(4 Paolo Accorti Biology 74 63 Spain) dtRowsAdd(5 Elizabeth Brown ComputerScience 80 93 Mexico) dtRowsAdd(6 Jaime Yorres Biology 61 48 Spain) dtRowsAdd(7 Yvonne Moncada Aeronautics 85 78 Mexico) dtRowsAdd(8 Martine Ranceacute Aeronautics 67 81 Spain) dtRowsAdd(9 Sergio Gutieacuterrezy ComputerScience 62 58 Mexico) dtRowsAdd(10 Thomas Hardy Aeronautics 94 92 Mexico) dtRowsAdd(11 Patricio Simpson Aeronautics 46 52 Spain) dtRowsAdd(12 Maria Anders ComputerScience 85 73 Spain) gridDataSource = dt gridAutoSizeCols() (gridDataSource as DataTable)DefaultViewSort = Course

C

FlexGrid for WinForms

165 Copyright copy GrapeCity Inc All rights reserved

FlexGridでツリーを作成しますpublic void CreateTree(C1FlexGrid grid) gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1) gridAutoSizeCols()public void CreateSubTotal(C1FlexGrid grid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加します gridSubtotal(AggregateEnumAverage 1 3 3 4 Average for 0) gridAutoSizeCols()

Private Sub SubtotalNode_Bound_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) Creates Subtotal(s) in Bound FlexGrid CreateSubTotal(_gridBound)End Sub

Public Sub BindGrid(ByVal grid As C1FlexGrid) Dim dt As DataTable = New DataTable() dtColumnsAdd(ID GetType(Integer)) dtColumnsAdd(Name GetType(String)) dtColumnsAdd(Course GetType(String)) dtColumnsAdd(Score GetType(Integer)) dtColumnsAdd(Attendance GetType(Integer)) dtColumnsAdd(Country GetType(String))

サンプルデータ dtRowsAdd(1 Helen Bennett ComputerScience 79 84 Spain) dtRowsAdd(2 Ana Trujillo Biology 78 87 Mexico) dtRowsAdd(3 Antonio Moreno Aeronautics 71 70 Spain) dtRowsAdd(4 Paolo Accorti Biology 74 63 Spain) dtRowsAdd(5 Elizabeth Brown ComputerScience 80 93 Mexico) dtRowsAdd(6 Jaime Yorres Biology 61 48 Spain) dtRowsAdd(7 Yvonne Moncada Aeronautics 85 78 Mexico) dtRowsAdd(8 Martine Ranceacute Aeronautics 67 81 Spain) dtRowsAdd(9 Sergio Gutieacuterrezy ComputerScience 62 58 Mexico) dtRowsAdd(10 Thomas Hardy Aeronautics 94 92 Mexico) dtRowsAdd(11 Patricio Simpson Aeronautics 46 52 Spain) dtRowsAdd(12 Maria Anders ComputerScience 85 73 Spain) gridDataSource = dt gridAutoSizeCols() TryCast(gridDataSource DataTable)DefaultViewSort = CourseEnd Sub

FlexGridでツリーを作成しますPublic Sub CreateTree(ByVal grid As C1FlexGrid) gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)

VBNET

FlexGrid for WinForms

166 Copyright copy GrapeCity Inc All rights reserved

Unbound Mode (Using Subtotal Method)

The Subtotal method is a very convenient and flexible way to create a tree grid It has a number of overloads thatallow you to specify which columns are to be grouped on and totaled on by index or by name whether to include acaption in the node rows that it inserts how to perform the grouping and so on

In the code below Subtotal method of the C1FlexGrid class is used for creating nodes in an unbound WinForms TreeGrid

gridAutoSizeCols()End Sub

Public Sub CreateSubTotal(ByVal grid As C1FlexGrid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加します gridSubtotal(AggregateEnumAverage 1 3 3 4 Average for 0) gridAutoSizeCols()End Sub

private void Unbound_Subtotal_Load(object sender EventArgs e) 連結されていないFlexGridにデータを追加します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) 連結されていないFlexGridに小計を作成します CreateSubTotal(_gridUnbound) public void PopulateGrid(C1FlexGrid grid) グリッドにデータを入力します Random rnd = new Random() gridRowsCount = 14 grid[0 1] = Direction grid[0 2] = Region CellRange rg = gridGetCellRange(0 3 0 gridColsCount - 1) rgData = Rnd

C

FlexGrid for WinForms

167 Copyright copy GrapeCity Inc All rights reserved

for (int r = 1 r lt gridRowsCount r++) grid[r 0] = r grid[r 1] = (r lt 7) Inbound Outbound grid[r 2] = (r lt 3) North (r lt 7) South (r lt 10) East West for (int c = 3 c lt gridColsCount c++) grid[r c] = rndNext(1000) gridCols[c]Format = gridAutoSizeCols()

FlexGridでツリーを作成しますprivate void ShowTreeNode(C1FlexGrid grid) ツリーを作成します gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols()

Creates Subtotal in FlexGridpublic void CreateSubTotal(C1FlexGrid grid) Clears any existing subtotal(s) present in grid gridSubtotal(AggregateEnumClear) for (int c = 3 c lt gridColsCount c++) Adds subtotals in grid gridSubtotal(AggregateEnumSum 0 -1 c Grand Total) gridSubtotal(AggregateEnumSum 2 2 c Total for 0) gridAutoSizeCols()

Private Sub Unbound_Subtotal_Load(ByVal sender As Object ByVal e As EventArgs) 連結されていないFlexGridにデータを追加します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) 連結されていないFlexGridに小計を作成します CreateSubTotal(_gridUnbound) End Sub

Public Sub PopulateGrid(ByVal grid As C1FlexGrid) グリッドにデータを入力します Dim rnd As Random = New Random() gridRowsCount = 14 grid(0 1) = Direction grid(0 2) = Region Dim rg As CellRange = gridGetCellRange(0 3 0 gridColsCount - 1) rgData = Rnd Dim r As Integer = 1

While r And lt gridRowsCount End While

VBNET

FlexGrid for WinForms

168 Copyright copy GrapeCity Inc All rights reserved

r += 1

If True Then grid(r 0) = r grid(r 1) = r And lt 7 Inbound Outbound grid(r 2) = r And lt 3 North r And lt 7 South r And lt 10 East West Dim c As Integer = 3

While c And lt gridColsCount End While

c += 1

If True Then grid(r c) = rnd[Next](1000) gridCols(c)Format = End If End If

gridAutoSizeCols() End Sub

FlexGridでツリーを作成します Private Sub ShowTreeNode(ByVal grid As C1FlexGrid) ツリーを作成しますFlexGridでツリーを作成します gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols() End Sub

FlexGridで小計を作成します Public Sub CreateSubTotal(ByVal grid As C1FlexGrid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) Dim c As Integer = 3

While c And lt gridColsCount End While

c += 1

If True Then グリッドに小計を追加します gridSubtotal(AggregateEnumSum 0 -1 c Grand Total) gridSubtotal(AggregateEnumSum 2 2 c Total for 0) End If

gridAutoSizeCols() End Sub

FlexGrid for WinForms

169 Copyright copy GrapeCity Inc All rights reserved

Unbound Mode(Using IsNode Property)

In an unbound grid you can turn regular rows into node rows by simply setting the IsNode property to true If youtry to turn a regular data bound row into a node it causes the grid to throw an exception

Use the following code to create nodes using IsNode property in an unbound WinForms Tree Grid

private void Unbound_Row_Load(object sender EventArgs e) 連結されていないFlexGridにデータを入力します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound)

private void PopulateGrid(C1FlexGrid grid) FlexGridをリセットします gridRowsCount = 0 gridColsCount = 2 string fileName = testxml xmlドキュメントをロードします XmlDocument xdoc = new XmlDocument() xdocLoad(fileName) XMLドキュメントを読み取りFlexGridのノードとして表示します ShowNode(_gridUnbound xdocChildNodes[1] 0) gridAutoSizeCols() FlexGridでツリーを作成しますprivate void ShowTreeNode(C1FlexGrid grid) ツリーを作成します gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols()

FlexGridにxmlノードを追加しますprivate void ShowNode(C1FlexGrid grid XmlNode node int level)

C

FlexGrid for WinForms

170 Copyright copy GrapeCity Inc All rights reserved

コメントノードをスキップします if (nodeNodeType == XmlNodeTypeComment) return 読み取りxmlノードの新しい行を追加します int row = gridRowsCount gridRowsAdd() グリッドのセルにxmlノードデータを割り当てます grid[row 0] = nodeName xmlノードに子が1つしかないかどうかを確認します if (nodeChildNodesCount == 1) グリッドのセルにノード値を設定します grid[row 1] = nodeInnerText 新しい行をノードにします gridRows[row]IsNode = true gridRows[row]NodeLevel = level ノードに子がある場合はそれらも取得します if (nodeChildNodesCount gt 1) 子を取得するために再帰します foreach (XmlNode child in nodeChildNodes) ShowNode(_gridUnbound child level + 1)

Private Sub Unbound_Row_Load(ByVal sender As Object ByVal e As EventArgs) 連結されていないFlexGridにデータを入力します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) End Sub

Private Sub PopulateGrid(ByVal grid As C1FlexGrid) FlexGridをリセットします gridRowsCount = 0 gridColsCount = 2 Dim fileName As String = testxml xmlドキュメントをロードします Dim xdoc As XmlDocument = New XmlDocument() xdocLoad(fileName) XMLドキュメントを読み取りFlexGridのノードとして表示します ShowNode(_gridUnbound xdocChildNodes(1) 0) gridAutoSizeCols() End Sub

FlexGridでツリーを作成します Private Sub ShowTreeNode(ByVal grid As C1FlexGrid) ツリーを作成します gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols() End Sub

FlexGridにxmlノードを追加します Private Sub ShowNode(ByVal grid As C1FlexGrid ByVal node As XmlNode ByVal level As Integer) コメントノードをスキップします If nodeNodeType Is XmlNodeTypeComment Then Return

VBNET

FlexGrid for WinForms

171 Copyright copy GrapeCity Inc All rights reserved

読み取りxmlノードの新しい行を追加します Dim row As Integer = gridRowsCount gridRowsAdd() グリッドのセルにxmlノードデータを割り当てます grid(row 0) = nodeName

xmlノードに子が1つしかないかどうかを確認します If nodeChildNodesCount = 1 Then グリッドのセルにノード値を設定します grid(row 1) = nodeInnerText End If

新しい行をノードにします gridRows(row)IsNode = True gridRows(row)NodeLevel = level

ノードに子がある場合はそれらも取得します If nodeChildNodesCount And gt Then End If

1

If True Then

子を取得するために再帰します For Each child As XmlNode In nodeChildNodes ShowNode(_gridUnbound child level + 1) Next End If End Sub

ノードの操作

Tree Grid not only allows you to present the data in a structured form but it also supports performing variousoperations with the nodes You can add delete move and fetch nodes by using various methods provided bythe Node class

FlexGrid for WinForms

172 Copyright copy GrapeCity Inc All rights reserved

Add NodeYou can add a node at a specific position in the Tree Grid using AddNode method of the Node class This appends anew node row to the collection The method takes NodeTypeEnum enumeration as its argument which lets youspecify a node with respect to another given node

The code below shows how to add a node in the WinForms Tree Grid at a specific location

private void cmbAdd_SelectionChangeCommitted(object sender SystemEventArgs e) 現在の行ノードを取得します Node nd = flexRows[flexRow]Node ユーザーの要求に応じて相対を追加します (could be a child or a sibling) ndAddNode((NodeTypeEnum)(cmbAddSelectedIndex + 2) cmbAddText) flexFocus()

C

Private Sub cmbAdd_SelectionChangeCommitted(ByVal sender As Object ByVal e As EventArgs) 現在の行ノードを取得します Dim nd As Node = flexRows(flexRow)Node ユーザーの要求に応じて相対を追加します (could be a child or a sibling) ndAddNode(CType(cmbAddSelectedIndex + 2 NodeTypeEnum) cmbAddText)

VBNET

FlexGrid for WinForms

173 Copyright copy GrapeCity Inc All rights reserved

Delete NodeYou can delete a selected node from the Tree Grid using RemoveNode method of the Node class

Following code demonstrates how to delete a node from the WinForms Tree Grid

Move NodeThe Tree Grid allows you to move the node rows to a new position using Move method of the Node class Themethod takes NodeMoveEnum enumeration as an argument which lets you specify the direction in which node hasto be moved

Use the code below to move a node of the WinForms Tree Grid to a new position

flexFocus()End Sub

private void btnDelete_Click(object sender SystemEventArgs e) 現在のノードを取得します Node nd = null if ( flexRowsCount gt 0 ampamp flexRow gt= 0 ampamp flexRow lt flexRowsCount) nd = flexRows[flexRow]Node if (nd = null) FlexGridからノードを削除します ndRemoveNode() flexFocus()

C

Private Sub btnDelete_Click(ByVal sender As Object ByVal e As EventArgs) 現在のノードを取得します Dim nd As Node = Nothing

If flexRowsCount gt 0 AndAlso flexRow gt= 0 AndAlso flexRow lt flexRowsCount Then nd = flexRows(flexRow)Node End If

If nd IsNot Nothing Then FlexGridからノードを削除します ndRemoveNode() flexFocus() End IfEnd Sub

VBNET

private void btnMove_Click(object sender SystemEventArgs e) 現在の行のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択した動きを適用します

C

FlexGrid for WinForms

174 Copyright copy GrapeCity Inc All rights reserved

Select NodesIn Tree Grid you can select the nodes to perform different operations using GetNode method of the Node class Themethod takes a parameter called NodeTypeEnum enumeration which specifies a node with respect to another givennode

The code below specifies how to fetch a specific node of the WinForms Tree Grid and show it in selected state

(これにより選択したノードが移動します) if (sender == btnMoveOut) ndMove(NodeMoveEnumOut) else if (sender == btnMoveIn) ndMove(NodeMoveEnumIn) else if (sender == btnMoveUp) ndMove(NodeMoveEnumUp) else if (sender == btnMoveDown) ndMove(NodeMoveEnumDown) else if (sender == btnMoveFirst) ndMove(NodeMoveEnumFirst) else if (sender == btnMoveLast) ndMove(NodeMoveEnumLast) ノードがまだ表示されていることを確認します ndEnsureVisible() flexFocus()

Private Sub btnMove_Click(ByVal sender As Object ByVal e As EventArgs) 現在の行のノードを取得します Dim nd As Node = flexRows(flexRow)Node

ユーザーが選択した動きを適用します (これにより選択したノードが移動します) If sender Is btnMoveOut Then ndMove(NodeMoveEnumOut) ElseIf sender Is btnMoveIn Then ndMove(NodeMoveEnum[In]) ElseIf sender Is btnMoveUp Then ndMove(NodeMoveEnumUp) ElseIf sender Is btnMoveDown Then ndMove(NodeMoveEnumDown) ElseIf sender Is btnMoveFirst Then ndMove(NodeMoveEnumFirst) ElseIf sender Is btnMoveLast Then ndMove(NodeMoveEnumLast) End If

ノードがまだ表示されていることを確認します ndEnsureVisible() flexFocus()End Sub

VBNET

private void cmbSelect_SelectionChangeCommitted(object sender SystemEventArgs e) 現在の行のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択したノードを取得します nd = ndGetNode((NodeTypeEnum)cmbSelectSelectedIndex) 失敗した場合はメッセージを表示します if (nd == null) MessageBoxShow(Cant find + cmbSelectText + for this node) return ノードを選択しそれが表示されていることを確認します(スクロールして表示します)

C

FlexGrid for WinForms

175 Copyright copy GrapeCity Inc All rights reserved

Expand and Collapse NodesYou can expand and collapse all nodes in your Tree Grid application using the Collapsed property of Node class asshown in the code below This feature makes it convenient to navigate through node headers as a group whenrequired

Following code shows how to expand and collapse nodes of the WinForms Tree Grid

ndSelect() ndEnsureVisible() flexFocus()

Private Sub cmbSelect_SelectionChangeCommitted(ByVal sender As Object ByVal e As EventArgs) 現在の行のノードを取得します Dim nd As Node = flexRows(flexRow)Node ユーザーが選択したノードを取得します nd = ndGetNode(CType(cmbSelectSelectedIndex NodeTypeEnum))

失敗した場合はメッセージを表示します If nd Is Nothing Then MessageBoxShow(Cant find amp cmbSelectText amp for this node) Return End If

ノードを選択しそれが表示されていることを確認します(スクロールして表示します) nd[Select]() ndEnsureVisible() flexFocus()End Sub

VBNET

foreach (Row row in flexRowsCastltRowgt()Where(rw =gt rwIsNode == true)) Node node = rowNode nodeCollapsed = false

foreach (Row row in flexRowsCastltRowgt()Where(rw =gt rwIsNode == true)) Node node = rowNode nodeCollapsed = true

C

For Each row As Row In flexRowsCast(Of Row)()Where(Function(rw) rwIsNode = True) Dim node As Node = rowNode nodeCollapsed = False Next

For Each row As Row In flexRowsCast(Of Row)()Where(Function(rw) rwIsNode = True) Dim node As Node = rowNode nodeCollapsed = True Next

VBNET

FlexGrid for WinForms

176 Copyright copy GrapeCity Inc All rights reserved

Drag and Drop NodesIn Tree Grid you can drag and drop a selected node to a specific position by handling the MouseUp MouseDownand MouseMove events

The code below lets the user drag and drop nodes of the WinForms Tree Grid

private void flex_MouseDown(object sender MouseEventArgs e) m_DragInfocheckDrag = false 左ボタンを押すと移動しません ドラッグするマウスの追跡を開始します if (eButton = MouseButtonsLeft) return if (chkDragChecked || m_DragInfodragging) return if (flexMouseRow lt flexRowsFixed || flexMouseCol = 0) return 現在の行とマウスの位置を保存します m_DragInforow = flexRow m_DragInfomouseDown = new Point(eX eY) チェックを開始します m_DragInfocheckDrag = true

private void flex_MouseMove(object sender MouseEventArgs e) チェックしてユーザーが許容範囲を超えた場合はドラッグを開始します if (m_DragInfocheckDrag || eButton = MouseButtonsLeft) return if (MathAbs(eX - m_DragInfomouseDownX) + MathAbs(eY - m_DragInfomouseDownY) lt= DRAGTOL) return フラグを更新します m_DragInfodragging = true Sets cursor and highlight node CellStyle cs = flexStyles[SourceNode] flexCursor = CursorsNoMove2D flexSetCellStyle(m_DragInforow 0 cs) ここにドロップできるかどうかを確認します Cursor c = (NoDropHere()) CursorsNo CursorsNoMove2D if (c = flexCursor) flexCursor = c private bool NoDropHere() カーソルの下の行は無効です if (flexMouseRow lt flexRowsFixed) return true カーソルの下の列が無効です if (flexMouseCol lt flexColsFixed) return true if (flexGetDataDisplay(flexRow 0) == SKU) return true return false private void flex_MouseUp(object sender MouseEventArgs e) マウスが再び下がるまでチェックしないでください m_DragInfocheckDrag = false Not dragging were done if (m_DragInfodragging) return ドラッグを停止します m_DragInfodragging = false flexSetCellStyle(m_DragInforow 0 (CellStyle)null) flexCursor = CursorsDefault ドロップが許可されているかどうかをテストします

C

FlexGrid for WinForms

177 Copyright copy GrapeCity Inc All rights reserved

if (NoDropHere()) return ノードを新しい親ノードに移動します Node ndSrc = flexRows[m_DragInforow]Node Node ndDst = flexRows[flexRow]Node ndSrcMove(NodeMoveEnumChildOf ndDst) ndSrcSelect()

internal struct DRAGINFO public bool dragging 現在ドラッグ中 public bool checkDrag 現在マウスをチェックしてドラッグを開始しています public int row ドラッグされている行のインデックス public Point mouseDown マウスダウンの位置

Private Sub flex_MouseDown(ByVal sender As Object ByVal e As MouseEventArgs) m_DragInfocheckDrag = False 左ボタンを押すと移動しません ドラッグするマウスの追跡を開始します If eButton IsNot MouseButtonsLeft Then Return If Not chkDragChecked OrElse m_DragInfodragging Then Return If flexMouseRow lt flexRowsFixed OrElse flexMouseCol ltgt 0 Then Return 現在の行とマウスの位置を保存します m_DragInforow = flexRow m_DragInfomouseDown = New Point(eX eY) チェックを開始します m_DragInfocheckDrag = True End Sub

Private Sub flex_MouseMove(ByVal sender As Object ByVal e As MouseEventArgs) チェックしてユーザーが許容範囲を超えた場合はドラッグを開始します If Not m_DragInfocheckDrag OrElse eButton IsNot MouseButtonsLeft Then Return If MathAbs(eX - m_DragInfomouseDownX) + MathAbs(eY - m_DragInfomouseDownY) lt= DRAGTOL Then Return フラグを更新します m_DragInfodragging = True カーソルを設定しノードを強調表示します Dim cs As CellStyle = flexStyles(SourceNode) flexCursor = CursorsNoMove2D flexSetCellStyle(m_DragInforow 0 cs) ここにドロップできるかどうかを確認します Dim c As Cursor = If((NoDropHere()) CursorsNo CursorsNoMove2D) If c IsNot flexCursor Then flexCursor = c End Sub

Private Function NoDropHere() As Boolean カーソルの下の行は無効です If flexMouseRow lt flexRowsFixed Then Return True カーソルの下の列が無効です If flexMouseCol lt flexColsFixed Then Return True If flexGetDataDisplay(flexRow 0) Is SKU Then Return True Return False End Function

Private Sub flex_MouseUp(ByVal sender As Object ByVal e As MouseEventArgs) マウスが再び下がるまでチェックしないでください m_DragInfocheckDrag = False If Not m_DragInfodragging Then Return ドラッグを停止します m_DragInfodragging = False

VBNET

FlexGrid for WinForms

178 Copyright copy GrapeCity Inc All rights reserved

flexSetCellStyle(m_DragInforow 0 CType(Nothing CellStyle)) flexCursor = Cursors[Default] ドロップが許可されているかどうかをテストします If NoDropHere() Then Return ノードを新しい親ノードに移動します Dim ndSrc As Node = flexRows(m_DragInforow)Node Dim ndDst As Node = flexRows(flexRow)Node ndSrcMove(NodeMoveEnumChildOf ndDst) ndSrc[Select]() End Sub

Friend Structure DRAGINFO Public dragging As Boolean 現在ドラッグ中 Public checkDrag As Boolean 現在マウスをチェックしてドラッグを開始しています Public row As Integer ドラッグされている行のインデックス Public mouseDown As Point マウスダウンの位置 End Structure

データの操作

In Tree Grid just like a usual grid you can also perform various operations at data level such as sorting and retainingthe changes

SortingTo apply sorting in Tree Grid you can select the parent node and sort the child nodes using Sort Method of the NodeClass You can specify the sorting order by using the SortFlags enumeration

Following code applies sorting on the WinForms Tree Grid

FlexGrid for WinForms

179 Copyright copy GrapeCity Inc All rights reserved

Retain the ChangesSo far we have discussed how to create trees and totals using the high-level Subtotal method as well as lower-level InsertNode and Aggregate methods

At this point it is important to remember that the Tree Grid is created based on the data but is not bound to it in anyway and is not automatically maintained when there are changes to the grid or to the data

For example if the user modifies a value in the column the subtotals will not be automatically updated If the usersorts the grid it refreshes the data and the subtotals disappear

There are two common ways to maintain the Tree Grid

1 Prevent the user from making any changes that would invalidate the tree This is the easiest option You can setthe grids AllowEditing AllowDragging and AllowSorting properties to false and prevent any changes thatwould affect the tree

2 Update the tree when there are changes to the data or to the grid You can attach handlers to thegrids AfterDataRefresh AfterSort and AfterEdit events and re-generate the outline appropriately

The second option is usually more interesting as it provides a quick and simple tool for dynamic data analysis Thisapproach is illustrated by a product sample Analyze shipped with the FlexGrid control The sample creates an initialoutline and allows users to reorder the columns When the column order changes the sample automatically re-sortsthe data and re-creates the outline

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing

private void btnSort_Click(object sender SystemEventArgs e) 現在のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択した並べ替えを適用します (これにより選択したノードの子が並べ替えられます) if (sender == btnSortAscending) ndSort(SortFlagsAscending) else ndSort(SortFlagsDescending) 完了 flexFocus()

C

Private Sub btnSort_Click(ByVal sender As Object ByVal e As EventArgs) 現在のノードを取得します Dim nd As Node = flexRows(flexRow)Node

ユーザーが選択した並べ替えを適用します (これにより選択したノードの子が並べ替えられます) If sender Is btnSortAscending Then ndSort(SortFlagsAscending) Else ndSort(SortFlagsDescending) End If

完了 flexFocus()End Sub

VBNET

FlexGrid for WinForms

180 Copyright copy GrapeCity Inc All rights reserved

WinForms Edition using ComponentOneControlPanelexe

In Create Nodes section we also learnt about implementing GroupBy method that inserts node rows groupingidentical values on a given column The code scans all the columns skipping existing node rows so it can be called toadd several levels of nodes and keeps track of the current value for the column being grouped on When the currentvalue changes a node row is inserted showing the new group name in the first scrollable column

However there are some challenges to maintain the grouping like the method assumes that data is sorted accordingto the outline structure Also the GroupBy method may insert rows which would cause the grid to flicker To avoidthis you would normally set the Redraw property to false before making the updates and set it back to true whendone

The DeferRefresh class is a simple utility that sets the grids Redraw property to false and restores its original valuewhen it is disposed This ensures that Redraw is properly restored even when exceptions happen during the updatesThe BindGrid method ensures that the grid is sorted in the order required by our outline structure

ツリーグリッドのカスタマイズ

FlexGrid allows you to customize Tree Grid by styling as well as by using various elements like checkboxes toexpandcollapse nodes or images as node icons A customized Tree Grid can make the outline tree nodes look moredistinctive and structured making it visually appealing and more understandable

Style Tree GridStyling a Tree Grid is similar to styling the FlexGrid control The Tree property returns a reference to a GridTree objectthat exposes several methods and properties used to customize the Tree Grid Following is the list of some commonlyused properties

Column Gets or sets the index of the column that contains the outline tree Setting this property to -1 causesthe outline tree to be hidden from the usersIndent Gets or sets the indent in pixels between adjacent node levels Higher indent levels cause the tree tobecome widerStyle Gets or sets the type of outline tree to display Use this property to determine whether the tree shouldinclude a button bar at the top to allow users to collapseexpand the entire tree whether lines andor symbolsshould be displayed and whether lines should be displayed connecting the tree to data rows as well as noderowsLineColor Gets or sets the color of the connecting linesLineStyle Gets or sets the style of the connecting lines

For more information on styling the tree grid see Styling and Appearance topic in FlexGrid documentation

Display Tree with CheckBoxesTo create a custom Tree Grid with checkbox and images you need to first initialize FlexGrid for creating Tree Grid andthen add nodes to the tree by using AddNode method of the RowCollection class

Now to implement checkboxes in Tree Grid you need to maintain the checkboxes in parent and child nodes Thismethod uses Checked property of the Node class which defines whether to show a checkbox for the node or not

FlexGrid for WinForms

181 Copyright copy GrapeCity Inc All rights reserved

The code below shows how to display checkboxes on tree nodes of the WinForms Tree Grid

void c1FlexGrid1_CellChecked(object sender C1WinC1FlexGridRowColEventArgs e) すべての子にチェック値を適用します var node = thisc1FlexGrid1Rows[eRow]Node UpdateCheckChildren(node) 親にチェック値を適用します UpdateCheckParent(node)

void UpdateCheckChildren(C1WinC1FlexGridNode node) var checkState = nodeChecked foreach (C1WinC1FlexGridNode child in nodeNodes) childChecked = checkState UpdateCheckChildren(child)

void UpdateCheckParent(C1WinC1FlexGridNode node) このノードの親を取得します var parent = nodeParent if (parent = null)

C

FlexGrid for WinForms

182 Copyright copy GrapeCity Inc All rights reserved

チェックされたチェックされていない子をカウントします int cntChecked = 0 int cntUnchecked = 0 int cntGrayed = 0 foreach (C1WinC1FlexGridNode child in parentNodes) switch (childChecked) case C1WinC1FlexGridCheckEnumChecked cntChecked++ break case C1WinC1FlexGridCheckEnumUnchecked cntUnchecked++ break case C1WinC1FlexGridCheckEnumGrayed cntGrayed++ break 親のチェック状態を更新します if (cntGrayed gt 0 || (cntChecked gt 0 ampamp cntUnchecked gt 0)) parentChecked = C1WinC1FlexGridCheckEnumGrayed else if (cntChecked gt 0 ampamp cntUnchecked == 0) parentChecked = C1WinC1FlexGridCheckEnumChecked else if (cntUnchecked gt 0 ampamp cntChecked == 0) parentChecked = C1WinC1FlexGridCheckEnumUnchecked 祖父も更新します UpdateCheckParent(parent)

Private Sub c1FlexGrid1_CellChecked(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) すべての子にチェック値を適用します Dim node = Mec1FlexGrid1Rows(eRow)Node UpdateCheckChildren(node) 親にチェック値を適用します UpdateCheckParent(node) End Sub

Private Sub UpdateCheckChildren(ByVal node As C1WinC1FlexGridNode) Dim checkState = nodeChecked

For Each child As C1WinC1FlexGridNode In nodeNodes childChecked = checkState MeUpdateCheckChildren(child) Next End Sub

Private Sub UpdateCheckParent(ByVal node As C1WinC1FlexGridNode) このノードの親を取得します Dim parent = nodeParent

If parent IsNot Nothing Then チェックされたチェックされていない子をカウントします

VBNET

FlexGrid for WinForms

183 Copyright copy GrapeCity Inc All rights reserved

Display Tree with ImagesTo add the images as your Tree Grid node icons you can use the AddImageFolder method for creating nodes relatedto files and assigning images to the nodes

Dim cntChecked As Integer = 0 Dim cntUnchecked As Integer = 0 Dim cntGrayed As Integer = 0

For Each child As C1WinC1FlexGridNode In parentNodes

Select Case childChecked Case C1WinC1FlexGridCheckEnumChecked cntChecked += 1 Case C1WinC1FlexGridCheckEnumUnchecked cntUnchecked += 1 Case C1WinC1FlexGridCheckEnumGrayed cntGrayed += 1 End Select Next

親のチェック状態を更新します If cntGrayed gt 0 OrElse cntChecked gt 0 AndAlso cntUnchecked gt 0 Then parentChecked = C1WinC1FlexGridCheckEnumGrayed ElseIf cntChecked gt 0 AndAlso cntUnchecked = 0 Then parentChecked = C1WinC1FlexGridCheckEnumChecked ElseIf cntUnchecked gt 0 AndAlso cntChecked = 0 Then parentChecked = C1WinC1FlexGridCheckEnumUnchecked End If

祖父も更新します UpdateCheckParent(parent) End If End Sub

FlexGrid for WinForms

184 Copyright copy GrapeCity Inc All rights reserved

Use the code below to display images or icons along with nodes of the WinForms Tree Grid

void AddImageFolder(string path int level) int cnt = 0 try ディレクトリ内のすべてのファイルをループします foreach (string file in DirectoryGetFiles(path)) ファイルごとにノードを作成しFlexGridに追加します var node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(file) 画像をノードに割り当てるためのコード ShowImage(node file) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt++ if (cnt gt 20) break catch try パスのすべてのサブディレクトリをループします foreach (string subPath in DirectoryGetDirectories(path))

C

FlexGrid for WinForms

185 Copyright copy GrapeCity Inc All rights reserved

ファイルごとにノードを作成しFlexGridに追加します var node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(subPath) 画像をノードに割り当てるためのコード ShowImage(node subPath) 現在のディレクトリのサブディレクトリファイルをトラバースします AddImageFolder(subPath level + 1) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt++ if (cnt gt 20) break catch

Private Sub AddImageFolder(ByVal path As String ByVal level As Integer) Dim cnt As Integer = 0

Try

ディレクトリ内のすべてのファイルをループします For Each file As String In DirectoryGetFiles(path) ファイルごとにノードを作成しFlexGridに追加します Dim node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(file)

画像をノードに割り当てるためのコード ShowImage(node file) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt += 1 If cnt gt 20 Then Exit For Next

Catch End Try

Try

パスのすべてのサブディレクトリをループします For Each subPath As String In DirectoryGetDirectories(path) ファイルごとにノードを作成しFlexGridに追加します Dim node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(subPath) 画像をノードに割り当てるためのコード ShowImage(node subPath) 現在のディレクトリのサブディレクトリファイルをトラバースします AddImageFolder(subPath level + 1) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt += 1 If cnt gt 20 Then Exit For Next

Catch End TryEnd Sub

VBNET

FlexGrid for WinForms

186 Copyright copy GrapeCity Inc All rights reserved

The above code uses a custom method called ShowImage to set the image for nodes based on its file extensions

public void ShowImage(C1WinC1FlexGridNode node string path) パスからファイル拡張子を取得します string extension = PathGetExtension(path) パスがファイルに属している場合 if (extension = ) ファイル拡張子に基づいてノードの画像を設定します switch (extension) case txt nodeImage = PropertiesResourcesTxt break case resx nodeImage = PropertiesResourcesTxt break case licx nodeImage = PropertiesResourcesTxt break case cs nodeImage = PropertiesResourcesTxt break case vb nodeImage = PropertiesResourcesTxt break case exe nodeImage = PropertiesResourcesExe break case dll nodeImage = PropertiesResourcesDll break case sln nodeImage = PropertiesResourcesVS break case csproj nodeImage = PropertiesResourcesVS break case bmp nodeImage = PropertiesResourcesImg break case png nodeImage = PropertiesResourcesImg break case gif nodeImage = PropertiesResourcesVideo break case accdb nodeImage = PropertiesResourcesAccess break default nodeImage = PropertiesResourcesUnknown break それ以外のパスはディレクトリフォルダに属しています else nodeImage = PropertiesResourcesFolder

C

FlexGrid for WinForms

187 Copyright copy GrapeCity Inc All rights reserved

Public Sub ShowImage(ByVal node As C1WinC1FlexGridNode ByVal path As String) パスからファイル拡張子を取得します Dim extension As String = PathGetExtension(path)

パスがファイルに属している場合 If Not Equals(extension ) Then

ファイル拡張子に基づいてノードの画像を設定します Select Case extension Case txt nodeImage = PropertiesResourcesTxt Case resx nodeImage = PropertiesResourcesTxt Case licx nodeImage = PropertiesResourcesTxt Case cs nodeImage = PropertiesResourcesTxt Case vb nodeImage = PropertiesResourcesTxt Case exe nodeImage = PropertiesResourcesExe Case dll nodeImage = PropertiesResourcesDll Case sln nodeImage = PropertiesResourcesVS Case csproj nodeImage = PropertiesResourcesVS Case bmp nodeImage = PropertiesResourcesImg Case png nodeImage = PropertiesResourcesImg Case gif nodeImage = PropertiesResourcesVideo Case accdb nodeImage = PropertiesResourcesAccess Case Else nodeImage = PropertiesResourcesUnknown それ以外のパスはディレクトリフォルダに属しています End Select Else nodeImage = PropertiesResourcesFolder End IfEnd Sub

VBNET

FlexGrid for WinForms

188 Copyright copy GrapeCity Inc All rights reserved

クリップボード

FlexGrid provides flexibility to perform various clipboard operations such as cut copy and paste on the editable griddata To enable automatic handling of common clipboard keys you need to set the AutoClipboard property to trueThe property handles following clipboard operations and their corresponding keys

Copy CTRL+C Ctrl+INS

Cut CTRL+X SHIFT+DEL

Paste CTRL+V SHIFT+INS

Delete DEL

The abovementioned clipboard operations do not have any affect on the styles and images and only work on gridheaders and data You can choose which part of the selected content to copy out of row header column headerand data by using the ClipboardCopyMode property When a datamap or multicolumn combobox exists in thecopied range only the display value is copied Also note that hidden cells are also copied when copying a cellrange To exclude hidden cells from copying see Exclude Hidden Cells

The code below demonstrates how to enable clipboard operations in the WinForms FlexGrid

Clipboard Operations through CodeYou can also perform clipboard operations through code The example below shows how to perform copying andpasting operations on button click

Use the code below to perform the clipboard operations through code in the WinForms FlexGrid

キーボードからクリップボード操作を有効にします c1FlexGrid1AutoClipboard = true データとすべてのヘッダーをコピーするようにコピーモードを設定します c1FlexGrid1ClipboardCopyMode = C1WinC1FlexGridClipboardCopyModeEnumDataAndAllHeaders

C

キーボードからクリップボード操作を有効にしますc1FlexGrid1AutoClipboard = True

データとすべてのヘッダーをコピーするようにコピーモードを設定しますc1FlexGrid1ClipboardCopyMode = C1WinC1FlexGridClipboardCopyModeEnumDataAndAllHeaders

VBNET

private void CopyButton_Click(object sender EventArgs e) クリップボードにコピーするグリッドのデータのみをコピーできるようにします c1FlexGrid1ClipboardCopyMode = ClipboardCopyModeEnumDataOnly

Clipプロパティに改行コードを追加しクリップボードに設定します ClipboardSetDataObject(c1FlexGrid1Clip + r) MessageBoxShow($Copied Range [c1FlexGrid1Rowc1FlexGrid1Col]-[c1FlexGrid1RowSelc1FlexGrid1ColSel])

C

FlexGrid for WinForms

189 Copyright copy GrapeCity Inc All rights reserved

Exclude Hidden CellsIn FlexGrid by default hidden cells are also copied when copying a cell range through keyboard operations enabledusing the AutoClipboard property However you can exclude the hidden rows and columns by using the code below

Following code shows how you can exclude the hidden cells from clipboard operations performed on the WinFormsTree Grid

private void PasteButton_Click(object sender EventArgs e) クリップボードのテキストを取得します IDataObject data = ClipboardGetDataObject() if (dataGetDataPresent(DataFormatsText)) string str1 str2 クリップボードからデータを取得します str1 = (string)dataGetData(DataFormatsText)

クリップボードから最後の行のフィードコードを削除します str2 = str1Remove(str1Length - 1 1)

範囲を選択してデータを貼り付けます c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col c1FlexGrid1RowsCount - 1 c1FlexGrid1ColsCount - 1 true) c1FlexGrid1Clip = str2 c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col)

Private Sub CopyButton_Click(ByVal sender As Object ByVal e As EventArgs) クリップボードにコピーするグリッドのデータのみをコピーできるようにします c1FlexGrid1ClipboardCopyMode = ClipboardCopyModeEnumDataOnly

Clipプロパティに改行コードを追加しクリップボードに設定します ClipboardSetDataObject(c1FlexGrid1Clip amp MicrosoftVisualBasicConstantsvbCr) MessageBoxShow($Copied Range [c1FlexGrid1Rowc1FlexGrid1Col]-[c1FlexGrid1RowSelc1FlexGrid1ColSel])End Sub

Private Sub PasteButton_Click(ByVal sender As Object ByVal e As EventArgs) クリップボードのテキストを取得します Dim data As IDataObject = ClipboardGetDataObject()

If dataGetDataPresent(DataFormatsText) Then Dim str1 str2 As String クリップボードからデータを取得します str1 = CStr(dataGetData(DataFormatsText))

クリップボードから最後の行のフィードコードを削除します str2 = str1Remove(str1Length - 1 1)

範囲を選択してデータを貼り付けます c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col c1FlexGrid1RowsCount - 1 c1FlexGrid1ColsCount - 1 True) c1FlexGrid1Clip = str2 c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col) End If

VBNET

C

FlexGrid for WinForms

190 Copyright copy GrapeCity Inc All rights reserved

列を非表示にしますc1FlexGrid1Cols[2]Visible = falsec1FlexGrid1AutoClipboard = true

次にCtrl + Cを押す前に非表示の列を含むいくつかのセルを選択しますprivate void c1FlexGrid1_KeyDown_1(object sender KeyEventArgs e) [Ctrl + C]でコピーします if ((eControl == true) ampamp (eKeyCode == KeysC)) 自動処理が行われないためキー入力を無効にします eHandled = true 選択したセル範囲のCellRangeオブジェクトを取得します C1WinC1FlexGridCellRange cr cr = c1FlexGrid1Selection

string StrCopy = for (int i = crr1 i lt= crr2 i++) if (c1FlexGrid1Rows[i]Visible == true) for (int j = crc1 j lt= crc2 j++) if (c1FlexGrid1Cols[j]Visible == true) StrCopy = StrCopy + c1FlexGrid1[i j]ToString() if (j = crc2) StrCopy = StrCopy + t StrCopy = StrCopy + n クリップボードに設定します ClipboardSetDataObject(StrCopy) MessageBoxShow(Copied data n + StrCopy)

列を非表示にします c1FlexGrid1Cols(2)Visible = False c1FlexGrid1AutoClipboard = True

次にCtrl + Cを押す前に非表示の列を含むいくつかのセルを選択しますPrivate Sub c1FlexGrid1_KeyDown_1(ByVal sender As Object ByVal e As KeyEventArgs)

[Ctrl + C]でコピーします If eControl = True AndAlso eKeyCode = KeysC Then 自動処理が行われないためキー入力を無効にします eHandled = True 選択したセル範囲のCellRangeオブジェクトを取得します Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1Selection Dim StrCopy =

VBNET

FlexGrid for WinForms

191 Copyright copy GrapeCity Inc All rights reserved

For i = crr1 To crr2

If c1FlexGrid1Rows(i)Visible = True Then For j = crc1 To crc2

If c1FlexGrid1Cols(j)Visible = True Then StrCopy = StrCopy amp c1FlexGrid1(i j)ToString()

If j ltgt crc2 Then StrCopy = StrCopy amp MicrosoftVisualBasicConstantsvbTab End If End If Next

StrCopy = StrCopy amp MicrosoftVisualBasicConstantsvbLf End If Next クリップボードに設定します ClipboardSetDataObject(StrCopy) MessageBoxShow(Copied data amp MicrosoftVisualBasicConstantsvbLf amp StrCopy) End IfEnd Sub

FlexGrid for WinForms

192 Copyright copy GrapeCity Inc All rights reserved

保存ロードと印刷

FlexGrid provides various built-in options so that you can easily save a grid and its content in a text excel or an XML file You can even load these saved filesto another grid or can save it as backup of a particular state of the grid You can also save the grid image in your desired format Not just this you can alsoprint the grid or selected areas of the grid if you need to have a hard copy This topic discusses various options related save load and print available in thegrid

Topic Content

Save Discusses about how to save the grid and its contents in different formats

Save as Text FileSave as Excel FileSave as XMLSave as Image

Load Discusses about how to load grid content from various file formats

Load from Text FileLoad from Excel FileLoad from DatabaseLoad from XML

Print Discusses about how to print the grid and other print related options

Print GridPrint OptionsCustomize Print Preview Dialog

保存

FlexGrid provides various methods to save the grid in the desired format such as text excel xml and image formatsThis feature is enabled through an assembly named C1WinC1FlexGridImportExportdll hence you need to addreference to this assembly to save the grid

Save as Text FileTo save grid content as a text file you can use the SaveGrid method of the Extensions class The method hasparameters that let you choose delimiter encoding and also lets you specify which portion of grid should be savedThe resulting text files can later be loaded back into the control or into other applications that support comma or tab-delimited files such as Microsoft Excel

Following code shows how to save content of the WinForms FlexGrid as a text file

private void btnSaveTxt_Click(object sender EventArgs e) c1FlexGrid1SaveGrid(ExportedGridtxt FileFormatEnumTextComma FileFlagsAsDisplayed | FileFlagsIncludeFixedCells)

C

Private Sub btnSaveTxt_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1SaveGrid(ExportedGridtxt FileFormatEnumTextComma FileFlagsAsDisplayed Or FileFlagsIncludeFixedCells)End Sub

VBNET

FlexGrid for WinForms

193 Copyright copy GrapeCity Inc All rights reserved

Save as Excel FileTo save grid as an excel file you can use the abovementioned SaveGrid method and simply set the format parameterto FileFormatEnumExcel You dont need to have Microsoft Excel installed on your computer However SaveGridmethod can only save the data in a workbook with single worksheet

To get an additional control over how you save your data to an excel file you can use the SaveExcel method insteadIn this case the process of saving excel files converts most data types and formatting information including row andcolumn dimensions fonts colors formats and cell alignment However some other features such as frozen andmerged cells images data maps and cell borders are not translated while converting to an excel file

Use the code below to save the WinForms FlexGrid as an Excel file

Save as XMLTo serialize grid contents into an XML document you can simply call WriteXML method of the C1FlexGrid class andparse path of the XML document as a parameter The method serializes all grid contents into the Xml documentincluding the data stored in the cells row and column properties styles and images Objects of custom types storedin the grid are also serialized as long as they have an associated SystemComponentModelTypeConverter thatprovides conversions to and from string

Below code demonstrates how to save contents of the WinForms FlexGrid to an XML document

Save as ImageTo save a grid as an image you can create the grid image using CreateImage method of the C1FlexGrid class andsave that image object at the specified path You can also specify a cell range or pass a cell range object as itsparameter to save a specific portion of the grid as an image

Use the code below to save the WinForms FlexGrid as an image

private void btnSaveExcl_Click(object sender EventArgs e) c1FlexGrid1SaveExcel(ExportedGridxlsx FileFlagsAsDisplayed | FileFlagsIncludeFixedCells)

C

Private Sub btnSaveExcl_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1SaveExcel(ExportedGridxlsx FileFlagsAsDisplayed Or FileFlagsIncludeFixedCells)End Sub

VBNET

private void btnSaveXML_Click(object sender EventArgs e) c1FlexGrid1WriteXml(ExportedGridxml)

C

Private Sub btnSaveXML_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1WriteXml(ExportedGridxml)End Sub

VBNET

FlexGrid for WinForms

194 Copyright copy GrapeCity Inc All rights reserved

private void btnSaveImg_Click(object sender EventArgs e) Image gridImage = c1FlexGrid1CreateImage() gridImageSave(ExportedGridpng)

C

Private Sub btnSaveImg_Click(ByVal sender As Object ByVal e As EventArgs) Dim gridImaage As Image = c1FlexGrid1CreateImage() gridImaageSave(ExportedGridpng)End Sub

VBNET

ロード

FlexGrid not only lets you save the grid to various formats but also lets you load data from various formats such textexcel XML or databases This feature is enabled through an assembly named C1WinC1FlexGridImportExportdllhence you need to add reference to this assembly to load the grid with data from these sources

Load from Text FileTo load data from a text file FlexGrid provides LoadGrid method of the Extensions class The method has parametersthat let you choose delimiter encoding etc You can also load text files saved using SaveGrid method When loadingtext files rows and columns are added to the grid if needed to accommodate the file contents The method supportsformats such as comma-delimited text files (CSV format) tab-delimited text files and even MS Excel files (xls)

Following code shows how to populate data in the WinForms FlexGrid by loading it from a text file

Load from Excel FileTo load grid from an excel file you can use the abovementioned LoadGrid method and simply set the formatparameter to FileFormatEnumExcel You dont need to have Microsoft Excel installed on your computer However theLoadGrid method can only load the data from first worksheet of a workbook

To get an additional control over how you load your data from an excel file you can use the LoadExcel methodinstead In this case the process of loading excel files converts most data types and formatting information includingrow and column dimensions fonts colors formats and cell alignment However there are still some exceptions Forexample the grid loads the values in excel cells but cannot load the underlying formulas Other features such asfrozen and merged cells images data maps and cell borders are not translated either

Use the code below to load contents in the WinForms FlexGrid from an excel file

private void btnLoadTxt_Click(object sender EventArgs e) c1FlexGrid1LoadGrid(ExportedGridtxt FileFormatEnumTextComma )

C

Private Sub btnLoadTxt_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1LoadGrid(ExportedGridtxt FileFormatEnumTextComma)End Sub

VBNET

FlexGrid for WinForms

195 Copyright copy GrapeCity Inc All rights reserved

Load from DatabaseTo load grid data from a database you can use the DataReader objects This process is different from data bindingwhich keeps a live connection between one or more controls and the underlying data source

Below code demonstrates how to load contents in the WinForms FlexGrid from the database

private void btnLoadExcl_Click(object sender EventArgs e) c1FlexGrid1LoadExcel(ExportedGridxlsx)

C

Private Sub btnLoadExcl_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1LoadExcel(ExportedGridxlsx)End Sub

VBNET

private void btnLoadDB_Click(object sender EventArgs e) DataReaderを準備します string strConn = data source=MYMACHINEinitial catalog=Northwind SystemDataSqlClientSqlConnection myConn = new SystemDataSqlClientSqlConnection(strConn) SystemDataSqlClientSqlCommand myCMD = new SystemDataSqlClientSqlCommand(SELECT FROM Employees myConn) myConnOpen() SystemDataSqlClientSqlDataReader myReader = myCMDExecuteReader()

DBスキーマからグリッド構造を構築します DataTable dt = myReaderGetSchemaTable() c1FlexGrid1ColsCount = 1 foreach (DataRow dr in dtRows) Column c =c1FlexGrid1ColsAdd() cCaption = cName = (string)dr[ColumnName] cDataType = (Type)dr[DataType]

グリッドにデータを入力します c1FlexGrid1RowsCount = 1 int row = 1 int cols = dtColumnsCount object[] v = (object[])ArrayCreateInstance(typeof(object) cols) while (myReaderRead()) myReaderGetValues(v) c1FlexGrid1AddItem(v row++ 1)

クリーンアップします c1FlexGrid1AutoSizeCols() myReaderClose() myConnClose()

C

FlexGrid for WinForms

196 Copyright copy GrapeCity Inc All rights reserved

Load from XMLTo deserialize grid contents from an XML document you can simply call ReadXML method of the C1FlexGrid classand parse path of the XML document as a parameter

Use the code below to load contents for the WinForms FlexGrid from an XML document

Private Sub btnLoadDB_Click(ByVal sender As Object ByVal e As EventArgs) DataReaderを準備します Dim strConn As String = data source=MYMACHINEinitial catalog=Northwind Dim myConn As New SqlClientSqlConnection(strConn) Dim myCMD As New SqlClientSqlCommand(SELECT FROM Employees myConn) myConnOpen() Dim myReader As SqlClientSqlDataReader = myCMDExecuteReader() DBスキーマからグリッド構造を構築します Dim dt As DataTable = myReaderGetSchemaTable() _flexColsCount = 1 Dim dr As DataRow For Each dr In dtRows Dim c As C1WinC1FlexGridColumn = _flexColsAdd() cCaption =(cName lt= CStr(dr(ColumnName))) cDataType = CType(dr(DataType) Type) Next dr グリッドにデータを入力します _flexRowsCount = 1 Dim row As Integer = 1 Dim cols As Integer = dtColumnsCount Dim v As Object() = CType(ArrayCreateInstance(GetType(Object) cols) Object()) While myReaderRead() myReaderGetValues(v) _flexAddItem(v row + 1 1) End While クリーンアップします _flexAutoSizeCols() myReaderClose() myConnClose()End Sub

VBNET

private void btnLoadXML_Click(object sender EventArgs e) c1FlexGrid1ReadXml(ExportedGridxml)

C

Private Sub btnLoadXML_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1ReadXml(ExportedGridxml)End Sub

VBNET

FlexGrid for WinForms

197 Copyright copy GrapeCity Inc All rights reserved

印刷

FlexGrid lets you print the grid and perform various basic and advanced print settings using its built-in methods andproperties

Print GridFlexGrid provides PrintGrid method of the C1FlexGrid class which lets you print the grid contents with some basicprinting options The method has an optional parameter PrintGridFlags that allows you to specify how to print thegrid such as its scaling mode and whether to display various print related dialog boxes You can also set text in headerand footer of the printed grid using this method

Following code shows how to use PrintGrid method to print the WinForms FlexGrid

Print OptionsTo set advanced printing options such as header and footer fonts page margins and page orientation you can usePrintParameter property of the C1FlexGrid class

Use the code below to print the WinForms FlexGrid with advanced print options

プレビューダイアログを表示し指定したヘッダとフッターでグリッドを印刷しますc1FlexGrid1PrintGrid(C1FlexGrid PrintGridFlagsFitToPageWidth | PrintGridFlagsShowPreviewDialog C1FlexGridtt + StringFormat(DateTimeNowToString() d) ttPage 0 of 1)

C

プレビューダイアログを表示し指定したヘッダとフッターでグリッドを印刷しますc1FlexGrid1PrintGrid(C1FlexGrid PrintGridFlagsFitToPageWidth Or PrintGridFlagsShowPreviewDialog C1FlexGrid amp vbTab amp vbTab amp StringFormat(DateNowToString() d) vbTab amp vbTab amp Page 0 of 1)

VBNET

FlexGrid for WinForms

198 Copyright copy GrapeCity Inc All rights reserved

Customize Print Preview DialogYou can customize the print preview dialog by using PrintPreviewDialog property of the GridPrinter class Theproperty can be accessed through PrintParameter property of the C1FlexGrid class The code below uses thePrintPreviewDialog property to display a maximized preview dialog with a custom caption

Below code demonstrates how to customize the print preview dialog of the WinForms FlexGrid

グリッドのPrintDocumentオブジェクトを取得しますSystemDrawingPrintingPrintDocument pd = c1FlexGrid1PrintParametersPrintDocument

ページを設定します(横向き15 左マージン)pdDefaultPageSettingsLandscape = truepdDefaultPageSettingsMarginsLeft = 150

ヘッダとフッタのフォントを設定しますc1FlexGrid1PrintParametersHeaderFont = new Font(Arial Black 14 FontStyleBold)c1FlexGrid1PrintParametersFooterFont = new Font(Arial Narrow 8 FontStyleItalic)

C

グリッドのPrintDocumentオブジェクトを取得しますDim pd As DrawingPrintingPrintDocument = c1FlexGrid1PrintParametersPrintDocument

ページを設定します(横向き15 左マージン)pdDefaultPageSettingsLandscape = TruepdDefaultPageSettingsMarginsLeft = 150

ヘッダとフッタのフォントを設定しますc1FlexGrid1PrintParametersHeaderFont = New Font(Arial Black 14 FontStyleBold)c1FlexGrid1PrintParametersFooterFont = New Font(Arial Narrow 8 FontStyleItalic)

VBNET

Form dlg = c1FlexGrid1PrintParametersPrintPreviewDialog as Form dlgText = Order Details dlgStartPosition = FormStartPositionCenterParent dlgWindowState = FormWindowStateMaximized c1FlexGrid1PrintGrid(Orders PrintGridFlagsShowPreviewDialog)

C

Dim dlg As Form = TryCast(c1FlexGrid1PrintParametersPrintPreviewDialog Form) dlgText = Order Details dlgStartPosition = FormStartPositionCenterParent dlgWindowState = FormWindowStateMaximized c1FlexGrid1PrintGrid(Orders PrintGridFlagsShowPreviewDialog)

VBNET

FlexGrid for WinForms

199 Copyright copy GrapeCity Inc All rights reserved

外観とスタイル設定

FlexGrid provides built-in visual styles as well as various design time and run time options so that you can style the grid and its elements as per the needsand appearance of your application The grid also provides style editors to let you customize appearance of your grid without writing a single line of codeFor more information about these editors and design time styling see Editors

This section discusses the built-in options provided by FlexGrid as well as various other ways to customize the appearance of grid and its elements

Topic Snapshot Content

Built-in Options Discusses about the available visual styles and built-in collection of styles

Visual StylesStyles Collection

Custom Styles Discusses how to create and apply the custom styles

Approach 1 Style an ObjectApproach 2 Create Re-usable Style

Customize Grid Discusses about customization at grid level

Set Alternate RowSet Background Image

Customize Border Discusses about customization of cell borders at row column or grid level

Customize Grid BorderCustomize RowColumn BorderCustomize Cell Border

Customize Text Discusses about various aspects of styling the grid text

Change FontSet MarginSet Vertical TextWrap TextDisplay Trimmed TextAlign TextApply Text Effect

Custom Glyphs Discusses about applying custom glyphs in the grid

組み込みオプション

Visual StylesFlexGrid provides six built-in visual styles so that you can easily customize the appearance of FlexGrid based on any ofthe Microsoft Office 2007 and 2010 themes These visual styles can be accessed through VisualStyle property ofthe C1FlexGrid class Apart from MS Office based visual styles you can also set this property to Custom and SystemWhen set to Custom the grid does not apply any visual styles and uses the grid properties for rendering When theproperty is set to System the grid renders its appearance based on current system settings

FlexGrid for WinForms

200 Copyright copy GrapeCity Inc All rights reserved

The property can be set using designer as well as through code To set the property at design time click smart tag toopen the C1FlexGrid Tasks menu and select a visual style from the VisualStyle combobox To apply visual style in theWinForms FlexGrid through code use the code below

Styles CollectionFlexGrid provides built-in collection of styles for predefined cell types and states such as normal cells fixed cellsfocused cells and so on You can use these built-in styles at design time as well as through code In design view youcan access these styles through the C1FlexGrid Style Editor which can be opened by clicking Styles option in Tasksmenu This collection of styles is represented by the CellStyleCollection class which can be accessed through Stylesproperty of the C1FlexGrid class Each built-in style is an object of the CellStyle class and holds various propertiessuch as BackColor DataType and Format

Following code shows how to use the styles from Styles collection of the WinForms FlexGrid

視覚スタイルをOffice2010Blueスキームに設定しますc1FlexGrid1VisualStyle = VisualStyleOffice2010Blue

C

視覚スタイルをOffice2010Blueスキームに設定しますc1FlexGrid1VisualStyle = VisualStyleOffice2010Blue

VBNET

組み込みセルスタイルNormalのプロパティを設定しますc1FlexGrid1Styles[Normal]BackColor = ColorAzurec1FlexGrid1Styles[Normal]ForeColor = ColorBlueViolet

固定セルの背景色を設定しますc1FlexGrid1Styles[Fixed]BackColor = ColorAqua

C

FlexGrid for WinForms

201 Copyright copy GrapeCity Inc All rights reserved

You can also add your own custom styles to Styles collection by using the Add method For more information abouthow to create and apply custom styles to grid cells see Custom Styles

組み込みセルスタイルNormalのプロパティを設定しますc1FlexGrid1Styles(Normal)BackColor = ColorAzurec1FlexGrid1Styles(Normal)ForeColor = ColorBlueViolet

固定セルの背景色を設定しますc1FlexGrid1Styles(Fixed)BackColor = ColorAqua

VBNET

カスタムのスタイル

Approach 1 Style an ObjectTo style a specific row column or a cell range of the WinForms FlexGrid you can use StyleNew property of the rowcolumn or cell range object

This approach is useful for styling a particular object when style is not expected to be reused To reuse a particularstyle you must create a style using the CellStyle object as discussed in the section below

Approach 2 Create Re-usable StyleIn this approach you can create a custom style as an object of CellStyle class and add it to the Styles collection usingthe Add method Then define its properties and apply it to a row column or cell range whenever required Asmentioned above this approach is very useful when you need to repeatedly use a particular style

Use the code below to create re-usable custom styles for your WinForms FlexGrid

特定の行にカスタムスタイルを適用しますc1FlexGrid1Rows[1]StyleNewBackColor = ColorAzurec1FlexGrid1Rows[1]StyleNewForeColor = ColorBlueViolet

C

特定の行にカスタムスタイルを適用しますc1FlexGrid1Rows(1)StyleNewBackColor = ColorAzurec1FlexGrid1Rows(1)StyleNewForeColor = ColorBlueViolet

VBNET

新しいスタイルを作成しスタイルコレクションに追加しますCellStyle cs = thisc1FlexGrid1StylesAdd(Custom) 新しいカスタムスタイルのプロパティを定義しますcsBackColor = ColorAzurecsForeColor = ColorBlueViolet

行にカスタムスタイルを適用しますc1FlexGrid1Rows[1]Style = cs

C

VBNET

FlexGrid for WinForms

202 Copyright copy GrapeCity Inc All rights reserved

新しいスタイルを作成しスタイルコレクションに追加しますDim cs As CellStyle = Mec1FlexGrid1StylesAdd(Custom)

新しいカスタムスタイルのプロパティを定義しますcsBackColor = ColorAzurecsForeColor = ColorBlueViolet

行にカスタムスタイルを適用しますc1FlexGrid1Rows(1)Style = cs

グリッドのカスタマイズ

FlexGrid also lets you customize overall look of the grid not to just increase its aesthetic value but also increases itsreadability You can add the alternate rows which make the grid more readable Also you can set image for instance awatermark or a company logo in background of the grid

Set Alternate RowTo set the alternate row color and styles in the grid you can use the built-in style Alternate either at design time orat runtime To apply style at design time you need to access the FlexGrid Style Editor and set properties for Alternatestyle

To apply alternate row style in the WinForms FlexGrid through code you need to use the CellStyle item Alternate ofthe CellStyleCollection class and set various properties for setting the alternate style

代替行の前色を設定します c1FlexGrid1Styles[Alternate]ForeColor = ColorWhite

代替行の背景色を設定します c1FlexGrid1Styles[Alternate]BackColor = ColorCadetBlue

C

FlexGrid for WinForms

203 Copyright copy GrapeCity Inc All rights reserved

Set Background Image in GridTo set the background image on a grid you can use the BackgroundImage property and assign the path of the imagefile to it Another property called BackgroundImageLayout property lets you choose whether and how to renderimage on the grid

Use the code below to set the background image on the WinForms FlexGrid

代替行の前色を設定しますc1FlexGrid1Styles(Alternate)ForeColor = ColorWhite

代替行の背景色を設定しますc1FlexGrid1Styles(Alternate)BackColor = ColorCadetBlue

VBNET

背景画像をグリッドに設定しますc1FlexGrid1BackgroundImage = ImageFromFile(CIMG-20190524-WA0037png)c1FlexGrid1BackgroundImageLayout = ImageLayoutStretch

C

背景画像をグリッドに設定しますc1FlexGrid1BackgroundImage = ImageFromFile(CIMG-20190524-WA0037png)c1FlexGrid1BackgroundImageLayout = ImageLayoutStretch

VBNET

境界線のカスタマイズ

The FlexGrid control lets you customize the border of grid row column and even cells by changing its style colordirection and so on

FlexGrid for WinForms

204 Copyright copy GrapeCity Inc All rights reserved

Customize Grid BorderTo customize border of the grid control you can use the BorderStyle property which accepts valuesfrom BorderStyleEnum provided by the C1WinFlexGridUtilBaseControls namespace

Following code shows how to customize border of the WinForms FlexGrid control

Customize RowColumn BorderTo customize the border style of a particular row or column you must access the Border item of CellStyle classusing StyleNew property and set its properties such as border style direction and color The grid controlprovides BorderStyleEnum as well as BorderDirEnum to set the border style and direction respectively

Use the below code to change border of rows or columns of the WinForms FlexGrid

Customize Cell BorderTo customize border of every cell in the grid you can access the built-in style Normal and set its border propertiesSimilarly you can change the style of specific types of cells such fixed or frozen by accessing their correspondingstyles from Styles collection

Below code lets you customize the border of normal cells of the WinForms FlexGrid

グリッドの境界線を3次元の境界線に変更しますc1FlexGrid1BorderStyle = C1WinC1FlexGridUtilBaseControlsBorderStyleEnumFixed3D

C

グリッドの境界線を3次元の境界線に変更しますc1FlexGrid1BorderStyle = C1WinC1FlexGridUtilBaseControlsBorderStyleEnumFixed3D

VBNET

最初の列の境界線スタイルを設定しますc1FlexGrid1Cols[1]StyleNewBorderStyle = BorderStyleEnumGroovec1FlexGrid1Cols[1]StyleNewBorderColor = ColorRedc1FlexGrid1Cols[1]StyleNewBorderDirection = BorderDirEnumVertical

最初の行の境界線スタイルを設定しますc1FlexGrid1Rows[1]StyleNewBorderStyle = BorderStyleEnumRaisedc1FlexGrid1Rows[1]StyleNewBorderColor = ColorBlue

C

最初の列の境界線スタイルを設定しますc1FlexGrid1Cols(1)StyleNewBorderStyle = BorderStyleEnumGroovec1FlexGrid1Cols(1)StyleNewBorderColor = ColorRedc1FlexGrid1Cols(1)StyleNewBorderDirection = BorderDirEnumVertical

最初の行の境界線スタイルを設定しますc1FlexGrid1Rows(1)StyleNewBorderStyle = BorderStyleEnumRaisedc1FlexGrid1Rows(1)StyleNewBorderColor = ColorBlue

VBNET

FlexGrid for WinForms

205 Copyright copy GrapeCity Inc All rights reserved

すべてのグリッドセルの境界線スタイルを設定しますc1FlexGrid1StylesNormalBorderStyle = BorderStyleEnumDouble

C

すべてのグリッドセルの境界線スタイルを設定しますc1FlexGrid1StylesNormalBorderStyle = BorderStyleEnumDouble

VBNET

テキストのカスタマイズ

FlexGrid lets you customize text in various ways such as changing its font margin orientation alignment effects and soon This topic caters to various aspects of text styling by taking a particular row object However if you wish to use anexisting built-in style or want to create your own custom style to re-use it see the corresponding topics

Change FontTo change font of text in a particular row or column object you can use Font property of its CellStyle Following codeshows how to change font of the WinForms FlexGrid row

カスタムスタイルを特定の行に適用しますc1FlexGrid1Rows[1]StyleNewFont = new Font(verdana 10 FontStyleUnderline)c1FlexGrid1Rows[0]StyleNewFont = new Font(verdana 10 FontStyleBold)

C

カスタムスタイルを特定の行に適用しますc1FlexGrid1Rows(1)StyleNewFont = new Font(verdana 10 FontStyleUnderline)c1FlexGrid1Rows(0)StyleNewFont = new Font(verdana 10 FontStyleBold)

VBNET

FlexGrid for WinForms

206 Copyright copy GrapeCity Inc All rights reserved

However if you want to change font of the whole grid you can set Font property of the C1FlexGrid class Followingcode shows how to change font of the entire WinForms FlexGrid

Set MarginTo set margin on text of a particular row or column you can set Margins property of the CellStyle Use the code belowto change margins in WinForms FlexGrid row

Set Vertical TextTo change the orientation and display a text as vertical text you can set TextDirection property of CellStyle of theobject Also to display the vertical text properly you may have to adjust height of the target cells depending upon thetext length Below code lets you set vertical text in the WinForms FlexGrid row

Wrap TextTo wrap a text which is longer than the available cell width you can set the WordWrap property of its CellStyle to trueFollowing code demonstrates how to apply text wrap in the WinForms FlexGrid row

グリッドの内容全体のフォントを変更しますc1FlexGrid1Font = new Font(verdana 10 FontStyleItalic)

C

グリッドの内容全体のフォントを変更しますc1FlexGrid1Font = New Font(verdana 10 FontStyleItalic)

VBNET

右側のマージンを設定しますc1FlexGrid1Rows[1]StyleNewMarginsRight = 10

C

右側のマージンを設定しますc1FlexGrid1Rows(1)StyleNewMarginsRight = 10

VBNET

行の内容のテキスト方向を設定しますc1FlexGrid1Rows[1]StyleNewTextDirection = TextDirectionEnumDown 行の高さを設定して垂直方向のテキストを表示しますc1FlexGrid1Rows[1]Height = 60

C

行の内容のテキスト方向を設定しますc1FlexGrid1Rows(1)StyleNewTextDirection = TextDirectionEnumDown

行の高さを設定して垂直方向のテキストを表示しますc1FlexGrid1Rows(1)Height = 60

VBNET

C

FlexGrid for WinForms

207 Copyright copy GrapeCity Inc All rights reserved

Display Trimmed TextTo display trimmed text when text is longer than the cell width set Trimming property of the style which takes its valuesfrom StringTrimming enumeration Use the code below to trim the long text to display ellipsis character in theWinForms FlexGrid row

Align TextYou can set the text alignment or position of the text with respect to cell by using the TextAlign property The propertyaccepts values from the TextAlignEnum enumeration

Use the code below to apply text alignment on the WinForms FlexGrid row

Apply Text EffectTo set various effects on the text you can use the TextEffect property which accepts its values from TextEffectEnumenumeration

Apply text on the WinForms FlexGrid row using the following code

セルの幅に応じて特定の行のテキストを折り返しますc1FlexGrid1Rows[1]StyleNewWordWrap = true

セルの幅に応じて特定の行のテキストを折り返しますc1FlexGrid1Rows(1)StyleNewWordWrap = True

VBNET

長いテキストをトリミングして最後に省略記号を表示しますc1FlexGrid1Rows[1]StyleNewTrimming = StringTrimmingEllipsisCharacter

C

長いテキストをトリミングして最後に省略記号を表示しますc1FlexGrid1Rows(1)StyleNewTrimming = StringTrimmingEllipsisCharacter

VBNET

テキストの配置を設定しますc1FlexGrid1Rows[1]StyleNewTextAlign = TextAlignEnumLeftCenter

C

テキストの配置を設定しますc1FlexGrid1Rows(1)StyleNewTextAlign = TextAlignEnumLeftCenter

VBNET

上げ表示するテキストを設定しますc1FlexGrid1Rows[1]StyleNewTextEffect = TextEffectEnumRaised

C

上げ表示するテキストを設定します c1FlexGrid1Rows(1)StyleNewTextAlign = TextAlignEnumLeftCenter

VBNET

FlexGrid for WinForms

208 Copyright copy GrapeCity Inc All rights reserved

カスタムのグリフ

FlexGrid lets you change the default glyph images used in the grid to indicate various actions such as column filteringand sorting This behavior of grid is exposed through GridGlyphs class which is a collection of images used by the gridto represent filtered state sorting order checkbox states and so on These images can be accessed through Glyphsproperty of the C1FlexGrid class which accepts values from GlyphEnum enumeration

Change the default glyphs used for filter editor and filtered column in the WinForms FlexGrid to a custom image usingthe code below

Note that setting this property to null restores the default glyph In order to hide a glyph you can set the Glyphproperty to a blank image

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilterEditor] = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilteredColumn] = ImageFromFile(filterico)

C

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilterEditor) = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilteredColumn) = ImageFromFile(filterico)

VBNET

FlexGrid for WinForms

209 Copyright copy GrapeCity Inc All rights reserved

永続的な状態

Grid persistence refers to saving the current state of the grid for later use and then restoring it back when needed Forinstance the user may apply grouping sorting filtering or some styling to the grid which he wants to use after fewmore operations or on opening the application again This behavior can be achieved by persisting the grids state

There are two steps to implement persistence of the grid state First we have to serialize the grid state and then werestore it In this topic we discuss how to persist the filtered sorted and grouped state of the FlexGrid control

You can implement persisting grid states by using XMLWriter and XMLReader class of the SystemXML namespace Tosave the grid state you can use the WriteStartElement method to write the specified start tag andWriteAttributeString method to write the filter sort and group attributes Finally call WriteEndElement method toclose the WriteStartElement method and save the state in the form of stream string or a file

Use the code below to serialize the state of WinForms FlexGrid to an XML file for later use

フィルタグループ並べ替えの定義をファイルに書き込みますprivate void WriteStateToXML(string filePath) using (XmlWriter writer = XmlWriterCreate(filePath)) writerWriteStartElement(FlexGrid) writerWriteStartElement(Definition ) writerWriteAttributeString(Filter flexGridFilterDefinition) writerWriteAttributeString(Sort flexGridSortDefinition) writerWriteAttributeString(Group flexGridGroupDefinition) writerWriteEndElement() writerWriteEndElement() writerFlush()

C

フィルタグループ並べ替えの定義をファイルに書き込みますPrivate Sub WriteStateToXML(ByVal filePath As String)

VBNET

FlexGrid for WinForms

210 Copyright copy GrapeCity Inc All rights reserved

To load the saved state back into the grid you can use the GetAttribute method of the object to read the filter sortand group attributes Then assign them to the FilterDefinition SortDefinition or GroupDefinition properties of theFlexGrid respectively

Use the code below to load saved state of the WinForms FlexGrid

Using writer = XmlWriterCreate(filePath) writerWriteStartElement(FlexGrid) writerWriteStartElement(Definition ) writerWriteAttributeString(Filter flexGridFilterDefinition) writerWriteAttributeString(Sort flexGridSortDefinition) writerWriteAttributeString(Group flexGridGroupDefinition) writerWriteEndElement() writerWriteEndElement() writerFlush() End UsingEnd Sub

保存したファイルからフィルタ並べ替えグループの定義を読み取りFlexGridに適用しますprivate void ReadStateXML(string filePath)

using (XmlReader reader = XmlReaderCreate(filePath)) readerReadToFollowing(Definition) flexGridSortDefinition = readerGetAttribute(Sort) flexGridFilterDefinition = readerGetAttribute(Filter) flexGridGroupDefinition = readerGetAttribute(Group) readerClose()

C

保存したファイルからフィルタ並べ替えグループの定義を読み取りFlexGridに適用しますPrivate Sub ReadStateXML(ByVal filePath As String) Using reader = XmlReaderCreate(filePath) readerReadToFollowing(Definition) flexGridSortDefinition = readerGetAttribute(Sort) flexGridFilterDefinition = readerGetAttribute(Filter) flexGridGroupDefinition = readerGetAttribute(Group) readerClose() End Using

VBNET

FlexGrid for WinForms

211 Copyright copy GrapeCity Inc All rights reserved

NET 5 リファレンス

FlexGrid for WinForms

212 Copyright copy GrapeCity Inc All rights reserved

NET 452 リファレンス

FlexGrid for WinForms

213 Copyright copy GrapeCity Inc All rights reserved

  • 目次
  • FlexGrid for WinForms
  • 主な特長
  • 機能比較
    • FlexGrid の比較
    • WinFormsグリッドの比較
      • クイックスタート
      • 設計時サポート
        • タスクメニュー
        • エディタ
          • データ
            • 非連結モード
            • 連結モード
              • 連結モードでの操作
                    • 基本操作
                    • ユーザー操作
                    • エディタ
                      • チェックボックス
                      • 数値
                      • 日付
                      • コンボボックス
                      • マスク
                      • マップリスト
                      • セルボタン
                        • 検証
                        • データ注釈
                        • スパークライン
                        • ヘッダとフッタ
                        • サイズ変更
                            • 基本操作
                            • ユーザー操作
                            • ヘッダ
                            • 行の詳細
                            • サイズ変更
                              • セル
                                • 基本操作
                                • セルの書式設定
                                  • グリッド
                                    • 基本操作
                                    • キーボードによる移動
                                    • パフォーマンスの向上
                                      • スクロールバー
                                      • 選択
                                      • 編集
                                        • 編集モード
                                        • 編集の無効化
                                          • 並べ替え
                                            • 並べ替えの操作
                                            • 並べ替えのインジケータ
                                              • フィルタ
                                                • フィルタの操作
                                                  • フィルタの種類
                                                    • フィルタUI
                                                      • 検索
                                                      • マージ
                                                        • 自動マージ
                                                        • はみ出して表示されるセルの処理
                                                        • カスタムのマージ
                                                          • グループ
                                                          • 集計
                                                          • ツリーグリッド
                                                            • ノードの操作
                                                            • データの操作
                                                            • ツリーグリッドのカスタマイズ
                                                              • クリップボード
                                                              • 保存ロードと印刷
                                                                • 保存
                                                                • ロード
                                                                • 印刷
                                                                  • 外観とスタイル設定
                                                                    • 組み込みオプション
                                                                    • カスタムのスタイル
                                                                    • グリッドのカスタマイズ
                                                                    • 境界線のカスタマイズ
                                                                    • テキストのカスタマイズ
                                                                    • カスタムのグリフ
                                                                      • 永続的な状態
                                                                      • NET 5 リファレンス
                                                                      • NET 452 リファレンス
Page 5: FlexGrid for WinForms

FlexGrid for WinForms

FlexGrid for WinForms is one of the fastest datagrids available in the market that renders and displays large data sets quicker than any other NET datagrid It is a powerfulgrid packed with basic as well as advanced features like in-cell editing sorting filtering merging grouping and much more Moreover it displays the hierarchical dataefficiently using tree grids with multiple columns aggregates subtotals and row details Not just this the control offers robust API and extensive design-time support sothat you can give your end-users a familiar Excel-like experience

The FlexGrid control binds with any of the NET data sources such as ADONET data source objects and custom business objects It also lets you work in the unbound modegiving you the power to manually add each row or column and set the cell values

One of the main strengths of FlexGrid is the ability to customize almost every aspect of appearance of the entire grid and individual cells In addition to standard formatstrings and cell styling FlexGrid goes above and beyond most NET datagrid components by providing complete control over the cell drawing using its OwnerDrawCell event

Besides the main C1FlexGrid control FlexGrid for WinForms also contains a C1FlexGridClassic control derived from C1FlexGrid It provides an object model that is virtuallyidentical to the VSFlexGrid ActiveX control and is mainly targeted for customers who want to migrate their existing VSFlexGrid projects from ActiveX to the latest technology

Not just this if you are developing your own custom grid control you can use C1FlexGridClassic as a reference The C1FlexGridClassic control is a perfect example of customgrid control created with C1FlexGrid control as base class We ship its source code as a product sample named Classic

Release Notes Product Samples

See the version-wise updates for all controls here Product samples are located at DocumentsComponentOne SamplesWinFormsvxxxC1FlexGridCS onyour system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

Documentation Blogs

Create your First Application with FlexGrid

FlexGrid at Design-time

Work with Columns and Editors

Filter Grid Data

Enable Merging in FlexGrid

Create Groups

Create a Tree Grid

Financial Data Displays using FlexGrid

FlexGrid Performance Compare WinForms WPF UWP

Creating Custom Styles for FlexGrid

Add Dynamic Grouping to your WinForms Data Grid

Implement responsive columns in a WinForms data grid

Creating a Derived Accordion Control with FlexGrid

Show RadioButton in a ComponentOne FlexGrid Tree

Videos Demo Samples

Meet FlexGrid WinForms and WPF Grid Demo

Note ComponentOne FlexGrid for WinForms is compatible with both NET 452 and NET 5

API Reference

C1WinFlexGrid452 Assembly C1WinFlexGrid5 Assembly

FlexGrid for WinForms

4 Copyright copy GrapeCity Inc All rights reserved

主な特長

Code-free Development

Why write code when a click is enough With rich design-time options beginning from binding to styling whichare accessible through the tasks menu and various editors FlexGrid lets you do a lot even without writing a single lineof code

Advanced Cell Editing

Choose from a variety of built-in editors or just create one for yourself FlexGrid offers various built-in cell editors sothat you can choose from simple text editing drop-down lists combo lists cell buttons masks and so on Not justthis with an option to create your own custom cell editors you can change your cells to accept or display almostany type of data

Work in Bound Mode or Unbound Mode

Bound grid or unbound populate the data seamlessly FlexGrid lets you bind the grid with any of the NET datasources such as ADONET and DataObjects for NET You can also work in unbound mode and let FlexGrid manage thedata itself

Present Hierarchical Data

View data the way that is best for you and your users When FlexGrid is bound to a hierarchical data source eachmaster record can be expanded or collapsed to show or hide the details in child grids which may contain moredetails The result is a data tree similar to the type of grid presented by Microsoft Access when displayinghierarchical data When bound the control detects subordinate data sources and creates additional instances of itselfto display child tables

Summarize Data and Show Aggregates

Get a quick outline of your grid data by summarizing it FlexGrid allows you to summarize data by adding a subtotalrow and display aggregates such as sum average count and so on for the specified column

Make it a Tree

Easily display your hierarchical data by converting your grid into a tree FlexGrid lets you represent your bound orunbound hierarchical data in Tree Grid which is similar to a TreeView control and gives a clean yet accessible structureto the data

Built-in Data Filtering

Let your users filter the data by value by condition or just give them both the options to choose from FlexGridprovides advanced built-in filtering with column filter value filter and condition filter already in place Still does notwork for you Create your own custom filter using rich FlexGrid API

Grouping

Group programmatically or at run-time With FlexGrid both are possible FlexGrid lets you group either through codeand even give your users an option to group at run-time using the FlexGridGroupPanel control or through contextmenu

Instant Search

Search the entire grid in one go and locate entries among millions of records instantly FlexGridprovides FlexGridSearchPanel control which lets the user type in the search box filters the records that match thetyped text and also highlights the search results

Merge Cells

Give your grid a tidy look by merging the cells with the same values FlexGrid lets you merge the contiguous cells withthe same values the way you want With free and restricted auto-merge options the grid can intelligently decidewhich cells to merge

Save and Load Multiple Formats

Back up the grid data or load it back in a jiffy FlexGrid lets you save the grid in your favorite format be it a text fileexcel file or XML You can even load content from these formats Not just this you can also load grid data from a

FlexGrid for WinForms

5 Copyright copy GrapeCity Inc All rights reserved

database using DataReader objects

Show Sparklines

Perk up your grid with the tiny charts FlexGrid allows you to add sparklines to grid columns so that you can easilydisplay trends and fluctuations in a single cell and make your grid data more useful and attractive at the same time

Perform Clipboard Operations

Move your text easily with Ctrl+C and Ctrl+V FlexGrid lets you perform clipboard operations on the grid data andheaders using your favorite keys

Assign Field Names to Columns

No need to remember the index of columns just call them by name FlexGrid automatically assigns column keysto field names when the grid is data-bound or you may assign them through code You can refer to a column using aColIndex(ColKey) syntax later which will retrieve the column you want even if your user has moved it to a differentposition on the grid

Use Data Annotations

Hint the user with data annotations FlexGrid lets you add data annotations in the form of metadata tags to theclasses and other objects to display messages and tips for the users

UI Automation and Support

Enable accessible and rich client applications through UI Automation (UIA) FlexGrid control supports UI Automationusing frameworks such as TestStackWhite You can enable applications such as screen readers coded UI testing toexamine user-interface elements and even simulated user interaction through code

Note UI Automation works only for the 452 version of C1FlexGrid and NET framework 47 or above applicationtarget frameworks

Add Special Drawing Effects

Make your grid look different and attractive with special drawing effects FlexGrid lets you paint special drawingeffects such as lines bitmaps and icons in the grid cells Additionally you can even scale images and addtransparency to them

Display Images in Cells

Need to display images in columns not an issue at all With FlexGrid you can display images along with data You caneven bind grid columns to image lists an easy and efficient way to display graphical information from data sources

Integrated Printing

Print the grid with a single statement FlexGrid gives you control over paper orientation margins header and footertext as well as the dialog boxes to set up the printer or see a preview You can even implement advanced printingoptions such as adding page breaks or custom elements to each page by using printing events

Styling

Use the visual styles or create your own custom styling use the designer or write your own code FlexGrid gives youenormous options to customize the appearance of the grid to match your requirements You can customize everyelement of the FlexGrid starting from headers and icons to borders and subtotal rows

FlexGrid for WinForms

6 Copyright copy GrapeCity Inc All rights reserved

機能比較

This section compares the features of various FlexGrids available across different platforms as well as shows acomparison with MS DataGridView

Topic Content

ComparingFlexGrids

Lists the difference between ActiveX version(VSFlexGrid control) and NET version of the FlexGridcontrol making it easy to migrate your grid from AciveX to NET

VSFlexGrid (ActiveX) and C1FlexGrid (NET)

ComparingWinForms Grids

Shows comparison between features of grids available in ComponentOne WinForms Edition andMS DataGridView

FlexGrid or True DBGridComparing ComponentOne Grids with MS DataGridView

FlexGrid の比較

VSFlexGrid (ActiveX) and C1FlexGrid (NET)ComponentOne provides ActiveX as well as NET version of the FlexGrid control While the ActiveX version is known asVSFlexGrid the NET version is shipped in the name of C1FlexGrid Being a NET version C1FlexGrid came laterinto the picture and instead of porting from the already existing VSFlexGrid we decided to create a brand new gridcontrol written from the ground up in C with the same design principles but with a new object model that is moremodern clean and powerful than the one in the ActiveX control

This section caters to original users of the VSFlexGrid control who want to migrate their applications from ActiveX tothe NET version that is the C1FlexGrid control To facilitate the hassle-free migration and a smooth learning curvethe NET version provides the C1FlexGridClassic control that derives from the C1FlexGrid class and provides an objectmodel that is virtually identical to the VSFlexGrid control The C1FlexGridClassic control is available in the form of aproduct sample Classic so that you may know exactly how to use the new object model This sample can also beused as a reference for creating the custom grid controls based on the C1FlexGrid class

Note The Classic sample is located at DocumentsComponentOne SamplesWinFormsv452C1FlexGridCS onyour system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

For users creating new applications we recommend using the new C1FlexGrid control However for the users who areporting their existing applications from ActiveX to NET we recommend using the C1FlexGridClassic control tominimize the programming effort Following table highlights some of the key differences between VSFlexGrid andC1FlexGrid

VSFlexGrid (ActiveX) C1FlexGrid (NET)

RowsCols1 Rows and Cols properties are used to

get or set the number of rows andcolumns

2 VSFlexGrid uses the TextMatrixproperty to represent the rows andcolumns

1 In C1FlexGrid Rows and Cols propertiesreturn the rows and column collectionsThe collections have readwriteproperties that return the number ofelements and fixed elements in eachcollection

FlexGrid for WinForms

7 Copyright copy GrapeCity Inc All rights reserved

For instance in ActiveX you would write

Dim r c c = 1

For r = c1FlexGrid1FixedRows To

c1FlexGrid1Rows - 1

DebugPrint

c1FlexGrid1TextMatrix(rc)

Next

2 C1FlexGrid uses indexers to representrows and columns

For instance in NET you would write

Dim r c c = 1

For r = c1FlexGrid1RowsFixed To

c1FlexGrid1RowsCount - 1

DebugPrint(c1FlexGrid1(r c))

Next

CellCell range The Cell property is one of the mostpowerful elements of the VSFlexGrid objectmodel It allows you to get or set anyproperty of any cell or cell range with asingle command Using a single propertymeans using variants and this prevents thecompiler from catching many subtleproblems in case you make mistakes whilecoding

For instance in ActiveX you would write

flexCell(flexcpPicture 5 5

10 10)

= theImage

In C1FlexGrid CellRange object has replacedthe Cell property to expose type-safeproperties and methods for accessing cellrange So if variable theImage contained astring instead of an image you get a compilererror and not a runtime error Also you getcommand-completion when writing the codebecause the types for each property are known

For instance in NET you would write

Dim rg As CellRange

rg =

c1FlexGrid1GetCellRange(551010)

rgImage = theImage

Typed Columns In the ActiveX version the ColDataTypeproperty allows you to set the type of datathat each column contains This informationis used mainly for sorting columns thatcontain dates or numbers

In the NET version Cols[i]DataType propertydetermines the type of data the column holdsBy default the DataType property for allcolumns is set to object that is you can storeany type of data in any column You can set thedata type to specific types however the gridtries to coerce any data stored in the grid tothe proper type

For instance in NET you would write

c1FlexGrid1Cols(2)DataType =

GetType(Integer)

Sets the value to 12

c1FlexGrid1(1 2) = 12

Can not convert hello string to

integer

Fires the GridError event

Retains the original value

c1FlexGrid1(2 2) = hello

Styles In VSFlexGrid you can customize theappearance of individual cells or cell rangesusing the Cell property

For instance in ActiveX you would write

Set the backcolor of second row

c1FlexGrid1Cell(flexcpBackColor

In C1FlexGrid cell appearance can becustomized using the CellStyle object

For instance in NET you would write

Create a cell style

Dim redStyle As CellStyle =

c1FlexGrid1Styles

FlexGrid for WinForms

8 Copyright copy GrapeCity Inc All rights reserved

2 0 2

c1FlexGrid1Cols-1) = vbRed

Demerit

To change the appearance of all red cellsyou need to clear all styles and start again oryou need to scan for red cells and thenchange their appearance

Add(Red)

redStyleBackColor = ColorRed

Set the backcolor of second row

c1FlexGrid1Rows(2)Style =

redStyle

Merit

The main advantage of this approach is that thenew style is an object that can be changed orassigned to new ranges For instance tochange the fore-color and text font of red cellsyou would write

c1FlexGrid1Styles(Red)ForeColor

= ColorWhite

c1FlexGrid1Styles(Red)Font =

new Font(Arial 9)

The VSFlexGrid control had many propertiesthat affected the way the grid was displayed(eg BackColor BackColorAlternateBackColorBkg BackColorFixedBackColorFrozen BackColorSel and so on)

The C1FlexGrid control replaces all theseproperties with a collection of CellStyle objectsso you can write something likeStylesFixedBackColor orStylesHighlightForeColor This makes theobject model simpler more consistent andmore powerful You can change the built-instyles or define your own and assign them torows columns or arbitrary cell ranges

WinFormsグリッドの比較

FlexGrid or True DBGridComponentOne offers two grid components in WinForms Edition FlexGrid and True DBGrid While both of these are robust and easy-to-usegrids allowing you to browse edit add delete and manipulate tabular data they still have their own strengths and capabilities

Both ComponentOne WinForms Edition grids can be used in bound as well as unbound mode but C1FlexGrid allows you to work more easilyin unbound mode With C1FlexGrid you can customize trees and make use of its cell merging capabilities FlexGrid is also apt for deriving acustomized grid

If you are planning to develop or migrate to NET 5 or higher it is recommended to use C1FlexGrid While we will continue to supportC1TrueDBGrid in NET 5 it no longer receives new enhancements and features like C1FlexGrid

Comparing ComponentOne Grids with MS DataGridViewThis section gives you a quick comparison between the two ComponentOne WinForms Edition grids and the standard MS DataGridViewavailable for WinForms platform For easy navigation we have broadly divided these features into different categories Click on thecorresponding category in the right hand pane or scroll down to know more about availability of a particular feature

Data Binding

Features FlexGrid TrueDBGrid MS DataGridView

Binding Data Sources

Binding Data Sources with hierarchical datarelations

With custom code

Unbound data storage and manipulations

Data Presentation

FlexGrid for WinForms

9 Copyright copy GrapeCity Inc All rights reserved

Features FlexGrid TrueDBGrid MS DataGridView

Hierarchical Styles With custom code

TreeView-like Styles

MultiLine Data View

Grouping

Built-in Drag And Drop

Horizontal and Vertical Interactive Splits

Child grids within master grid support

Drop-Down Objects Support

Drop-Down Multicolumn Object support

Drop-Down Multicolumn Bindable and SortableObject support

Data Exchange

Features FlexGrid TrueDBGrid MS DataGridView

Export Data (Delimited Text XLS and XLSX)

Export Data in other formats (PDF HTML RTFJPG and other)

Load data from Excel files

Enhanced Printing data from grid and PrintPreview support

Cell Manipulations

Features FlexGrid TrueDBGrid MS DataGridView

In-Cell Objects

Enhanced Cell Editing with Custom Editors

Merging Cells and Rows

Customize Cells Merging

Drag And Drop Columns and rows

Automatic Cell Sizing

Fixed Non-scrolling Columns

Excel-style Cell Selection

Customize each Cell Rendering

Zooming Cells

Run-Time CellTips

Data Manipulations with Cell Ranges

Layout and Styling

Features FlexGrid TrueDBGrid MS DataGridView

Visual Styles Support

Dynamic Support of 38 Decoration Themes

Office 2007 and 2010 Styling

Alternating Row Colors

Customizable Cell Border Style

FlexGrid for WinForms

10 Copyright copy GrapeCity Inc All rights reserved

Add Special Drawing Effects

Data-Sensitive Display

Input and Navigation

Features FlexGrid TrueDBGrid MS DataGridView

Input Masking

Simplify Data Input

Automatic Data Translation

Spell Checking support

Customizable Keyboard Navigation and keysbehavior

Right-To-Left navigation

Touch Support

Clipboard support

Rich Scrolling Capabilities

Data Manipulations

Features FlexGrid TrueDBGrid MS DataGridView

Sorting

Multi-column Sorting

Built-in Data Filtering

Extended and Conditional Filtering

Customizable filter form

Additional Filter Bar row

Multi-language Filtering

AutoSearch

Range Aggregates

Localization

Features FlexGrid TrueDBGrid MS DataGridView

Right-To-Left support

Net localization support

Regional settings support

Other Features

Features FlexGrid TrueDBGrid MS DataGridView

Optimize performance for displaying largeamount of data in bound and unbound mode

Just-In-Time Data Loading

Server-side Data Virtualization withC1DataSource

Automatic Lookup Columns with C1DataSource

Design-time extended support

Assembly size 1508 K 2108 K Part of

FlexGrid for WinForms

11 Copyright copy GrapeCity Inc All rights reserved

SystemWindowsForms

FlexGrid for WinForms

12 Copyright copy GrapeCity Inc All rights reserved

クイックスタート

This quick start will guide you through the steps of creating a simple grid application using the FlexGrid control Follow thesteps below to get started

FlexGrid for WinForms

13 Copyright copy GrapeCity Inc All rights reserved

This section demonstrates how to create a FlexGrid application in NET 452 by binding it to an externaldatasource You can also create a class to supply data to the grid as shown in the NET 5 tab Similarly you can usebelow steps to bind FlexGrid to a datasource in NET 5 However note that some design-time steps may vary in caseof NET 5

Set Up the Application1 Create a new Windows Forms app(NET Framework)2 Configure your project and set the Framework property3 Drag and drop the FlexGrid control from the Visual Studio toolbox onto the form

Observe An empty grid is added to the form at design time

Bind FlexGrid to a Data SourceThere are two ways to bind data with the FlexGrid control either choose to bind at design time or through code atrun time

Binding at Design Time

1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Click the Choose Data Source drop down button and select Add Project Data Source option to open the

Data Source Configuration Wizard3 On Choose a Data Source Type page select Database and click Next4 On Choose a Database Model page select Dataset and click Next5 On Choose Your Data Connection page click New Connection to open the Add Connection dialog6 Against the DataSource field click Change button to open the Change Data Source dialog7 Select Microsoft Access Database File and click OK to return to the Add Connection dialog8 Against the Database file name field click Browse and navigate to the database file Provide the User name

and Password if required to connect to the database file This example uses C1NWindmdb file located atthe following location by defaultDocumentsComponentOne SamplesCommon

9 Click Test Connection to make sure that you have successfully connected to the database or server and clickOK

NET 452

FlexGrid for WinForms

14 Copyright copy GrapeCity Inc All rights reserved

10 Click OK again to close the Add Connection dialog box11 Click Next 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 Choose the appropriate option as per your requirement12 Save the connection string in the application configuration file by checking the Yes save the connection as

box and entering a name13 Click Next to switch to the Choose Your Database Objects page14 Choose a table say Products from the Tables node and click Finish15 The above steps add a dataset and connection string to your project Also Visual Studio automatically creates

the following code to fill the datasetC

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて

移動または削除できます

thisproductsTableAdapterFill(thisc1NWindDataSetProducts)

VBNET

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移

動または削除できます

MeProductsTableAdapterFill(Mec1NWindDataSetProducts)

Binding at Run Time

To bind the grid through code first we need to create a database connection string Then use an object of dataadapter (in this case OleDbDataAdapter) to create a query to fetch products from the data table and fill it in thedata table which is assigned to the DataSource property of C1FlexGrid class

C

グリッドをデータソースに連結します

string conn = GetConnectionString()OleDbDataAdapter da = new OleDbDataAdapter(select from products conn)DataTable dt = new DataTable(Products)daFill(dt)c1FlexGrid1DataSource = dt

VBNET

グリッドをデータソースに連結します

Dim conn As String = GetConnectionString()Dim da As OleDbDataAdapter = New OleDbDataAdapter(select from products conn)Dim dt As DataTable = New DataTable(Products)daFill(dt)c1FlexGrid1DataSource = dt

Note that the above sample code uses a custom method named GetConnectionString to create a connection stringwith database

C

static string GetConnectionString() string path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) + ComponentOne SamplesCommon string conn = provider=microsoftjetoledb40data source=0c1nwindmdb return stringFormat(conn path)

VBNET

Private Shared Function GetConnectionString() As String Dim path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) amp

FlexGrid for WinForms

15 Copyright copy GrapeCity Inc All rights reserved

ComponentOne SamplesCommon Dim conn = provider=microsoftjetoledb40data source=0c1nwindmdb Return StringFormat(conn path)End Function

Configure the FlexGrid controlThis section walks you through the design-time and run-time steps to configure the grid with some basic settingsThese settings and features are explained in detail in the topics below

Configuring Grid at Design Time

Click smart tag to open the C1FlexGrid Tasks MenuClick the Styles option to open C1FlexGrid Styles EditorSelect Fixed from Built-in Styles pane customize some settings such as Backcolor Font and ForeColor andclick OKTo fit the grid to the form click the Dock in Parent Container optionFor customizing a column click the column (say Unit Price column) to open C1FlexGrid Column TasksMenuClick the ellipsis alongside Format field to open the Format String dialogSelect Currency as Format Type and click OK

Configuring Grid at Run Time

Add following code to configure the grid and its columns at run time

C

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = new Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols[6]Format = c

VBNET

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = New Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols(6)Format = c

FlexGrid for WinForms

16 Copyright copy GrapeCity Inc All rights reserved

This section demonstrates how to create a FlexGrid application in NET 5 by populating its data from a custom classYou can also use an external datasource to supply data to the grid as shown in NET 452 tab However note thatsome design-time steps given in the aforementioned tab may vary in case of NET 5 Similarly you can use belowsteps to bind FlexGrid to an internal datasource in NET 452

Set Up the Application1 Create a new Windows Forms app(NET Framework)2 Configure your project and set the Framework property3 Initialize the FlexGrid control and add it to the form

C

コントロールを初期化します

C1FlexGrid flexGrid = new C1FlexGrid() フォームにコントロールを追加します

thisControlsAdd(flexGrid)

VBNET

コントロールを初期化します

Dim flexGrid As C1FlexGrid = New C1FlexGrid() フォームにコントロールを追加します

MeControlsAdd(flexGrid)

Bind FlexGrid to a Data Source1 Create a custom class Product to be used as a data source

C

カスタムクラスProductを作成します

public class Product static Random _rnd = new Random()

NET 5

FlexGrid for WinForms

17 Copyright copy GrapeCity Inc All rights reserved

static string[] _names = Macko|Surfair|Pocohey|StudebySplit(|) static string[] _lines = Computers|Washers|Stoves|CarsSplit(|) static string[] _colors = Red|Green|Blue|WhiteSplit(|) public Product() Name = _names[_rndNext() _namesLength] Line = _lines[_rndNext() _linesLength] Color = _colors[_rndNext() _colorsLength] Price = 30 + _rndNextDouble() 1000 Cost = 3 + _rndNextDouble() 300 Discontinued = _rndNextDouble() lt 2 Introduced = DateTimeTodayAddDays(_rndNext(-600 0)) public string Name get set public string Color get set public string Line get set public double Price get set public double Cost get set public DateTime Introduced get set public bool Discontinued get set

VBNET

カスタムクラスProductを作成します

Public Class Product Private Shared _rnd As Random = New Random() Private Shared _names As String() = Macko|Surfair|Pocohey|StudebySplit(|c) Private Shared _lines As String() = Computers|Washers|Stoves|CarsSplit(|c) Private Shared _colors As String() = Red|Green|Blue|WhiteSplit(|c)

Public Sub New() Name = _names(_rnd[Next]() Mod _namesLength) Line = _lines(_rnd[Next]() Mod _linesLength) Color = _colors(_rnd[Next]() Mod _colorsLength) Price = 30 + _rndNextDouble() 1000 Cost = 3 + _rndNextDouble() 300 Discontinued = _rndNextDouble() lt 2 Introduced = DateTodayAddDays(_rnd[Next](-600 0)) End Sub

Public Property Name As String Public Property Color As String Public Property Line As String Public Property Price As Double Public Property Cost As Double Public Property Introduced As Date Public Property Discontinued As BooleanEnd Class

2 Initialize a list of type ProductC

Productがクラス型であるProduct型のリストを初期化します

ListltProductgt _products = new ListltProductgt()

FlexGrid for WinForms

18 Copyright copy GrapeCity Inc All rights reserved

VBNET

Productがクラス型であるProduct型のリストを初期化します

Dim _products As List(Of Product) = New List(Of Product)()

3 Initialize a For loop and add products to the list

C

forループを初期化し製品をリストに追加します

for (int i = 0 i lt100 i++) _productsAdd(new Product())

VBNET

forループを初期化し製品をリストに追加します

For i As Integer = 0 To 100 - 1 _productsAdd(New Product())Next

4 Bind FlexGrid to the created data sourceC

FlexGridにデータを連結します flexGridDataSource = _products

VBNET

FlexGridにデータを連結します flexGridDataSource = _products

Configure the FlexGrid controlAdd following code to configure the grid and its columns at run time

C

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = new Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols[6]Format = c

VBNET

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = New Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols(6)Format = c

FlexGrid for WinForms

19 Copyright copy GrapeCity Inc All rights reserved

設計時サポート

FlexGrid for WinForms comes with various design time options to make your programming tasks a lot easier In addition to smart tag context menu andproperty grid FlexGrid provides tasks menus and editors as well While C1FlexGrid Tasks menu lets you work on the entire grid in design time the ColumnTasks menu provides options to set some common properties for each column of the grid At the same time various editors such as C1FlexGrid ColumnEditor and C1FlexGrid Style Editor provide detailed properties to customize the columns and styles

This section discusses about various design-time options available in the FlexGrid control

Topic Snapshot Content

Tasks Menus Discusses about the C1FlexGrid Tasks menu the Column Tasks menu and their options

C1FlexGrid Tasks MenuC1FlexGrid Column Tasks Menu

Editors Discusses about the various editors and how to access them

C1FlexGrid Column EditorC1FlexGrid Style EditorCaption Style EditorColumn Style Editor

タスクメニュー

C1FlexGrid Tasks MenuC1FlexGrid Tasks menu provides you an easy access to the commonly used properties of FlexGrid It also providesoptions to open various editors such as C1FlexGrid Column Editor C1FlexGrid Style Editor

To access the C1FlexGrid Tasks menu click the smart tag ( ) in the upper right corner of the grid Following tableexplains various options available through the C1FlexGrid Tasks menu

Option Description

ChooseDataSource

The dropdown opens the list of available data sourcesand gives you Add Project Data Source option to openData Source Configuration Wizard

For more information on how to add a new data sourceto the project see Bound Mode

EnableAddingRows

The checkbox toggles the AllowAddNew propertywhich allows users to add new row to the grid at runtime When checked ON it displays a template row withstar at the bottom of the grid to enter the new record

EnableDeletingRows

The checkbox toggles the AllowDelete property whichallows users to delete the selected rows by pressing theDelete key

EnableEditing

The checkbox toggles the AllowEditing property whichallows users to edit the grid

Enable Column Reordering The checkbox sets the AllowDragging property toColumns which allows users to re-order the columns by draggingthe column headers

Enable Column Filtering The checkbox toggles the FlexGridAllowFiltering property to

FlexGrid for WinForms

20 Copyright copy GrapeCity Inc All rights reserved

enable or disable the filtering on grid columns

VisualStyle The dropdown lets you choose the built-in visual styles availablein the grid By default the value is set to Custom

Designer The option opens C1FlexGrid Column Editor which allows you toset the properties of each column of the grid

Styles The option opens C1FlexGrid Style Editor which allows youto customize the various pre-defined styles or create the newstyles at design time

Display Hidden Columns The checkbox lets you display or hide grid columns in the designview Note that this option is NOT associated with the run-timevisibility of columns Hence even if this checkbox is checked ONcolumns with Visible property set to False still remain hiddenwhen the application is run

Column Tasks The option switches the task menu to C1FlexGrid Column Tasksmenu which provides options to set the properties for theselected column

About C1FlexGrid The option displays a dialog box displaying the information suchas version of the FlexGrid control

Dock in Parent Container This option sets the Dock property of the grid to Fill which resizesthe grid to occupy the whole form space Clicking the option alsoswitches the text and provides option to Undock in ParentContainer which restores the grid to its original size

C1FlexGrid Column Tasks MenuC1FlexGrid Column Tasks menu provides you an easy access to the commonly used properties of grid columns Italso provides options to open editors named Caption Style and Column Style

To access the C1FlexGrid Column Tasks menu double-click header of the column to be configured at design-timeAnother way to open C1FlexGrid Column Tasks menu is to click on the smart tag ( ) in the upper right corner of thegrid and then navigate to the Column Tasks option Following table explains various options available through theC1FlexGrid Column Tasks menu

FlexGrid for WinForms

21 Copyright copy GrapeCity Inc All rights reserved

Option Description

ColumnCaption

The field allows you to specify the value of Captionproperty which sets text in header cell of the column

DataField

The dropdown opens a list of available fields in the datasource to choose from and sets value of Name property ofthe column

DataType

The dropdown opens a list of available data types and letsyou set the data type of the selected column This fieldcorresponds to the DataType property of the column

EditMask

The field lets you specify value of EditMask property whichsets mask for the selected column The ellipsis button onthe right side of the field opens the Input Mask dialog boxwhere you can select from the list of pre-defined masks

FormatString

The field lets you specify the value of Format propertywhich sets format string to display data value from source

ComboList

The field lets you specify the list of multiple values fromwhich user can choose The ellipsis button on the right sideof the field lets you open the Combo List dialog box whereyou can specify the value options

Allow Sorting The checkbox toggles the AllowSorting property to enable ordisable sorting in the column By default sorting is enabled for allcolumns

Allow Editing The checkbox toggles the AllowEditing property to make thecolumn read-only or editable By default editing is enabled for allcolumns

Allow Resizing The checkbox toggles the AllowResizing property which allows usersto adjust the size of column at run time By default resizing isenabled for all columns

Allow Dragging The checkbox toggles the AllowDragging property to enable ordisable re-ordering of the column at run time By default dragging isenabled for all columns

Allow Merging The checkbox toggles the AllowMerging property to enable ordisable merging two adjacent column cells having same values Bydefault merging is disabled for all columns

Allow Filtering The dropdown lets you specify the value of ColumnAllowFilteringproperty and choose the type of filter for each column The availableoptions are Default ByValue ByCondition Custom or None

Visible The checkbox lets you set the visibility of the column in the grid atrun time by toggling value of its Visible property

FlexGrid for WinForms

22 Copyright copy GrapeCity Inc All rights reserved

Caption Style The option opens the Caption Style editor which gives you options tostyle the text alignment background and border for the header cellof column

Column Style The option opens the Column Style editor which gives you options tostyle the text alignment background and border for the column text

C1FlexGrid Tasks The option switches the task menu to C1FlexGrid Tasks menu whichprovides options to set the properties for the entire grid

Dock in Parent Container The option sets the Dock property of the grid to Fill which resizes thegrid to occupy the whole form Clicking the option also switches thetext and provides option to Undock in Parent Container whichrestores the grid to its original size by setting the Dock property toNone

エディタ

Apart from the tasks menu FlexGrid also provides various editors that help you set a number of properties related togrid its columns and their styles

C1FlexGrid Column EditorFlexGrid provides the C1FlexGrid Column Editor making it easy to work with columns at design-time instead ofwriting code The editor lets you set various properties related to columns such as Caption DataTypeAllowFiltering and AllowMerging through its property pane on left hand side Toolbar on the top of this editorgives you options such as reloading data from the data source adding removing and resizing columns You can evenstyle the column text using the options given in this toolbar For further customization of column text you can usethe Column Style editor to access more specific properties

FlexGrid for WinForms

23 Copyright copy GrapeCity Inc All rights reserved

There are three ways in which you can access the C1FlexGrid Column Editor at design time

Smart Tag Click the smart tag ( ) in the upper right corner of the grid and select Designer from theC1FlexGrid Tasks menuProperty Window Select the grid go to the Properties window and click the ellipsis button (hellip) next to theCols propertyContext Menu Right-click the grid and select Designer from the context menu

C1FlexGrid Style EditorFlexGrid provides the C1FlexGrid Style editor which lets you style the grid at design time by customizing the built-instyles and creating the new ones The editor offers a list of styles for specific types of cell on left hand side and aproperty window on right hand side to customize these styles The list of styles is divided into two sections thedefault Built-in Styles and Custom Styles Towards the bottom there are Add and Remove buttons to add anddelete the custom styles and a Clear button to revert the editor to default settings The AutoFormat button in theend opens a secondary dialog C1FlexGrid Auto Format which lists the pre-defined set of styles and also shows apreview in the Preview pane

FlexGrid for WinForms

24 Copyright copy GrapeCity Inc All rights reserved

There are three ways in which you can access the C1FlexGrid Style Editor at design-time

Smart Tag Click the smart tag ( ) in the upper right corner of the grid and select Styles from theC1FlexGrid Tasks menuProperty Window Select the grid go to the Properties window and click the ellipsis button (hellip) next to theStyles propertyContext Menu Right-click the grid and select Styles from the context menu

Caption Style EditorFlexGrid provides the Caption Style editor which allows you to set styling related properties of the column header celland its text The editor comprises of four tabs Text Alignment Border and Background for customizing variousaspects of the header cells

To access the Caption Style editor click smart tag ( ) click the C1FlexGrid Column Tasks option on the task menu toopen column tasks and then go to Caption Style option

FlexGrid for WinForms

25 Copyright copy GrapeCity Inc All rights reserved

Column Style EditorSimilar to Caption Style editor FlexGrid provides another editor the Column Style editor for styling the column textThe editor has got the same options as that of Caption Style editor The only difference is that Caption Style editorcustomizes the column header text while this editor works on the general text in the column cells

To access the Column Style editor click smart tag ( ) click the C1FlexGrid Column Tasks option on the task menu toopen column tasks and then go to Column Style option

FlexGrid for WinForms

26 Copyright copy GrapeCity Inc All rights reserved

データ

This section discusses about various ways to populate data in the FlexGrid control

Topic Snapshot Content

Unbound Mode Discusses how to populate data in the unbound grid

Bound Mode Discusses ways of populating data in the grid through data binding and various operations on bound grid

Binding at design timeBinding at run time using DataSource propertyBinding at run time using SetDataBinding methodOperations in Bound Mode

非連結モード

As the name suggests in unbound mode grid is not bound to any data source and data is stored in the control itselfIn this case you need to provide data by adding rows and columns either at design time or programmatically throughrow and column collections You can also create an empty grid to let user enter the data

An unbound grid is not a very common scenario as grid does not store the data and hence user needs to manage itmanually However unbound grids suits better to some business scenarios like creation and maintenance of recordsFor instance you can use the grid in unbound mode for recording the date-wise sales data or to maintain the dailyinventory changes Below example demonstrates a grid with data populated through code

In C1FlexGrid you can add empty rows or columns by setting the Count property of row or column objects Also youcan use the Add method of these collections to add the empty rows and columns to a grid To set data in the cellsyou can either use the familiar index notation(Item property) or the SetData method For more information on settingdata in the cells see Storing and Retrieving Data

Use the code below to populate data in unbound FlexGrid for WinForms

連結されていない列を追加しますColumn col = _flexColsAdd()colName = colCaption = Unbound_flex[1 Unbound] = 123

C

連結されていない列を追加しますDim col As Column = C1FlexGrid1ColsAdd()colName = UnboundcolCaption = Unbound

VBNET

FlexGrid for WinForms

27 Copyright copy GrapeCity Inc All rights reserved

連結モード

Bound mode as the name suggests refers to a state where grid fetches its data from an underlying data source Databinding also allows multiple data consumers to be connected to a data provider in the synchronized manner

FlexGrid supports data binding to most of the commonly used data sources such as ObservableCollection IListltTgtListltTgt Array BindingSource ADONET objects such as DataSet DataTable etc

There are three ways of binding FlexGrid to a data source

Binding at design timeBinding at run time using DataSource propertyBinding at run time using SetDataBinding method

Binding at Design Time1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Click the Choose Data Source drop down button and select Add Project Data Source option to open the

Data Source Configuration Wizard3 On Choose a Data Source Type page select Database and click Next4 On Choose a Database Model page select Dataset and click Next5 On Choose Your Data Connection page click New Connection to open the Add Connection dialog6 Against the DataSource field click Change button to open the Change Data Source dialog7 Select Microsoft Access Database File and click OK to return to the Add Connection dialog8 Against the Database file name field click Browse and navigate to the database file Provide the User name

and Password if required to connect to the database file This example uses C1NWindmdb file located at thefollowing location by defaultDocumentsComponentOne SamplesCommon

FlexGrid for WinForms

28 Copyright copy GrapeCity Inc All rights reserved

9 Click Test Connection to make sure that you have successfully connected to the database or server and clickOK

10 Click OK again to close the Add Connection dialog box11 Click Next 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 Choose the appropriate option as per your requirement12 Save the connection string in the application configuration file by checking the Yes save the connection as

box and entering a name13 Click Next to switch to the Choose Your Database Objects page14 Choose a table say Products from the Tables node and click Finish15 The above steps add a dataset and connection string to your project Also Visual Studio automatically creates

the following code to fill the dataset

Binding at Run Time Using DataSource PropertyFlexGrid provides the DataSource property to bind the FlexGrid control to a data source at run time You need toassign a data source object to the DataSource property of FlexGrid If the data source object contains more than onetable you can set the DataMember property to table name to specify the target table

Following code uses DataSource property to bind data to the WinForms FlexGrid

Note that the above sample code uses a custom method named GetData to supply data You can set up the datasource as per your requirements Following code shows an example of creating data for WinForms FlexGrid

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移動または削除できます thisproductsTableAdapterFill(thisc1NWindDataSetProducts)

C

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移動または削除できます MeProductsTableAdapterFill(Mec1NWindDataSetProducts)

VBNET

c1FlexGrid1BeginUpdate()C1DataCollectionltCustomergt c1DataCollection = new C1DataCollectionltCustomergt(GetData())c1FlexGrid1DataSource = new C1DataCollectionBindingList(c1DataCollection)c1FlexGrid1EndUpdate()

C

c1FlexGrid1BeginUpdate()Dim c1CollectionView As C1DataCollectionC1DataCollection(Of Customer) = New C1DataCollectionC1DataCollection(Of Customer)(GetData())c1FlexGrid1DataSource = New C1DataCollectionBindingListC1DataCollectionBindingList(c1CollectionView)c1FlexGrid1EndUpdate()

VBNET

ObservableCollectionltCustomergt GetData() var data = new ObservableCollectionltCustomergt() for (int i = 0 i lt 25 i++)

C

FlexGrid for WinForms

29 Copyright copy GrapeCity Inc All rights reserved

Binding at Run Time Using SetDataBinding MethodFlexGrid also provides the SetDataBinding method using which you can set DataSource and DataMember propertiesboth using a single call The following code demonstrates an example of rendering a parent table and its child tablesin different grids with the help of the SetDataBinding method

Below code demonstrates how to bind data to WinForms FlexGrid using SetDataBinding method

dataAdd(new Customer()) return data

Private Function GetData() As ObservableCollection(Of Customer) Dim data = New ObservableCollection(Of Customer)()

For i = 0 To 25 - 1 dataAdd(New Customer()) Next

Return dataEnd Function

VBNET

グリッドにデータセットを連結します_flexCustomersBeginUpdate()_flexCustomersSetDataBinding(ds Customers)_flexCustomersEndUpdate()

_flexOrdersBeginUpdate()_flexOrdersSetDataBinding(ds CustomersCustomerOrders)_flexOrdersEndUpdate()

_flexOrderDetailsBeginUpdate()_flexOrderDetailsSetDataBinding(ds CustomersCustomerOrdersOrderDetails)_flexOrderDetailsEndUpdate()

C

グリッドにデータセットを連結します_flexCustomersBeginUpdate()_flexCustomersSetDataBinding(ds Customers)_flexCustomersEndUpdate() _flexOrdersBeginUpdate()_flexOrdersSetDataBinding(ds CustomersCustomerOrders)_flexOrdersEndUpdate() _flexOrderDetailsBeginUpdate()_flexOrderDetailsSetDataBinding(ds CustomersCustomerOrdersOrderDetails)_flexOrderDetailsEndUpdate()

VBNET

連結モードでの操作

Adding Unbound Column in Bound ModeIn the bound mode grid fetches the data from data source and display it as records and bound columns To add a column to

FlexGrid for WinForms

30 Copyright copy GrapeCity Inc All rights reserved

display data that does not exist in the data source you need to add unbound columns at design time or through code

Adding unbound column at design time

1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Bind the grid control with a data source For detailed steps about how to bind FlexGrid to a data source see Bound

Mode3 Click the Designer option to open the C1FlexGrid Column Editor4 In the right hand side pane select an existing column from the grid preview5 Click Insert Column options in the toolbar to add a column before or after the selection

Adding unbound column through code

FlexGrid provides Add Insert and InsertRange method of the ColumnCollection class to add an unbound column to the gridWhile Add method adds a column at the end the Insert method lets you specify the position where you want to add a newcolumn Similarly you can add multiple columns at a specified position by using the InsertRange method

Use the code below to add unbound column in a bound WinForms FlexGrid

連結されていない列を追加しますColumn col = _flexColsAdd()colName = colCaption = Unbound_flex[1 Unbound] = 123

C

連結されていない列を追加しますDim col As Column = C1FlexGrid1ColsAdd()colName = UnboundcolCaption = Unbound

VBNET

FlexGrid for WinForms

31 Copyright copy GrapeCity Inc All rights reserved

Set Values in Unbound ColumnTo define values in the unbound column of bound grid you need to usethe SetUnboundValue and GetUnboundValue events of the C1FlexGrid class First create a hash table to store the enteredvalues then use the SetUnboundValue event to set unbound value in the hash table using a unique key to identify therecord and use GetUnboundValue event to get the value stored in the hash table using its unique key and set unboundvalue to be displayed in the cell

Following code shows how to set values in an unbound column added to a bound WinForms FlexGrid

Displaying Data in Fixed ColumnTo set values in the fixed columns you need to set DrawMode property of the C1FlexGrid class to OwnerDraw in the formload event and then create the OwnerDrawCell event to set values in the fixed column cells In this example we are settingrow numbers in the fixed column of a bound WinForms FlexGrid

get value from hashtable using ProductID as keyvoid _flex_GetUnboundValue(object sender C1WinC1FlexGridUnboundValueEventArgs e) DataRowView drv = (DataRowView)_flexRows[eRow]DataSource eValue = _hash[drv[ProductID]]

store value in hashtable using ProductID as keyvoid _flex_SetUnboundValue(object sender C1WinC1FlexGridUnboundValueEventArgs e) DataRowView drv = (DataRowView)_flexRows[eRow]DataSource _hash[drv[ProductID]] = eValue

C

Private Sub C1FlexGrid1_GetUnboundValue(sender As Object e As C1WinC1FlexGridUnboundValueEventArgs) Handles C1FlexGrid1GetUnboundValue Dim drv As DataRowView = DirectCast(C1FlexGrid1Rows(eRow)DataSource DataRowView) eValue = _hash(drv(ProductID))End Sub

Private Sub C1FlexGrid1_SetUnboundValue(sender As Object e As C1WinC1FlexGridUnboundValueEventArgs) Handles C1FlexGrid1SetUnboundValue Dim drv As DataRowView = DirectCast(C1FlexGrid1Rows(eRow)DataSource DataRowView) _hash(drv(ProductID)) = eValueEnd Sub

VBNET

FlexGrid for WinForms

32 Copyright copy GrapeCity Inc All rights reserved

Auto-adjust Column WidthFlexGrid provides AutoResize property of the C1FlexGrid class to adjust the width of columns automatically according tothe text length You need to set the property to true before binding it to the data source to load the grid with appropriatecolumn width You can also call AutoSizeCol method to adjust the width of the specified column

Use the code below auto-adjust the column width according to the text in WinForms FlexGrid

Display Bitmap Image in FieldIn most of the scenarios grid directly fetches the images from the data source However if the grid is bound to a databasewhich stores images as OLE objects such as Microsoft Access a little bit of extra processing is required to fetch bitmapimages In such case you need to convert the image data stored as byte array to a memory stream and then usethe OwnerDrawCell event to load the image In the form load event you need to set the DrawMode property toOwnerDraw Also adjust the height of row to display the image properly

Following code demonstrates how to display bitmap image in fields of WinForms FlexGrid

private void C1FlexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if ((eRow gt= thisc1FlexGrid1RowsFixed) amp (eCol == (thisc1FlexGrid1ColsFixed - 1))) eText = eRowToString() または任意のテキスト

C

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If eRow gt= Mec1FlexGrid1RowsFixed And eCol Is Mec1FlexGrid1ColsFixed - 1 Then eText = eRowToString() または任意のテキスト End IfEnd Sub

VBNET

すべての列の幅を自動的に調整します c1FlexGrid1AutoResize = true

4列目の幅を自動調整します c1FlexGrid1AutoSizeColumns(3)

C

すべての列の幅を自動的に調整します c1FlexGrid1AutoResize = True

4列目の幅を自動調整します c1FlexGrid1AutoSizeColumns(3)

VBNET

private void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) if(eMeasuring ampamp eRowgt=c1FlexGrid1RowsFixed ampamp eCol gt=

C

FlexGrid for WinForms

33 Copyright copy GrapeCity Inc All rights reserved

Note that the above sample code uses a custom method LoadImage method to convert the images from byte array to amemory stream

c1FlexGrid1ColsFixed) 「Photo」はblob(byte [])に保存された画像です if (c1FlexGrid1Cols[eCol]Name == Picture) mdbからロードしてみてください eImage = LoadImage(c1FlexGrid1[eRow eCol] as byte[])

画像が表示された場合はテキストを入力しないでください if (eImage = null) eText = null

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) If Not eMeasuring AndAlso eRow gt= c1FlexGrid1RowsFixed AndAlso eCol gt= c1FlexGrid1ColsFixed Then

「Photo」はblob(byte [])に保存された画像です If c1FlexGrid1Cols(eCol)Name Is Picture Then mdbからロードしてみてください eImage = LoadImage(TryCast(c1FlexGrid1(eRow eCol) Byte()))

画像が表示された場合はテキストを入力しないでください If eImage IsNot Nothing Then eText = Nothing End If End IfEnd Sub

VBNET

Image LoadImage(byte[] picData) static Image LoadImage(byte[] picData) これが埋め込みオブジェクトであることを確認してください const int bmData = 78 if (picData == null || picDataLength lt bmData + 2) return null if (picData[0] = 0x15 || picData[1] = 0x1c) return null

現在点ではビットマップのみを処理します if (picData[bmData] = B || picData[bmData + 1] = M) return null

画像をロードします Image img = null try MemoryStream ms = new MemoryStream(picData bmData picDataLength - bmData) img = ImageFromStream(ms) catch

画像を返します return img

C

Private Function LoadImageMethod(ByVal picData As Byte()) As Image

VBNET

FlexGrid for WinForms

34 Copyright copy GrapeCity Inc All rights reserved

Private Shared Function LoadImage(ByVal picData As Byte()) As Image これが埋め込みオブジェクトであることを確認してください Const bmData As Integer = 78 If picData Is Nothing OrElse picDataLength lt bmData + 2 Then Return Nothing If picData(0) ltgt ampH15 OrElse picData(1) ltgt ampH1c Then Return Nothing

現在点ではビットマップのみを処理します If picData(bmData) ltgt Bc OrElse picData(bmData + 1) ltgt Mc Then Return Nothing

画像をロードします Dim img As Image = Nothing

Try Dim ms As MemoryStream = New MemoryStream(picData bmData picDataLength - bmData) img = ImageFromStream(ms) Catch End Try

画像を返します Return imgEnd Function

FlexGrid for WinForms

35 Copyright copy GrapeCity Inc All rights reserved

A grid control is a collection of rows and columns Columns generally contain a particular type of information through out while rows are used to recorddifferent types of information about a particular item

In FlexGrid the collection of columns is represented by the ColumnCollection class which can be accessed through Cols property of the C1FlexGrid class Thissection discusses the various operations that can be performed on columns

Topic Snapshot Content

BasicOperations

Discusses about how to perform basic column operations

Set Column CountAdd ColumnDelete ColumnInsert ColumnSet Data TypeSet Fixed ColumnSet Frozen Column

UserInteraction

Discusses about operations that can be performed by the end user at run time

Allow EditingAllow DraggingAllow FreezingAllow SortingAllow FilteringAllow Resizing

Editors Discusses about various built-in editors of FlexGrid and operations related to them Also discusses how to use customeditors in the FlexGrid

CheckBoxNumericDateComboBoxMaskMapped ListCell Button

Validation Discusses how to apply validation and show error information on FlexGrid cells

Sparkline Discusses about how to display Sparkline charts in FlexGrid cells

Header andFooter

Discusses about how to set column header and footer

Set Header TextMerge column headerWrap column header textStyle Column HeaderSet Column Footer

Sizing Discusses about various aspects of column sizing

Set Column WidthAuto-adjust Column WidthSet MinMax Column WidthStar Sizing

基本操作

This topic discusses various basic operations which can be performed on a column

FlexGrid for WinForms

36 Copyright copy GrapeCity Inc All rights reserved

Set Column CountWhen grid is bound to a data source the number of columns is determined by the number of fields available in thedata source However in the case of unbound mode you can set any arbitrary value in the Count property ofthe ColumnCollection class to set the number of columns to be displayed in the grid

Use the code below to set the number of columns to be added to WinForms FlexGrid in unbound mode

Add ColumnFlexGrid provides two ways to add a new column using the ColumnCollection class You can either use Add methodor increment the value of Count property provided by the class to add new columns Also note that if a new columnis added to a bound grid using these methods it is added as an unbound column only

Following are the two approaches to add column to a WinForms FlexGrid

Delete ColumnTo delete a particular column from the grid you can use Remove method of the ColumnCollection class and specifythe column you want to delete as its parameter In the unbound grid you can also reduce the number of columns bychanging the value of Count property This removes columns from the end of the column collection TheColumnCollection class also provides RemoveRange method which allows you to remove a range of columns

列数を設定します c1FlexGrid1ColsCount = 4

C

列数を設定しますc1FlexGrid1ColsCount = 4

VBNET

方法1 列コレクションのAddメソッドを使用します C1WinC1FlexGridColumn c c = c1FlexGrid1ColsAdd() cCaption = New Column

方法2 列コレクションのCountプロパティを変更します c1FlexGrid1ColsCount += 1 c1FlexGrid1Cols[c1FlexGrid1ColsCount - 1]Caption = New Column

C

方法1 列コレクションのAddメソッドを使用します Dim c As C1WinC1FlexGridColumn c = c1FlexGrid1ColsAdd() cCaption = New Column

方法2 列コレクションのCountプロパティを変更します c1FlexGrid1ColsCount += 1 c1FlexGrid1Cols(c1FlexGrid1ColsCount - 1)Caption = New Column

VBNET

FlexGrid for WinForms

37 Copyright copy GrapeCity Inc All rights reserved

Below code snippet shows all the three approaches to delete column from the WinForms FlexGrid

Insert ColumnTo insert a column in FlexGrid at a specific location you can use Insert method of the ColumnCollection class whichlets you specify the position where columns are to be inserted You can also insert multiple columns in the grid byusing the InsertRange method These methods add the unbound columns only even if the grid is a bound grid

Use any of the following approaches to insert a column in the WinForms FlexGrid at the specified location

方法1 列コレクションのRemoveメソッドを使用して2番目の列を削除します c1FlexGrid1ColsRemove(2)

方法2 Countプロパティを変更して最後の列を削除します c1FlexGrid1ColsCount -= 1

方法3 RemoveRangeメソッドを使用して2番目から始まる4つの列を削除します c1FlexGrid1ColsRemoveRange(2 4)

C

方法1 列コレクションのRemoveメソッドを使用して2番目の列を削除します c1FlexGrid1ColsRemove(2)

方法2 Countプロパティを変更して最後の列を削除します c1FlexGrid1ColsCount -= 1

方法3 RemoveRangeメソッドを使用して2番目から始まる4つの列を削除します c1FlexGrid1ColsRemoveRange(2 4)

VBNET

C1WinC1FlexGridColumn c

方法1 Insertメソッドを使用して2番目の位置に列を挿入します c = c1FlexGrid1ColsInsert(2) cCaption = Inserted Column

方法2 InsertRangeメソッドを使用して2番目の位置に3つの列を挿入します c1FlexGrid1ColsInsertRange(2 3)

C

Dim c As C1WinC1FlexGridColumn 方法1 Insertメソッドを使用して2番目の位置に列を挿入します c = c1FlexGrid1ColsInsert(2) cCaption = Inserted Column 方法2 InsertRangeメソッドを使用して2番目の位置に3つの列を挿入します c1FlexGrid1ColsInsertRange(2 3)

VBNET

FlexGrid for WinForms

38 Copyright copy GrapeCity Inc All rights reserved

Set Data TypeIn case of a bound FlexGrid data type of each bound column is automatically picked from the data source dependingon the data However in the case of unbound mode you can set the data type of columns by specifyingthe DataType property of Column class You can also set the Data Type property at design time by using theColumn Tasks menu For more information on tasks menus see Tasks Menus Note that when a particular data type isset to a FlexGrid column its cells accept the user input of keys accepted by the data type only For instance you cannot input alphabets in a Numeric type cell

Set the data type of an unbound column in WinForms FlexGrid as shown in the code below

Set Fixed ColumnFixed columns refer to the columns with non-editable cells which are always visible in the left hand side of the grideven if user scrolls the grid horizontally In FlexGrid fixed columns can be set using Fixed property ofthe ColumnCollection class This property accepts an integer value that specifies the number of columns to be fixed

Use the code below to set one column as fixed in the WinForms FlexGrid

Set Frozen ColumnFrozen columns similar to fixed columns are non-scrollable but can be edited by the user In FlexGrid frozen columnscan be set by using Frozen property provided by the ColumnCollection class

To set frozen columns in the WinForms FlexGrid use the code below

最初の列のデータ型を設定します c1FlexGrid1Cols[1]DataType = typeof(int)

C

最初の列のデータ型を設定しますc1FlexGrid1Cols(1)DataType = GetType(Integer)

VBNET

1つの列を固定列として設定しますc1FlexGrid1ColsFixed = 1

C

1つの列を固定列として設定しますc1FlexGrid1ColsFixed = 1

VBNET

最初の4列を静止として設定しますc1FlexGrid1ColsFrozen = 4

C

最初の4列を静止として設定しますc1FlexGrid1ColsFrozen = 4

VBNET

FlexGrid for WinForms

39 Copyright copy GrapeCity Inc All rights reserved

ユーザー操作

This topic discusses how you can let end users interact with the FlexGrid columns

Allow EditingBy default FlexGrid allows to edit all columns of the grid However you can choose to disable editing of a particularcolumn by setting AllowEditing property of the Column object to false You can also disable editing of the whole gridby setting the C1FlexGridAllowEditing property to false For more information on editing see Edit

Following code shows how to disable editing of WinForms FlexGrid while keeping only one column editable

Allow DraggingFlexGrid by default allows user to reorder columns by dragging a column header and dropping it to the targetposition However you can change this behavior by using the FlexGridAllowDragging propertyand ColumnAllowDragging property To disable dragging of a particular column you can set theColumnAllowDragging property of that column to false On the other hand setting the FlexGridAllowDraggingproperty to either Rows or None disables the column reordering at grid level This property accepts the valuesfrom AllowDraggingEnum You can also disable column reordering at design time by checking off the Enable ColumnReordering checkbox in the C1FlexGrid Tasks menu For more information on tasks menus see Tasks Menus

グリッド全体で編集を無効にしますc1FlexGrid1AllowEditing = false

3列目でのみ編集を有効にしますc1FlexGrid1Cols[3]AllowEditing = true

C

グリッド全体で編集を無効にしますc1FlexGrid1AllowEditing = False

3列目でのみ編集を有効にしますc1FlexGrid1Cols(3)AllowEditing = True

VBNET

FlexGrid for WinForms

40 Copyright copy GrapeCity Inc All rights reserved

Below code demonstrates how to enable dragging of columns in WinForms FlexGrid

Allow FreezingTo allow end user to freeze the columns at runtime you can use the AllowFreezing property of the C1FlexGrid classwhich accepts values from AllowFreezingEnum When this property is set to Columns or Both a lock sign appearswhen mouse is hovered over the edge of header column User can click and drag the lock sign to freeze the columns

Following code shows how to allow users to freeze the columns in WinForms FlexGrid

Allow PinningFlexGrid lets you allow your users to pin a particular column or column range at run time by using the AllowPinningproperty of the C1FlexGrid class Setting the property adds a Pin button( ) in the column header which allows usersto pin columns at run-time so they remain in view as the user scrolls the grid horizontally The property accepts itsvalues from AllowPinning enumeration which lets you set pinning for a single column or a column range Whenproperty is set to ColumnRange user can pin or unpin all the columns starting from left till the clicked column in onego

グリッド全体ですべての列のドラッグを許可します c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumColumns

特定の列のドラッグを無効にしますc1FlexGrid1Cols[3]AllowDragging = false

C

グリッド全体ですべての列のドラッグを許可します c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumColumns

特定の列のドラッグを無効にします c1FlexGrid1Cols(3)AllowDragging = False

VBNET

実行時に列のフリーズを許可します c1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumColumns

C

実行時に列のフリーズを許可しますc1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumColumns

VBNET

FlexGrid for WinForms

41 Copyright copy GrapeCity Inc All rights reserved

Use the code below to let user pin multiple columns in the WinForms FlexGrid

Allow SortingIn FlexGrid column sorting is enabled for the whole grid by default and value of AllowSorting property of theC1FlexGrid class is set to Auto In this mode user can sort a single column by clicking the column header andmultiple columns by holding the CTRL key while clicking the column headers On sorting multiple columns the gridshows sort index in the column header next to the sort direction glyph You can also choose to prevent sorting orsimply change the way the columns are sorted through AllowSortingEnum enumeration The AllowSortingEnumenumeration allows you to choose whether to auto sort columns sort single column multiple columns or columnrange or just prevent sorting

You can enable multi-column sorting in the WinForms FlexGrid using the code below When AllowSorting propertyis set to MultiColumn user may sort multiple columns by simply clicking on their headers one after the other

ユーザーが列範囲を固定できるようにしますc1FlexGrid1AllowPinning = C1WinC1FlexGridAllowPinningColumnRange

C

ユーザーが列範囲を固定できるようにしますc1FlexGrid1AllowPinning = C1WinC1FlexGridAllowPinningColumnRange

VBNET

グリッドで複数列の並べ替えを有効にしますc1FlexGrid1AllowSorting = C1WinC1FlexGridAllowSortingEnumMultiColumn

1列のみの並べ替えを無効にしますc1FlexGrid1Cols[1]AllowSorting = false

C

グリッドで複数列の並べ替えを有効にしますc1FlexGrid1AllowSorting = C1WinC1FlexGridAllowSortingEnumMultiColumn

1列のみの並べ替えを無効にしますc1FlexGrid1Cols(1)AllowSorting = False

VBNET

FlexGrid for WinForms

42 Copyright copy GrapeCity Inc All rights reserved

To disable sorting on a particular column you need to set the ColumnAllowSorting property of that column to falseFor more information on sorting see Sort

Allow FilteringFlexGrid doesnt allow filtering at runtime by default However you can enable it by settingthe C1FlexGridAllowFiltering property to true To define the type of filter you want to apply on a particularcolumn you can use the ColumnAllowFiltering property which accepts following values from the AllowFilteringenumeration

AllowFiltering Values Description

Default The grid automatically creates a filter of type ColumnFilter This filteris the combination of a value filter and a condition filter

ByValue The grid automatically creates a filter of type ValueFilter This filteroffers a checkbox list of values to choose from Values that are notchecked in the list are excluded from the filter output

ByCondition The grid automatically creates a filter of type ConditionFilter Thisfilter provides several options such as Equals is Greater thanContains Begins with etc to create conditions You can also combinetwo conditions by using the And and Or operators available in thefilter

Custom The grid does not create a filter automatically and allows you to defineyour own filter and then explicitly assign it to Filter property of theColumn class

None Filtering is disabled for the column

For more information on filtering see Filter

Following code shows how to enable filtering in the WinForms FlexGrid and how to apply filters

Allow ResizingBy default FlexGrid allows resizing of all columns of the grid To change this behavior you can use AllowResizingproperty of the C1FlexGrid class This property accepts values from the AllowResizingEnum enumeration which letsyou resize columns rows both or none The enumeration also gives you options to uniformly resize the rows columnsor both that is if you resize one of the columns or rows the grid automatically resizes rest of the columns or rows as

グリッドレベルでのフィルタリングを許可します c1FlexGrid1AllowFiltering = true

最初の列に条件フィルターを適用します c1FlexGrid1Cols[1]AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

C

グリッドレベルでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = True

最初の列に条件フィルターを適用しますc1FlexGrid1Cols(1)AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

VBNET

FlexGrid for WinForms

43 Copyright copy GrapeCity Inc All rights reserved

well FlexGrid also provides ColumnAllowResizing property which is a Boolean type property and lets you enable ordisable resizing of a particular row or column

Below code shows how to allow users to resize columns of WinForms FlexGrid

Enable Context MenuFlexGrid provides support for column context menu at run-time to facilitate quick actions related to columnoperations To enable the column context menu on right-click you need to set ColumnContextMenuEnabled propertyprovided by the C1FlexGrid class to true By default this property is set to false

The column context menu provides following options

Option Description

Sort Ascending Sorts the column in ascending order

Sort Descending Sorts the column in descending order

Group by This Groups the grid data based on column under mouse pointer

列と行のサイズを均一に変更できますc1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumBoth

最初の列のサイズ変更のみを無効にしますc1FlexGrid1Cols[1]AllowResizing = false

C

列と行のサイズを均一に変更できますc1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumBoth

最初の列のサイズ変更のみを無効にしますc1FlexGrid1Cols(1)AllowResizing = False

VBNET

FlexGrid for WinForms

44 Copyright copy GrapeCity Inc All rights reserved

Column

Ungroup Removes grouping from the grid data The option displays only when grid is in groupedstate

Hide this Column Hides the column under mouse pointer

Auto size Resizes the column according to the length of longest value

Auto size (allcolumns)

Resizes all columns according to the length of longest value in each of them

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = true

C

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = True

VBNET

Option Description

エディタ

This topic discusses various built-in editors of FlexGrid and operations related to them The topic also takes you through thesteps to apply custom editors in the FlexGrid columns

Built-in EditorsFlexGrid provides several built-in editors to enable efficient in-cell editing The grid uses TextBox control as its default editorHowever other built-in editors such as numeric date checkbox and combo box are also supported These editors areautomatically assigned generally based on the value of some specific properties such as DataType property of the column Thetable below summarizes the built-in editors provided by FlexGrid their brief description and the example codes demonstratingthem For more information about built-in editors and their customization click the corresponding hyperlink

Built-inEditor

Snapshot Description Sample Code

Checkbox Gets enabledautomatically whenDataType propertyof the Columnobject is set to

c1FlexGrid1Cols[colIndex]DataType =

typeof(Boolean)

FlexGrid for WinForms

45 Copyright copy GrapeCity Inc All rights reserved

Boolean

Numeric Gets enabledautomatically whenDataType propertyis set to a numericdata type such asInt or Decimal

c1FlexGrid1Cols[colIndex]DataType =

typeof(Int32)

Date Gets enabledautomatically if theDataType propertyof column is set toDate or DateTime

c1FlexGrid1Cols[colIndex]DataType =

typeof(DateTime)

ComboBox Gets enabled bysetting multiplevalues separated bypipe inthe ComboListproperty

c1FlexGrid1Cols[colIndex]ComboList =

Red|Green|Blue|Red|White

Mask Gets enabled whenthe EditMaskproperty of columnis set

c1FlexGrid1Cols[colIndex]EditMask =

(999) 999-9999

Mappedlist

Gets enabled whenthe DataMapproperty is set to anIDictionary objectwhich establishesmapping betweenvalues stored in thegrid and thosevisible to a user

ListDictionary customerNames = new

ListDictionary()

customerNamesAdd(AJK18F Sam

Anders)

customerNamesAdd(BBK21D Daneil)

customerNamesAdd(AEF25N Henry

Hussain)

customerNamesAdd(BZD42S Owen

Romanov)

customerNamesAdd(AKC16G Serena

Nguyen)

c1flexGrid1Cols[Name]DataMap =

customerNames

c1flexGrid1ShowButtons =

ShowButtonsEnumWithFocus

Cell Button Gets enabled whenthe ComboListproperty is set to anellipsis() whichautomaticallydisplays a cellbutton in editmode You can then

c1flexGrid1Cols[colIndex]ComboList

=

c1flexGrid1CellButtonClick +=

C1flexGrid1_CellButtonClick

FlexGrid for WinForms

46 Copyright copy GrapeCity Inc All rights reserved

capturethe CellButtonClickevent either toshow a dialog boxor to perform anyother operation

Custom EditorsFlexGrid control provides most of the commonly used editing options through the above-mentioned built-in editors However inaddition you can also use external controls as editors to meet the specialized editing needs Any control that derives from thebase Control class can be easily used as an editor This can be done at design time as well as through code In the examplebelow we are setting the C1ColorPicker control as a cell editor

At Design Time

1 Add the C1FlexGrid control and C1ColorPicker control to the form2 Select Designer option from the C1FlexGrid Tasks menu to open the C1FlexGrid Column Editor3 Select a column and switch to Properties pane on left hand side4 Navigate to the Editor property and set its value to instance of the C1ColorPicker control

At Run Time

To set an external control as editor through code create an instance of the control and assign it to the Editor property ofthe Column object

See the code below to know how to set an external control as editor in WinForms FlexGrid column

カスタムエディタとして使用するC1ColorPickerコントロールのインスタンスを作成します C1WinC1InputC1ColorPicker customeditor = new C1WinC1InputC1ColorPicker() カスタムエディタにEditorプロパティを割り当てます c1FlexGrid1Cols[1]Editor = customeditor

C

FlexGrid for WinForms

47 Copyright copy GrapeCity Inc All rights reserved

For controls which are not derived from the Control base class it is still possible to use them as editors usingIC1EmbeddedEditor interface You can even use the UITypeEditor classes as grid editors This way the FlexGrid control canuse virtually any control as a cell editor For more information about the implementation see the product sample named CustomEditors

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

カスタムエディタとして使用するC1ColorPickerコントロールのインスタンスを作成します Dim customeditor As C1WinC1InputC1ColorPicker = New C1WinC1InputC1ColorPicker()

カスタムエディタにEditorプロパティを割り当てます c1FlexGrid1Cols(1)Editor = customeditor

VBNET

チェックボックス

Display Checkbox for Boolean ValuesFlexGrid by default uses the checkbox editor for representing the Boolean values That is when the DataTypeproperty of a Row or Column object is set to Bool type a checkbox appears in the cells and user can toggle the valueof an editable cell simply by clicking it

To disable this default behavior and display text value instead of a checkbox in a Bool type you can set the Formatproperty of Row or Column object to string values

Default Checkbox Checkbox with Text Checkbox with Non-Boolean Value Three-state Checkbox

Use the code below to set checkbox type editor in a WinForms FlexGrid column and configure it further

データ型をブール値に設定します(チェックボックスを自動的に表示します)c1FlexGrid1Cols[Verified]DataType = typeof(Boolean)

チェックボックスを表示する代わりに文字列値を表示しますc1flexGrid1Cols[Verified]Format = YesNo ブール列のチェックボックスの横にあるテキストを有効にしますc1flexGrid1Cols[Verified]ImageAndText = true

C

データ型をブール値に設定します(チェックボックスを自動的に表示します)c1FlexGrid1Cols(Verified)DataType = GetType(Boolean)

チェックボックスを表示する代わりに文字列値を表示しますc1flexGrid1Cols(Verified)Format = YesNo

ブール列のチェックボックスの横にあるテキストを有効にしますc1flexGrid1Cols(Verified)ImageAndText = True

VBNET

FlexGrid for WinForms

48 Copyright copy GrapeCity Inc All rights reserved

Display Checkbox for Non-Boolean ValuesIn unbound mode you can display a checkbox along with any non-boolean text as well You can use the SetCellCheckmethod to add checkbox to any kind of cells Along with row and column index this method takes valueof CheckEnum enumeration as one of its parameters to specify the state of checkbox at the time of rendering

Following code demonstrates how you can display checkbox for non-boolean values

Set Checkbox AlignmentTo set position of checkbox in the cell you need to use ImageAlign property of the Row or Column object Thisproperty accepts values from the ImageAlignEnum enumeration which lets you hide tile stretch or position the image

Align the checkbox to display in center of a WinForms FlexGrid column using the code below

Change the Checkbox ImageTo change icon image of different states of checkbox you can use the GlyphEnum which can be accessed usingthe Glyphs property For more information about changing glyphs see Custom Glyphs

You can change the images to be used for various checkbox states in WinForms FlexGrid using the code below

チェックオン状態のセル(32)に2つの状態のチェックボックスを設定します c1flexGrid1SetCellCheck(3 2 CheckEnumChecked)

C

チェックオン状態のセル(32)に2つの状態のチェックボックスを設定しますc1flexGrid1SetCellCheck(3 2 CheckEnumChecked)

VBNET

チェックボックスをセルの右中央に揃えますc1flexGrid1Cols[Verified]ImageAlign = ImageAlignEnumRightCenter

C

チェックボックスをセルの右中央に揃えますc1flexGrid1Cols(Verified)ImageAlign = ImageAlignEnumRightCenter

VBNET

カスタム画像をチェックボックスアイコンとして設定します Image imgChk = new Bitmap(ResourcesImagescheckedpng) Image imgUnchk = new Bitmap(ResourcesImagesuncheckedpng) Image imgGray = new Bitmap(ResourcesImagesnullpng) c1flexGrid1Glyphs[GlyphEnumChecked] = imgChk c1flexGrid1Glyphs[GlyphEnumUnchecked] = imgUnchk c1flexGrid1Glyphs[GlyphEnumGrayed] = imgGray

C

カスタム画像をチェックボックスアイコンとして設定します Dim imgChk As Image = New Bitmap(ResourcesImagescheckedpng) Dim imgUnchk As Image = New Bitmap(ResourcesImagesuncheckedpng)

VBNET

FlexGrid for WinForms

49 Copyright copy GrapeCity Inc All rights reserved

Use Three State CheckboxIn addition to usual two state checkbox FlexGrid lets you create three state checkbox as well The simplest way ofenabling the third state is through the CheckEnum While a Boolean checkbox togglesbetween CheckEnumChecked and CheckEnumUnchecked states the three states of a three state checkbox arerepresented by CheckEnumTSChecked CheckEnumTSUnchecked and CheckEnumTSGrayed However in thiscase by default user can not go back to null after switching to checked or unchecked state once In order to cycle acheckbox between three states you need to handle the ValidateEdit event

Use the code below to create a three state checkbox in the WinForms FlexGrid

Dim imgGray As Image = New Bitmap(ResourcesImagesnullpng) c1flexGrid1Glyphs(GlyphEnumChecked) = imgChk c1flexGrid1Glyphs(GlyphEnumUnchecked) = imgUnchk c1flexGrid1Glyphs(GlyphEnumGrayed) = imgGray

private void c1FlexGrid1_ValidateEdit(object sender ValidateEditEventArgs e) if (c1FlexGrid1Cols[eCol]Name == Done) eCancel = true if (c1FlexGrid1[eRow eCol]Equals(false)) c1FlexGrid1[eRow eCol] = true else if (c1FlexGrid1[eRow eCol]Equals(true)) c1FlexGrid1[eRow eCol] = DBNullValue else if (c1FlexGrid1[eRow eCol]Equals(DBNullValue)) c1FlexGrid1[eRow eCol] = false

C

Private Sub c1FlexGrid1_ValidateEdit(ByVal sender As Object ByVal e As ValidateEditEventArgs) If c1FlexGrid1Cols(eCol)Name Is Done Then eCancel = True

If c1FlexGrid1(eRow eCol)Equals(False) Then c1FlexGrid1(eRow eCol) = True ElseIf c1FlexGrid1(eRow eCol)Equals(True) Then c1FlexGrid1(eRow eCol) = DBNullValue ElseIf c1FlexGrid1(eRow eCol)Equals(DBNullValue) Then c1FlexGrid1(eRow eCol) = False End If End IfEnd Sub

VBNET

数値

FlexGrid by default uses the numeric editor to edit the numeric data that is when the data type is set to any of the numeric types such as Int and Decimal Thisbehavior of FlexGrid is controlled by the EditOptions property which provides various editing options through the EditFlags enumeration One of the flagsprovided is UseNumericEditor As the default value of EditOptions property is All UseNumericEditor flag is always ON and hence grid automatically enablesthe numeric editor while editing the numeric data You can access the EditOptions property at design time as well as through code

FlexGrid for WinForms

50 Copyright copy GrapeCity Inc All rights reserved

Numeric Editor Numeric Editor with Format = C0 Numeric Editor with Spin Button Numeric Editor with Calculator

At Design Time

To enable or disable the numeric editor at design time you can access the EditOptions property from the Properties window

At Run Time

At run-time you need to set the UseNumericEditor flag On in the EditOptions property Use the code below to set EditOptions property in the WinFormsFlexGrid

Format Numeric CellTo format the data in a numeric cell FlexGrid provides the Format property of Column as well as Row object In case of the formats that support decimal valuessuch as numeric currency and exponential FlexGrid displays values up to two decimal places by default However you can specify the number of decimals todisplay by appending the value of Format property with that number For instance in order to display values up to three decimal places in a Number type cellyou specify value of Format property as N3 or n3

Note This property doesnt have any effect on the stored value but only on how value is displayed at the run time You can access the formatted valueof a cell using GetDataDisplay(Int32 Int32) method of the C1FlexGrid class

You can set the Format property at design time as well as through code Following table lists the commonly used formats for numeric cells

Format Value Description

Number N or n Specifies the formatting for simple numeric values

Currency C or c Specifies the formatting for monetary values

Exponential or Scientific E or e Specifies the formatting for values using scientific notations

Percentage P or p Specifies the formatting for percentage values

Custom User-defined Takes the value of format string from user

A custom string might require handling in the code

At Design Time

1 In design view click on the FlexGrid smart tag to open the C1FlexGrid Tasks menu2 Click the Column Tasks option and navigate to Format String property3 Click ellipsis button to open the Format String dialog

すべてのフラグをオンに設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsAll

UseNumericEditorフラグのみを設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsUseNumericEditor

C

すべてのフラグをオンに設定しますc1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsAll

UseNumericEditorフラグのみを設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsUseNumericEditor

VBNET

FlexGrid for WinForms

51 Copyright copy GrapeCity Inc All rights reserved

4 Select the required format from the list box on left say Currency5 Set the format specific properties on the right hand side of the dialog Decimal places in this case

At Run Time

To specify the format of a particular numeric type column set the Format property to any of the above mentioned values In this example we have set theformat of column 3 as currency without decimals

Following code shows how to set the format of a WinForms FlexGrid column

Input using Spin ButtonTo create a numeric editor which uses a spin button for input you need to assign instance of an external control such as NumericUpDown to the Editorproperty

Use the code below to create a numeric editor with spin button in the WinForms FlexGrid

Input using CalculatorTo allow user to give input using a calculator in a numeric editor you can use the C1NumericEdit control of C1Input library as an editor So just add thereference to C1WinC1Input and assign an instance of C1NumericEdit control to the Editor property For more information about using an external controlas editor see Custom Editors

To create a numeric editor with calculator use the code below

小数点なしの通貨形式を設定します c1FlexGrid1Cols[3]Format = C0

C

小数点なしの通貨形式を設定しますc1FlexGrid1Cols(3)Format = C0

VBNET

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols[2]Editor = new NumericUpDown()

C

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols(2)Editor = New NumericUpDown()

VBNET

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols[2]Editor = new C1NumericEdit()ShowUpDownButtons=false

C

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols(2)Editor = New C1NumericEdit() With ShowUpDownButtons = False

VBNET

日付

FlexGrid by default uses the Date editor for all the Date and DateTime type of data The Date editor consists of adropdown which opens a calendar when clicked and user can select the desired date by navigating through it Usercan also change the date month or year by simply selecting the corresponding part in the editor and pressing the upand down arrow keys

FlexGrid for WinForms

52 Copyright copy GrapeCity Inc All rights reserved

Default Date Editor Date Editor Without Calendar Date Editor with Spin Button

Use the code below to create a Date editor in a WinForms FlexGrid column

Input without Displaying CalendarAs mentioned earlier in FlexGrid a DateTime type cell automatically displays a dropdown calendar to receive theinput from user However in order to get a date input from user without displaying a calendar you can set a maskusing the EditMask property and then validate the input value using the ValidateEdit event

Following code demonstrates how to create a Date editor without calendar in WinForms FlexGrid

For more information about cell masks and validation see topics Mask and Validation respectively Another way ofhiding the calendar is to get user input using the spin buttons

Input using Spin ButtonBelow code shows how to create Date editor with spin button

To display spin buttons in a Date editor use the SetupEditor event to convert the editor into DateTimePicker and setits ShowUpDown property to true

Set the data type property to DateTime c1FlexGrid1Cols[1]DataType = typeof(DateTime)

C

Set the data type property to DateTimec1FlexGrid1Cols(1)DataType = GetType(Date)

VBNET

Set a mask on column c1flexGrid1Cols[3]EditMask = 00000000

C

Set a mask on columnc1flexGrid1Cols(3)EditMask = 00000000

VBNET

private void C1flexGrid1_SetupEditor(object sender RowColEventArgs e)

C

FlexGrid for WinForms

53 Copyright copy GrapeCity Inc All rights reserved

Set Date FormatTo set the format in a Date type column you need to set the Format property of the Column object

Following table lists the pre-defined formats

Format Value Example

Short Date d 11192003

Long Date D Friday November 19 2003

Short Time t 1215 AM

Long Time T 121530 AM

You can also create a custom format using the various custom format specifiers supported in the Net framework Fordetails see Custom date and time format strings on Microsoft website

Use the following code to create a custom date format in WinForms FlexGrid column

if (c1flexGrid1Cols[eCol]Name == DOB) Cast FlexGrids current cell editor var dateEditor = c1flexGrid1Editor as DateTimePicker

Show UpDown button (replacing the drop-down button for calendar) dateEditorShowUpDown = true

Private Sub C1flexGrid1_SetupEditor(ByVal sender As Object ByVal e As RowColEventArgs) If c1flexGrid1Cols(eCol)Name Is DOB Then Cast FlexGrids current cell editor Dim dateEditor = TryCast(c1flexGrid1Editor DateTimePicker)

Show UpDown button (replacing the drop-down button for calendar) dateEditorShowUpDown = True End IfEnd Sub

VBNET

Set a pre-defined format c1FlexGrid1Cols[DOB]Format = d Set a custom format c1FlexGrid1Cols[OrderDate]Format = ddMMyyyy

C

Set a pre-defined format c1FlexGrid1Cols(DOB)Format = d

Set a custom format c1FlexGrid1Cols(OrderDate)Format = ddMMyyyy

VBNET

FlexGrid for WinForms

54 Copyright copy GrapeCity Inc All rights reserved

Display Country-specific Date FormatAlthough abovementioned formats are the most commonly used date formats but there are cultures which preferusing their specific calendar and date formats in some cases such as Japan You can display those specific calendarsand date formats by using OwnerDrawCell event of the C1FlexGrid class and the SystemGlobalization namespaceThe namespace provides various classes to define culture related information including calendars and date formatsFor instance to display Japanese calendar and Japanese date format you can leveragethe SystemGlobalizationJapaneseCalendar class Similarly you can also display other calendars such as GregorianHebrew Hijri and Korean

Set the country specific date format in WinForms FlexGrid using the code below

Set MinMax DateTo set a range of valid values you can use the DateTimePicker control as editor and set its MinDate and MaxDate

c1flexGrid1Cols[DOB]Format = ddMMyyyy c1flexGrid1DrawMode = DrawModeEnumOwnerDraw c1flexGrid1OwnerDrawCell += C1flexGrid1_OwnerDrawCell private void C1flexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if (c1flexGrid1Cols[eCol]DataType == typeof(DateTime) ampamp eRow gt= c1flexGrid1RowsFixed) eText = DateTimeParse(eText)ToString(yyyy年MM月dd日(dddd) c)

C

C1FlexGrid1Cols(DOB)Format = ddMMyyyy C1FlexGrid1DrawMode = DrawModeEnumOwnerDraw

AddHandler C1FlexGrid1OwnerDrawCell AddressOf C1flexGrid1_OwnerDrawCell

Private Sub C1flexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If C1FlexGrid1Cols(eCol)DataType = GetType(DateTime) AndAlso eRow gt= C1FlexGrid1RowsFixed Then eText = DateTimeParse(eText)ToString(yyyy年MM月dd日(dddd) c) End If End Sub

VBNET

FlexGrid for WinForms

55 Copyright copy GrapeCity Inc All rights reserved

property

Use the code below to set a range of valid dates in WinForms FlexGrid

DateTimePicker dateTimePicker = new DateTimePicker() dateTimePickerFormat = DateTimePickerFormatShort

Sets Max and Min dates dateTimePickerMinDate = new DateTime(2015 05 01) dateTimePickerMaxDate = DateTimeToday

Assigns DateTimePicker control as editor for FirstOrderDate(date) column c1flexGrid1Cols[FirstOrderDate]Editor = dateTimePicker

C

Dim dateTimePicker As DateTimePicker = New DateTimePicker() dateTimePickerFormat = DateTimePickerFormat[Short]

Sets Max and Min dates dateTimePickerMinDate = New DateTime(2015 05 01) dateTimePickerMaxDate = DateToday

Assigns DateTimePicker control as editor for FirstOrderDate(date) column c1flexGrid1Cols(FirstOrderDate)Editor = dateTimePicker

VBNET

コンボボックス

ComboBox cell is a common way of providing the user with a well-defined list of possible values in the form of a drop-down list FlexGrid providesthis multi-option editor in various forms such as dropdown list dropdown combo ellipsis button or a textbox with ellipsis button

Default ComboBox Multi-column ComboBox ComboBox with custom BackColor ComboBox with Images

Display Dropdown List or ComboIn FlexGrid you can create a dropdown list by creating a string containing all the choices separated by pipe characters (for exampleTrue|False|Dont know) and assign it to the ComboList property of Row or Column object This causes the grid to display a drop-down buttonnext to the cell The user can click the dropdown button (or press F2) to display the list of choices available for that cell

Another common situation is where cells have a list of common values but users should be allowed to type a custom value as well This can beaccomplished with drop-down combos a combination of text box and drop-down list In FlexGrid you can create combos by starting the choicelist with a pipe character (for example |True|False|Dont know) and then assign it to the ComboList property

Following code shows how to create a dropdown list or combo editor in the WinForms FlexGrid

FlexGrid for WinForms

56 Copyright copy GrapeCity Inc All rights reserved

The ComboList property can also be set using the Combo List dialog at design time To access the Combo List dialog

1 Open the Column Tasks menu for column for which editor is to be set2 Go to the Combo List option and click the ellipsis button on the right hand side of the field3 Combo List dialog opens where you can specify the option values each in a new line4 You can also choose whether you want to display these values as a Dropdown List or Dropdown Combo Note that it also lets you create

cell button using Ellipsis Button or Textbox amp Ellipsis Button option

Display Multi-column ComboBoxIn FlexGrid you can also display multiple columns in a ComboBox using the MultiColumnDictionary class This class implementsthe IC1MultiColumnDictionary interface and has multiple overloads These overloads let you specify the data source object the key columncolumns that are to be displayed in multiple columns and the column to be displayed when ComboBox is closed

Display a multi-column combobox in a WinForms FlexGrid column using the code below

Note that the above code uses the data source object dt to supply data to the grid You can set up the data source as per your requirements

ドロップダウンリストとしてCustomerIDを割り当てますc1flexGrid1Cols[CustomerID]ComboList = AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

ドロップダウンコンボボックスとしてCustomerIDを割り当てパイプ文字|でリストを開始します c1flexGrid1Cols[CustomerID]ComboList = |AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

C

ドロップダウンリストとしてCustomerIDを割り当てますc1flexGrid1Cols(CustomerID)ComboList = AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

ドロップダウンコンボボックスとしてCustomerIDを割り当てパイプ文字|でリストを開始します c1flexGrid1Cols(CustomerID)ComboList = |AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

VBNET

string[] columnRange = new string[] City Country c1FlexGrid1Cols[City]DataMap = new MultiColumnDictionary(dt City columnRange 0)

C

Dim columnRange = New String() City Countryc1FlexGrid1Cols(City)DataMap = New MultiColumnDictionary(dt City columnRange 0)

VBNET

DataTable dt = new DataTable() dtColumnsAdd(CustomerID typeof(int)) dtColumnsAdd(ContactName typeof(string)) dtColumnsAdd(Designation typeof(string)) dtColumnsAdd(City typeof(string)) dtColumnsAdd(Country typeof(object))

サンプルデータ

C

FlexGrid for WinForms

57 Copyright copy GrapeCity Inc All rights reserved

Set Mapped Data in the ComboBoxTo set a ComboBox having display values different from the actual values you need to use the C1ComboBox as editor and leverageits ItemsDisplayMember and ItemsValueMember properties For instance the example below uses country names as display values while actualvalue is the dialing code of the corresponding country

Following code shows how to set the mapped data in combobox column of the WinForms FlexGrid

dtRowsAdd(1 Maria Anders Sales Representative Madrid Spain ) dtRowsAdd(2 Ana Trujillo Sales Associate Monterrey Mexico ) dtRowsAdd(3 Antonio Moreno Owner Dublin Ireland) dtRowsAdd(4 Thomas Hardy Sales Representative Bristol UK) dtRowsAdd(5 Patricio Simpson Marketing Manager Munich Germany) dtRowsAdd(6 Paolo Accorti Sales Representative Barcelona Spain) dtRowsAdd(7 Martine Ranceacute Owner Puebla Mexico) dtRowsAdd(8 Elizabeth Brown Marketing Manager London UK) dtRowsAdd(9 Jaime Yorres Order Administrator Vienna Austria) dtRowsAdd(10 Yvonne Moncada Marketing Manager Mexico Mexico) dtRowsAdd(11 Helen Bennett OwnerMarketing Cork Ireland) dtRowsAdd(12 Sergio Gutieacuterrezy Order Administrator Sao Paulo Brazil)

c1FlexGrid1DataSource = dt

Dim dt As DataTable = New DataTable()dtColumnsAdd(CustomerID GetType(Integer))dtColumnsAdd(ContactName GetType(String))dtColumnsAdd(Designation GetType(String))dtColumnsAdd(Country GetType(Object))dtColumnsAdd(City GetType(String))

サンプルデータdtRowsAdd(1 Maria Anders Sales Representative Spain Madrid)dtRowsAdd(2 Ana Trujillo Sales Associate Mexico Monterrey)dtRowsAdd(3 Antonio Moreno Owner Ireland Dublin)dtRowsAdd(4 Thomas Hardy Sales Representative UK Bristol)dtRowsAdd(5 Patricio Simpson Marketing Manager Germany Munich)dtRowsAdd(6 Paolo Accorti Sales Representative Spain Barcelona)dtRowsAdd(7 Martine Ranceacute Owner Mexico Puebla)dtRowsAdd(8 Elizabeth Brown Marketing Manager UK London)dtRowsAdd(9 Jaime Yorres Order Administrator Austria Vienna)dtRowsAdd(10 Yvonne Moncada Marketing Manager Mexico Mexico)dtRowsAdd(11 Helen Bennett OwnerMarketing Ireland Cork)dtRowsAdd(12 Sergio Gutieacuterrezy Order Administrator Brazil Sao Paulo)c1FlexGrid1DataSource = dt

VBNET

private void Form1_Load(object sender EventArgs e) 顧客データを取得します Customers = GetCustomers()

FlexGridにデータを入力します c1FlexGrid1DataSource = Customers

国とその国コードのコレクションを作成します ObservableCollectionltCountrygt countries = new ObservableCollectionltCountrygt() countriesAdd(new Country(1 USA)) countriesAdd(new Country(91 India)) countriesAdd(new Country(7 Russia))

C

FlexGrid for WinForms

58 Copyright copy GrapeCity Inc All rights reserved

Set ComboBox DimensionsTo set the height and width of combo box dropdown you need to assign an instance of ComboBox as an editor and then setthe DropDownHeight and DropDownWidth property of that instance

countriesAdd(new Country(54 Argentina)) countriesAdd(new Country(81 Japan)) countriesAdd(new Country(380 Ukraine)) countriesAdd(new Country(98 Iran)) countriesAdd(new Country(45 Denmark)) countriesAdd(new Country(84 Vietnam)) countriesAdd(new Country(49 Germany)) BindingSource countryBS = new BindingSource() countryBSDataSource = countries

C1Comboboxコントロールをインスタンス化して設定します C1ComboBox countryCodeCombo = new C1ComboBox() countryCodeComboItemsDataSource = countryBS

region Mapped Data using C1Combobox

国コードと国名をマッピングするためにプロパティを設定します countryCodeComboItemsDisplayMember = CountryName countryCodeComboItemsValueMember = CountryCode countryCodeComboTextDetached = true countryCodeComboTranslateValue = true

C1ComboboxをDiallingCode列のエディタとして設定します c1FlexGrid1Cols[DiallingCode]Editor = countryCodeCombo endregion

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) 顧客データを取得します Customers = GetCustomers()

FlexGridにデータを入力します c1FlexGrid1DataSource = Customers

国とその国コードのコレクションを作成します Dim countries As ObservableCollection(Of Country) = New ObservableCollection(Of Country)() countriesAdd(New Country(1 USA)) countriesAdd(New Country(91 India)) countriesAdd(New Country(7 Russia)) countriesAdd(New Country(54 Argentina)) countriesAdd(New Country(81 Japan)) countriesAdd(New Country(380 Ukraine)) countriesAdd(New Country(98 Iran)) countriesAdd(New Country(45 Denmark)) countriesAdd(New Country(84 Vietnam)) countriesAdd(New Country(49 Germany)) Dim countryBS As BindingSource = New BindingSource() countryBSDataSource = countries

C1Comboboxコントロールをインスタンス化して設定します Dim countryCodeCombo As C1ComboBox = New C1ComboBox() countryCodeComboItemsDataSource = countryBS

国コードと国名をマッピングするためにプロパティを設定します countryCodeComboItemsDisplayMember = CountryName countryCodeComboItemsValueMember = CountryCode countryCodeComboTextDetached = True countryCodeComboTranslateValue = True

C1ComboboxをDiallingCode列のエディタとして設定します c1FlexGrid1Cols(DiallingCode)Editor = countryCodeComboEnd Sub

VBNET

FlexGrid for WinForms

59 Copyright copy GrapeCity Inc All rights reserved

Use the code below to specify the height and width of the combobox to be displayed in the WinForms FlexGrid

Change Background Color or Font ColorTo change the background color or font color of the ComboBox list create an instance of ComboBox to assign it as editor Then set the BackColorand ForeColor property of that instance

Customize combobox in the WinForms FlexGrid by using the code below

Display Image in the ListTo display images in the ComboBox list you need to use the C1ComboBox as an editor and leverage its ItemsImageList property This property isof type ImageList class that acts as a container for the images which are stored in its Images collection First access the images stored in theproject resources through the ResourceManagerGetResourceSet method and create a collection of mapping between images and itscorresponding names The collection acts as a data source for ComboBox Now create an instance of the ImageList class add images to itsImages collection from data source and assign that instance of ImageList class to the ItemsImageList property to render images in the ComboBoxlist

Following code shows how to display images in the combobox lists of WinForms FlexGrid

ComboBox cb = (ComboBox)c1flexGrid1Editor cbDropDownWidth = 250 cbDropDownHeight = 200

C

Dim cb As ComboBox = CType(c1flexGrid1Editor ComboBox) cbDropDownWidth = 250 cbDropDownHeight = 200

VBNET

ComboBox comboBox = new ComboBox() comboBoxBackColor = ColorBlack comboBoxForeColor = ColorWhite

C

Dim comboBox As ComboBox = New ComboBox() comboBoxBackColor = ColorBlack comboBoxForeColor = ColorWhite

VBNET

コンボボックスに画像を入力します var itemsSource = new ListltFlaggt() ImageList imgFlag = new ImageList() imgFlagImagesClear() var rsrSet = ResourcesResourceManagerGetResourceSet(CultureInfoCurrentCulture true true)

foreach(DictionaryEntry entry in rsrSet) var img = entryValue as Image itemsSourceAdd(new Flag(entryKeyToString() img)) itemsSourceSort(new CompareFlag())

foreach (Flag entry in itemsSource) imgFlagImagesAdd(entryCountryName entryCountryFlag)

countryComboItemsImageList = imgFlag

C

FlexGrid for WinForms

60 Copyright copy GrapeCity Inc All rights reserved

Set Number of Displayed ItemsTo set the number of items to be displayed in a combo box you can use ComboBoxMaxDropDownItems property

Use the code below to limit the number of items to be displayed in combobox list of the WinForms FlexGrid

Sort the ComboBox ListTo sort the items in the ComboBox dropdown list you can use the C1ComboBox as editor and call the Sort method to sort the dropdown itemsgetting displayed in the ComboBox

To display sorted items in comboboxlist of the WinForms FlexGrid use the code below

countryComboItemMode = ComboItemModeHtmlPattern countryComboHtmlPattern = ltdiv ltdiv style=padding0pxgtltimg src=CountryName style=padding-right14pxgtCountryNameltdivgt

コンボボックスに画像を入力します Dim itemsSource = New List(Of Flag)()Dim imgFlag As ImageList = New ImageList()imgFlagImagesClear()Dim rsrSet = ResourcesResourceManagerGetResourceSet(CultureInfoCurrentCulture True True)

For Each entry As DictionaryEntry In rsrSet Dim img = TryCast(entryValue Image) itemsSourceAdd(New Flag(entryKeyToString() img))Next

itemsSourceSort(New CompareFlag())

For Each entry In itemsSource imgFlagImagesAdd(entryCountryName entryCountryFlag)Next

countryComboItemsImageList = imgFlagcountryComboItemMode = ComboItemModeHtmlPatterncountryComboHtmlPattern = ltdiv ltdiv style=padding0pxgtltimg src=CountryName style=padding-right14pxgtCountryNameltdivgt

VBNET

コンボボックスのドロップダウンに表示する国の数を設定します countryComboMaxDropDownItems = 10

C

コンボボックスのドロップダウンに表示する国の数を設定しますcountryComboMaxDropDownItems = 10

VBNET

C1ComboBox countryCombo = new C1ComboBox() countryComboDropDownStyle = DropDownStyleDropDownList Listltstringgt countries = new Listltstringgt USA Canada India Russia Japan Germany countriesSort() countryComboItemsDataSource = countries

C1ComboboxをCountry列のエディタとして設定します c1FlexGrid1Cols[Country]Editor = countryCombo

C

FlexGrid for WinForms

61 Copyright copy GrapeCity Inc All rights reserved

Get the Selected IndexTo get the selected index or value of the selected item you can use the SelectedIndex property or SelectedItem property of the ComboBoxEditorclass The example below uses the ComboCloseUp event to show a message box displaying the selected index and the selected item

Use the code below to fetch the index and value of selected item in combobox list of the WinForms FlexGrid

Dim countryCombo As C1ComboBox = New C1ComboBox() countryComboDropDownStyle = DropDownStyleDropDownList Dim countries As List(Of String) = New List(Of String) From USA Canada India Russia Japan Germany countriesSort() countryComboItemsDataSource = countries

C1ComboboxをCountry列のエディタとして設定します c1FlexGrid1Cols(Country)Editor = countryCombo

VBNET

private void C1FlexGrid1_ComboCloseUp(object sender C1WinC1FlexGridRowColEventArgs e) MessageBoxShow(Selected Index + c1FlexGrid1ComboBoxEditorSelectedIndex + n + Selected Item + c1FlexGrid1ComboBoxEditorSelectedItem)

C

Private Sub C1FlexGrid1_ComboCloseUp(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) MessageBoxShow(Selected Index amp c1FlexGrid1ComboBoxEditorSelectedIndex amp vbLf amp Selected Item + c1FlexGrid1ComboBoxEditorSelectedItem)End Sub

VBNET

マスク

Mask editor refers to pre-defined templates for getting input from users which also automatically validates the userinput as it is typed Mask strings have two types of characters literal characters and template characters While literalcharacters are the ones which become part of the input the template characters serve as placeholders for charactersbelonging to specific categories (for example digits or alphabets) For example the code below assigns a (999) 999-9999 editing mask to the first column which holds phone numbers Here special characters such as braces (()) andhyphen (-) are the literals and the digit 9 is a placeholder that stands for any digit

FlexGrid for WinForms

62 Copyright copy GrapeCity Inc All rights reserved

The FlexGrid control supports masked editing through the EditMask property which can be used with regular textfields and with drop-down combo fields To apply different masks within the same column you can trap the BeforEditevent and set the EditMask property to appropriate value

You can also set the EditMask property at design time using the Input Mask dialog You can access the dialog byclicking the ellipsis button against Edit Mask field in Column Tasks menu It also means that the Edit Mask field isspecific to the column selected at that time

Note that when the EditMask property is set to a non-empty string the grid uses the masked editor even if thecolumn contains DateTime values Usually grid uses the built-in Date editor to edit DateTime type cells

電話番号の編集マスクを設定します c1FlexGrid1Cols(1)EditMask = (999) 999-9999

C

電話番号の編集マスクを設定します c1FlexGrid1Cols(1)EditMask = (999) 999-9999

VBNET

マップリスト

Mapped lists refer to the mapping of data stored in the grid to the values visible to the user Such mapping is oftenused to display user-friendly values when actual data stored in the grid is either encoded or difficult to understand bythe user For instance in an employee record table it would be more convenient for administrative executive to seenames of the employees while database stores the employee IDs

FlexGrid for WinForms

63 Copyright copy GrapeCity Inc All rights reserved

Display Data MappingIn FlexGrid data mapping can be achieved by using the DataMap property This property contains reference to anIDictionary object that establishes mapping between database values and values to be displayed in the gridHashTable ListDictionary and SortedList are some examples of IDictionary objects which provide valid data maps

Following code demonstrates how to display the data mapped list in the WinForms FlexGrid

There is a difference in how HashTable ListDictionary and SortedList classes order the items So when these tables areused with editable columns the order of items rendering in the mapped list also differs depending upon the keys andclass used to create the list

Note that the keys in the data map must be of the same type as the cells being edited For example if a columncontains short integers (Int16) then any data maps associated with the column should have short integer keys

Display Image MappingTo display image mapping in a FlexGrid column you need to set the ImageMap property of Row or Column object toan IDictionary object that establishes mapping between images and the corresponding text values For example if acolumn contains country names you can use this property to display the corresponding flags You can controlwhether to show only images or images with text by using the ImageAndText property of the object

Create an image mapping in the WinForms FlexGrid using the code below

データマップを作成しますListDictionary customerNames = new ListDictionary()customerNamesAdd(AJK18F Sam Anders)customerNamesAdd(BBK21D Daneil)customerNamesAdd(AEF25N Henry Hussain)customerNamesAdd(BZD42S Owen Romanov)customerNamesAdd(AKC16G Serena Nguyen)

データマップをflexgrid列に割り当てますc1flexGrid1Cols[Name]DataMap = customerNames

C

データマップを作成しますDim customerNames As ListDictionary = New ListDictionary()customerNamesAdd(AJK18F Sam Anders)customerNamesAdd(BBK21D Daneil)customerNamesAdd(AEF25N Henry Hussain)customerNamesAdd(BZD42S Owen Romanov)customerNamesAdd(AKC16G Serena Nguyen)

データマップをflexgrid列に割り当てますc1flexGrid1Cols(Name)DataMap = customerNames

VBNET

Hashtable ht = new Hashtable() foreach (Row row in c1flexGrid1Rows) htAdd(row[CustomerID] LoadImage(row[Photo] as byte[])) ImageMapをPhoto列に割り当てます c1flexGrid1Cols[Photo]ImageMap = ht

C

FlexGrid for WinForms

64 Copyright copy GrapeCity Inc All rights reserved

アスペクト比を維持しながら画像をセルに合わせます c1flexGrid1Cols[Photo]ImageAlign = ImageAlignEnumScale c1flexGrid1Cols[Photo]Width = 80

Dim ht As Hashtable = New Hashtable()

For Each row As Row In c1flexGrid1Rows htAdd(row(CustomerID) LoadImage(TryCast(row(Photo) Byte()))) Next

ImageMapをPhoto列に割り当てます c1flexGrid1Cols(Photo)ImageMap = ht

アスペクト比を維持しながら画像をセルに合わせます c1flexGrid1Cols(Photo)ImageAlign = ImageAlignEnumScale c1flexGrid1Cols(Photo)Width = 80

VBNET

セルボタン

Cell button editor refers to a cell with an ellipsis button This editor comes to use when you need to get an operationdone or open a dialog on a button click Such dialogs generally contain multiple different options or settings for a userto choose from

Default Cell Button Cell Button with Text Cell Button with Custom Image

Display Cell ButtonIn FlexGrid you can display a cell button by setting the ComboList property to an ellipsis character You can alsouse a pipe character before ellipsis button to display an ellipsis with text box to let user enter his inputThe CellButtonClick event is fired when user clicks the cell button You can capture this event to implement thedesired operation or display a dialog of your choice

By default the cell button gets displayed when cell enters the edit mode However you can set the ShowButtonsproperty to Always to display the cell button even in non-edit mode

Use the code below to display cell button in a WinForms FlexGrid column

Mark列のComboListプロパティを設定してセルボタンを表示するようにします c1flexGrid1Cols[Mark]ComboList = セルボタンを常に表示できるようにします c1flexGrid1Cols[Mark]ShowButtons = ShowButtonsEnumAlways

エンドユーザーがセルボタンをクリックしたときに処理します c1flexGrid1CellButtonClick += C1flexGrid1_CellButtonClick

C

Mark列のComboListプロパティを設定してセルボタンを表示するようにしますc1flexGrid1Cols(Mark)ComboList =

VBNET

FlexGrid for WinForms

65 Copyright copy GrapeCity Inc All rights reserved

The ComboList property can also be set using the Combo List dialog at design time To access the Combo List dialog

1 Open the Column Tasks menu for column for which editor is to be set2 Go to the Combo List option and click the ellipsis button on the right hand side of the field3 Combo List dialog opens where you can specify the option values each in a new line4 You can also choose whether you want to display these values as an Ellipsis Button or Textbox amp Ellipsis

Button Note that it also gives you options to create Dropdown List and Dropdown Combo

The example below demonstrates change in back color and fore color of the current row on click of the cell buttonSimilarly you can perform the desired operation in the CellButtonClick event

セルボタンを常に表示できるようにしますc1flexGrid1Cols(Mark)ShowButtons = ShowButtonsEnumAlways

エンドユーザーがセルボタンをクリックしたときに処理しますc1flexGrid1CellButtonClick += C1flexGrid1_CellButtonClick

private void C1flexGrid1_CellButtonClick(object sender RowColEventArgs e) 次のコードは色を変更して現在の行をマークします if (c1flexGrid1Rows[eRow]StyleDisplayBackColor == ColorFromName(Window)) c1flexGrid1Rows[eRow]StyleNewBackColor = ColorGreen c1flexGrid1Rows[eRow]StyleNewForeColor = ColorWhite c1flexGrid1Rows[eRow]StyleNewBackColor = ColorFromName(Window) c1flexGrid1Rows[eRow]StyleNewForeColor = ColorFromName(WindowText)

C

FlexGrid for WinForms

66 Copyright copy GrapeCity Inc All rights reserved

Change Image of Cell ButtonBy default cell button displays an ellipsis However you can change the image of cell button usingthe CellButtonImage property

Set the image of cell button in the WinForms FlexGrid as shown in the code below

Private Sub C1flexGrid1_CellButtonClick(ByVal sender As Object ByVal e As RowColEventArgs) 次のコードは色を変更して現在の行をマークします If c1flexGrid1Rows(eRow)StyleDisplayBackColor Is ColorFromName(Window) Then c1flexGrid1Rows(eRow)StyleNewBackColor = ColorGreen c1flexGrid1Rows(eRow)StyleNewForeColor = ColorWhite End If

If True Then c1flexGrid1Rows(eRow)StyleNewBackColor = ColorFromName(Window) c1flexGrid1Rows(eRow)StyleNewForeColor = ColorFromName(WindowText) End IfEnd Sub

VBNET

CellButtonImageプロパティを設定してセルボタンの画像を定義しますImage imgCellBtn = new Bitmap(ResourcesImagesbuttonpng)c1flexGrid1CellButtonImage = imgCellBtn

C

CellButtonImageプロパティを設定してセルボタンの画像を定義しますDim imgCellBtn As Image = New Bitmap(ResourcesImagesbuttonpng)c1flexGrid1CellButtonImage = imgCellBtn

VBNET

検証

Data validation lets you control the data that a user can enter into a column cell There are various ways in which adata can be validated such as restricting invalid input keys showing the error or warning information or revert thevalue to original on getting an invalid input from the user

FlexGrid for WinForms

67 Copyright copy GrapeCity Inc All rights reserved

To implement validations such as specifying the range of acceptable values or defining the minimum string length ofinput FlexGrid provides EditorValidation property of the Column class The property is oftype ValidationRuleCollection class which consists of pre-defined rules for implementing enhanced data validation inFlexGrid columns For instance the sample code below demonstrates StringLength and Required validation rulesapplied to the Customer column using the EditorValidation property

Refer the code below to know how to add validation rules in WinForms FlexGrid columns

private void SetupGridColumns() var customerNameColumn = _flexCols[CustomerName] customerNameColumnCaption = Customer customerNameColumnEditorValidationAdd(new RequiredRule()) customerNameColumnEditorValidationAdd(new StringLengthRule() MinimumLength = 2 ) var customerIDColumn = _flexCols[CustomerID] customerIDColumnVisible = false var frequencyColumn = _flexCols[Frequency] frequencyColumnFormat = 0 frequencyColumnAllowEditing = false var ageColumn = _flexCols[Age] ageColumnEditorValidationAdd(new RequiredRule()) ageColumnEditorValidationAdd(new RangeRule() Minimum = 10 Maximum = 90 )

C

FlexGrid for WinForms

68 Copyright copy GrapeCity Inc All rights reserved

Another way of applying validation is by capturing the ValidateEdit event and checking the value of EditorTextproperty If value obtained is invalid set the Cancel parameter to true to keep the grid in editing mode until userenters a valid value Such validation can be used in scenarios such as setting the range of valid values validating thecurrent cell value based on another cell value For example the below sample code validates input into a currencycolumn to ensure that values entered are between 1000 and 10000

Use ValidateEdit event to check for valid values during edit mode of the WinForms FlexGrid cell as shown in the codebelow

Private Sub SetupGridColumns() Dim customerNameColumn = _flexCols(CustomerName) customerNameColumnCaption = Customer customerNameColumnEditorValidationAdd(New RequiredRule()) customerNameColumnEditorValidationAdd(New StringLengthRule() With MinimumLength = 2 ) Dim customerIDColumn = _flexCols(CustomerID) customerIDColumnVisible = False Dim frequencyColumn = _flexCols(Frequency) frequencyColumnFormat = 0 frequencyColumnAllowEditing = False Dim ageColumn = _flexCols(Age) ageColumnEditorValidationAdd(New RequiredRule()) ageColumnEditorValidationAdd(New RangeRule() With Minimum = 10 Maximum = 90 )End Sub

VBNET

private void _flex_ValidateEdit( object sender ValidateEditEventArgs e) 金額を検証します if (_flexCols[eCol]DataType == typeof(Decimal)) try Decimal dec = DecimalParse(_flexEditorText) if ( dec lt 1000 || dec gt 10000 ) MessageBoxShow(Value must be between 1000 and 10000) eCancel = true catch MessageBoxShow(Value not recognized as a Currency) eCancel = true

C

Private Sub _flex_ValidateEdit(ByVal sender As Object ByVal e As ValidateEditEventArgs)

VBNET

FlexGrid for WinForms

69 Copyright copy GrapeCity Inc All rights reserved

金額を検証します If _flexCols(eCol)DataType Is GetType(Decimal) Then

Try Dim dec As Decimal = DecimalParse(_flexEditorText)

If dec lt 1000 OrElse dec gt 10000 Then MessageBoxShow(Value must be between 1000 and 10000) eCancel = True End If

Catch MessageBoxShow(Value not recognized as a Currency) eCancel = True End Try End IfEnd Sub

データ注釈

Data annotation means adding meaningful metadata tags to the classes and other objects making it easier to bridgethe gap between models and views by performing data validation and displaying appropriate messages to the endusers For example you may use data annotations to specify how items should be formatted what their captionsshould be whether they should be editable or not

FlexGrid supports multiple data annotation attributes used for customizing data classes displaying data from sourceand setting validation rules To use the attributes in your project you need to add a reference to theSystemComponentModelDataAnnotations assembly and then add the attributes to your data objects in the code

Note The C1FlexGrid supports the annotations defined in NET 4SystemComponentModelDataAnnotations should be version 4000 or higher

Listed below are some of the major annotation attributes that are supported in FlexGrid control Cilck herefor complete list of DataAnnotation attributes

FlexGrid for WinForms

70 Copyright copy GrapeCity Inc All rights reserved

Attribute Name Functionality in FlexGrid

Association Specifies that an entity member represents a data relationship such as a foreignkey relationship

Display Provides a general-purpose attribute that lets you specify localizable strings fortypes and members of entity partial classes

DisplayFormat Specifies how data fields are displayed and formatted by ASPNET Dynamic Data

DisplayColumn Specifies the column that is displayed in the referred table as a foreign-keycolumn

Editable Indicates whether a data field is editable

Key Denotes one or more properties that uniquely identify an entity

Validation

RequiredAttributeStringLengthAttributeRangeAttributeRegularExpressionAttributeMinLengthAttributeMetaDataAttributeMaxLengthAttributeEmailAddressAttributeCompareAttributeDataTypeAttribute

The data annotation validation attributes are used as validation rules in FlexGridoperations

The following code example shows how data annotation feature works in WinForms FlexGrid control

自動生成されたCustomerName列ヘッダに「Customer」と表示されます この列には少なくとも2つの記号の長さが最小の空でない文字列も必要です[Display(Name = Customer)][Required][StringLength(intMaxValue MinimumLength = 2)]

public string CustomerName get set 自動生成されたCustomerID列は非表示になります[Display(AutoGenerateField = false)]public int CustomerID get set

自動生成された「Frequency」列にはパーセンテージで書式設定された値が表示されます また編集を許可しません[DisplayFormat(DataFormatString = 0)][Editable(false)]public double Frequency get set

自動生成された「Age」列は事前定義された範囲の値を許可します[Required][Range(10 90)]public int Age get set サンプルデータを作成しますpublic static BindingListltDatagt GetSampleData(int cnt) var list = new BindingListltDatagt() var rnd = new Random()

C

FlexGrid for WinForms

71 Copyright copy GrapeCity Inc All rights reserved

for (int i = 0 i lt cnt i++) var item = new Data() itemCustomerName = _firstNames[rndNext(0 _firstNamesLength)] + + _lastNames[rndNext(0 _lastNamesLength)] itemCustomerID = i itemFrequency = rndNextDouble() itemAge = rndNext(10 91) listAdd(item) return list

自動生成されたCustomerName列ヘッダに「Customer」と表示されます この列には少なくとも2つの記号の長さが最小の空でない文字列も必要です ltDisplay(Name=Customer)gt ltRequiredgt ltStringLength(IntegerMaxValue MinimumLength=2)gt Public Property CustomerName As String 自動生成されたCustomerID列は非表示になります ltDisplay(AutoGenerateField=False)gt Public Property CustomerID As Integer 自動生成された「Frequency」列にはパーセンテージで書式設定された値が表示されます また編集を許可しません ltDisplayFormat(DataFormatString=0)gt ltEditable(False)gt Public Property Frequency As Double 自動生成された「Age」列は事前定義された範囲の値を許可します ltRequiredgt ltRange(10 90)gt Public Property Age As Integer

サンプルデータを作成します Public Shared Function GetSampleData(ByVal cnt As Integer) As BindingList(Of Data) Dim list = New BindingList(Of Data)() Dim rnd = New Random()

For i As Integer = 0 To cnt - 1 Dim item = New Data() itemCustomerName = _firstNames(rnd[Next](0 _firstNamesLength)) amp + _lastNames(rnd[Next](0 _lastNamesLength)) itemCustomerID = i itemFrequency = rndNextDouble() itemAge = rnd[Next](10 91) listAdd(item) Next

Return list End Function

VBNET

スパークライン

Sparklines are the miniature charts visually representing a series of values to show trends such as periodic fluctuationsor to highlight maximum or minimum values of the data series In grids sparklines are specially useful as they easily fitin a single cell and can help identify the data patterns at a glance

FlexGrid for WinForms

72 Copyright copy GrapeCity Inc All rights reserved

FlexGrid for WinForms lets you display sparklines in columns by setting ShowSparkline property of the Column classto true You can also set the type of sparkline using SparklineType property of the Sparkline class FlexGrid supportsthree types of sparklines which are

Line Similar to line chart line sparkline indicates change in values over a period of time with the help of a lineColumn Similar to column charts column sparkline uses vertical columns to demonstrate pattern acrossdifferent categoriesWinLoss Similar to column sparkline winloss sparkline uses vertical columns to represent values However itdoes not indicate the magnitude and is generally used to indicate the binary data

To display the data markers on sparkline you can set the ShowMarkers property to true The Sparkline class alsoprovides properties to highlight the first last highest lowest or negative data points by displaying them in differentformat You can even style the sparklines using the Styles property

Below code shows how to add sparkline to the WinForms FlexGrid columns

WinLossSparklineを表示するようにプロパティを設定します c1FlexGrid1Cols[2]ShowSparkline = true c1FlexGrid1Cols[2]SparklineSparklineType = SparklineTypeWinLoss c1FlexGrid1Cols[2]SparklineStylesSeriesColor = ColorGreen c1FlexGrid1Cols[2]SparklineShowNegative = true

C

WinLossSparklineを表示するようにプロパティを設定します c1FlexGrid1Cols(2)ShowSparkline = True c1FlexGrid1Cols(2)SparklineSparklineType = SparklineTypeWinLoss c1FlexGrid1Cols(2)SparklineStylesSeriesColor = ColorGreen c1FlexGrid1Cols(2)SparklineShowNegative = True

VBNET

ヘッダとフッタ

Column header refers to the fixed rows on the top of the grid which contains a caption string sort glyph etc

In FlexGrid by default the top row with zero index is allocated for the column header However you can span the header to other rows aswell by specifying them as fixed To set more than one rows as fixed you need to set the Fixed property of RowCollection class to an integergreater than 1

FlexGrid for WinForms

73 Copyright copy GrapeCity Inc All rights reserved

Set Header TextFlexGrid when in bound mode reads the field names from the data source and renders them as column header text However youcan explicitly set Caption property of the Row class to overwrite field name string from the data source In case of unbound grid as well theCaption property specifies the header text Note that this property sets the value of cells in the default header row at zero index To setvalue in the other fixed row cells you need to use the usual value allocation ways of FlexGrid For more information on how to set cellvalues see Set Value in Cell

Specify the header rows and set the header text in WinForms FlexGrid using the code below

Merge Column HeaderFlexGrid provides the AllowMerging property for Row object which specifies whether it is allowed to merge cells in a particular row (in thiscase the header row) or not Once you have allowed merging in the header row set either AllowMerging or AllowMergingFixed propertyof C1FlexGrid class to FixedOnly Availability of these two properties in the FlexGrid control offers you more flexibility to implement multiplelogics related to merging For more information on merging cells see Merge

Use the code below to merge column headers in the WinForms FlexGrid

Wrap Column Header Text

2つの行を列ヘッダ行として設定しますc1FlexGrid1RowsFixed = 2 最初の列のヘッダとサブヘッダを設定しますc1FlexGrid1Cols [1] Caption = Column Header 1c1FlexGrid1 [11] = Column Sub-header 1

C

2つの行を列ヘッダー行として設定します c1FlexGrid1RowsFixed = 2

最初の列のヘッダとサブヘッダを設定します c1FlexGrid1Cols(1)Caption = Column Header 1 c1FlexGrid1(1 1) = Column Sub-header 1

VBNET

ヘッダ行でのマージを許可しますc1FlexGrid1Rows[0]AllowMerging = true

グリッドのAllowMergingまたはAllowMergingFixedプロパティを設定して固定行のみを結合します c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

ヘッダ行でのマージを許可しますc1FlexGrid1Rows(0)AllowMerging = True

グリッドのAllowMergingまたはAllowMergingFixedプロパティを設定して固定行のみを結合します c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

FlexGrid for WinForms

74 Copyright copy GrapeCity Inc All rights reserved

To wrap the text in column header access the CellStyle item Fixed of the CellStyleCollection class and set its WordWrap property totrue Note that to view the wrapped text properly you need to adjust the row height or just call the AutoSizeRow() method to automaticallyresize the row according to the text length

Use the code below to wrap header text of the WinForms FlexGrid columns

Style Column HeaderTo style the column header you can access the CellStyle item Fixed of the CellStyleCollection class and set various styling relatedproperties for same such as Font ForeColor and TextEffect

Customize column header of the WinForms FlexGrid using the code below

Set Column FooterColumn Footer refers to the last row of the grid which displays additional information about the whole column Most common use ofcolumn footer is to show the summary of column data

In FlexGrid you can create the column footer by using Footers property of the C1FlexGrid class FlexGrid lets you choose whether toscroll the footer along with rows or keep it fixed at the bottom of the grid by using Fixed property of the Footers class This class alsoprovides the Descriptions property which accesses the FooterDescription collection to set the additional information such as Caption Todisplay aggregate result in the column footer through various aggregate functions you must access the AggregateDefinition collection

列のキャプションを設定しますc1FlexGrid1Cols[3]Caption = Large Text for Column Header Text Wrapping

行の高さを設定しますc1FlexGrid1Rows[0]Height = 50

固定の行と列のワードラップを設定しますc1FlexGrid1Styles[Fixed]WordWrap = true

C

列のキャプションを設定しますc1FlexGrid1Cols(3)Caption = Large Text for Column Header Text Wrapping

行の高さを設定しますc1FlexGrid1Rows(0)Height = 50

固定の行と列のワードラップを設定しますc1FlexGrid1Styles(Fixed)WordWrap = True

VBNET

ヘッダテキストのフォントを設定しますc1FlexGrid1Styles[Fixed]Font = new Font(Tahoma 10 FontStyleBold) ヘッダテキストの前色を設定しますc1FlexGrid1Styles[Fixed]ForeColor = ColorAqua ヘッダーテキストの背景色を設定しますc1FlexGrid1Styles[Fixed]BackColor = ColorBlue

ヘッダテキストにテキスト効果を適用しますc1FlexGrid1Styles[Fixed]TextEffect = C1WinC1FlexGridTextEffectEnumRaised

C

ヘッダテキストのフォントを設定します c1FlexGrid1Styles(Fixed)Font = New Font(Tahoma 10 FontStyleBold)

ヘッダテキストの前色を設定します c1FlexGrid1Styles(Fixed)ForeColor = ColorAqua

ヘッダーテキストの背景色を設定します c1FlexGrid1Styles(Fixed)BackColor = ColorBlue

ヘッダテキストにテキスト効果を適用します c1FlexGrid1Styles(Fixed)TextEffect = C1WinC1FlexGridTextEffectEnumRaised

VBNET

FlexGrid for WinForms

75 Copyright copy GrapeCity Inc All rights reserved

using Aggregates property of the FooterDescription class Aggregate functions can be specified using the Aggregate property whichaccepts values from AggregateEnum enumeration

Following code shows how to add a column footer in the WinForms FlexGrid

列にフッタを追加しますc1FlexGrid1FootersDescriptionsAdd(new C1WinC1FlexGridFooterDescription() Caption = Total ) フッタに集計を適用しますc1FlexGrid1FootersDescriptions[0]AggregatesAdd(new C1WinC1FlexGridAggregateDefinition() Column = 4 Aggregate = C1WinC1FlexGridAggregateEnumSum )

C

列にフッタを追加しますc1FlexGrid1FootersDescriptionsAdd(New C1WinC1FlexGridFooterDescription() With Caption = Total )

フッタに集計を適用しますc1FlexGrid1FootersDescriptions(0)AggregatesAdd(New C1WinC1FlexGridAggregateDefinition() With Column = 4 Aggregate = C1WinC1FlexGridAggregateEnumSum )

VBNET

サイズ変更

Set Column WidthFlexGrid provides the DefaultSize property of ColumnCollection class to set the column width across the grid You canalso specify the width of a particular column by setting the Width property of the Column class Default value ofWidth property is -1 which indicates that the column is taking width specified by the DefaultSize property The Widthproperty is also available at design time through the C1FlexGrid Column Editor For more information on columneditor see Editors

Use the code below to set the default width of a column of the WinForms FlexGrid

Auto-adjust Column WidthTo adjust the column width according to the text length FlexGrid provides the AutoSizeCol() and AutoSizeCols()methods While AutoSizeCol() method automatically adjusts width of the specified column the AutoSizeCols()method is used for cell ranges

Following code shows how you can auto adjust the column widths according to the text length in the WinFormsFlexGrid

すべての列のデフォルト幅を設定しますc1FlexGrid1ColsDefaultSize = 110最初の列の幅を設定しますc1FlexGrid1Cols [1] Width = 30

C

すべての列のデフォルト幅を設定します c1FlexGrid1ColsDefaultSize = 110最初の列の幅を設定します c1FlexGrid1Cols(1)Width = 30

VBNET

FlexGrid for WinForms

76 Copyright copy GrapeCity Inc All rights reserved

Set MinMax Column WidthFlexGrid allows you to set bounds to the column width by using the MinSize and MaxSize propertiesof ColumnCollection This feature is especially useful in scenarios such as when AllowResizing property is set to trueor while using the AutoSizeCol or AutoSizeCols method

Specify the bounds of column width in the WinForms FlexGrid using the code below

Star SizingStar sizing refers to proportional sizing of grid columns to occupy the available space so that layout of grid remainssame even on resizing For instance consider a grid with 5 columns whose star sizes are specified as 3 2 and In this case first fourth and fifth column always take the same width and grid allocates thrice the width of firstcolumn to the second and twice the width to third column

テキストの長さに応じて最初の列の幅を自動調整しますc1FlexGrid1AutoSizeCol(1) 列の幅を1番目から4番目まで自動調整しますc1FlexGrid1AutoSizeCols(1 4 2)

すべての列の幅を自動調整します c1FlexGrid1AutoSizeCols()

C

テキストの長さに応じて最初の列の幅を自動調整しますc1FlexGrid1AutoSizeCol(1)

列の幅を1番目から4番目まで自動調整しますc1FlexGrid1AutoSizeCols(1 4 2)

すべての列の幅を自動調整します c1FlexGrid1AutoSizeCols()

VBNET

列コレクションの最小幅を設定します c1FlexGrid1ColsMinSize = 20 列コレクションの最大幅を設定します c1FlexGrid1ColsMaxSize = 60

C

列コレクションの最小幅を設定します c1FlexGrid1ColsMinSize = 20

列コレクションの最大幅を設定します c1FlexGrid1ColsMaxSize = 60

VBNET

FlexGrid for WinForms

77 Copyright copy GrapeCity Inc All rights reserved

FlexGrid provides the StarWidth property of Column class to specify the star sizes of columns To restrict the widthsfrom getting too narrow or too wide you can set the MinWidth and MaxWidth properties These properties are alsoavailable through the C1FlexGrid Column Editor For more information on column editor see Editors

Set star sizing or proportional sizing in the WinForms FlexGrid columns using the code below

列のスターサイズを設定しますc1FlexGrid1Cols[1]StarWidth = c1FlexGrid1Cols[2]StarWidth = 3c1FlexGrid1Cols[3]StarWidth = 2c1FlexGrid1Cols[4]StarWidth = c1FlexGrid1Cols[5]StarWidth =

列が狭くなりすぎないようにMinWidthプロパティを設定しますc1FlexGrid1Cols[1]MinWidth = 50

C

列のスターサイズを設定しますc1FlexGrid1Cols(1)StarWidth = c1FlexGrid1Cols(2)StarWidth = 3c1FlexGrid1Cols(3)StarWidth = 2c1FlexGrid1Cols(4)StarWidth = c1FlexGrid1Cols(5)StarWidth =

列が狭くなりすぎないようにMinWidthプロパティを設定しますc1FlexGrid1Cols(1)MinWidth = 50

VBNET

FlexGrid for WinForms

78 Copyright copy GrapeCity Inc All rights reserved

A grid control is a collection of rows and columns Columns generally contain a particular type of information through out while rows are used to recorddifferent types of information about a particular item

In FlexGrid the collection of rows is represented by the RowCollection class which can be accessed through Rows property of the C1FlexGrid class Thissection discusses the various operations that can be performed on rows

Topic Snapshot Content

Basic Operations Discusses about how to perform basic row operations

Set Row CountAdd RowDelete RowInsert RowSet Data TypeSet Fixed RowSet Frozen Row

User Interaction Discusses about operations that can be performed by the end-user at run time

Allow AddingAllow DeletingAllow DraggingAllow FreezingAllow Resizing

Header Discusses about how to set row header and perform other related operations

Set Header TextMerge Row HeaderWrap Row Header TextStyle Row Header

Row Detail Discusses how to display additional information using row detail feature

In-form EditingHierarchical ViewCustom Row Details

Sizing Discusses about various aspects of row sizing

Set Row HeightAuto-adjust Row HeightSet MinMax Row Height

基本操作

This topic discusses various basic operations which can be performed on a row

Set Row CountWhen grid is bound to a data source the number of rows is determined by the number of records available in thedata source However in the case of unbound mode you can set any integer value in Count property ofthe RowCollection class to set the number of rows to be displayed in the grid

Use the code below to set row count in the WinForms FlexGrid

Set row count c1FlexGrid1RowsCount = 15

C

VBNET

FlexGrid for WinForms

79 Copyright copy GrapeCity Inc All rights reserved

Add RowFlexGrid provides various ways to add a new row at runtime You can either use Add method of the RowCollectionclass or AddItem method of the C1FlexGrid class to add a new record In the unbound mode you can also incrementthe value of Count property to add new rows Note that all these ways add rows towards the end of the grid To inserta row at a specific location see Insert Row Also note that an exception is thrown if a new row is added to a boundgrid using Count property

Add a row to WinForms FlexGrid using any of these approaches shown in the code below

Delete RowTo delete a particular row from the grid you can use Remove method of the RowCollection class and specify the rowyou want to delete as its parameter The RowCollection class also provides RemoveRange method which allows you

Set row countc1FlexGrid1RowsCount = 15

Approach1 Use the RowCollectionAdd method to add row C1WinC1FlexGridRow r r = c1FlexGrid1RowsAdd() Set data r[1] = New Row 2

Approach2 Use AddItem method to add row and set data c1FlexGrid1AddItem( + t + New Row 1) Approach3 Use the RowCollectionCount property to add row c1FlexGrid1RowsCount += 1 Set data c1FlexGrid1[c1FlexGrid1RowsCount - 1 1] = New Row 3

C

Approach1 Use the RowCollectionAdd method to add row Dim r As C1WinC1FlexGridRow r = c1FlexGrid1RowsAdd()

Set data r(1) = New Row 2

Approach2 Use AddItem method to add row and set data c1FlexGrid1AddItem( amp vbTab amp New Row 1)

Approach3 Use the RowCollectionCount property to add row c1FlexGrid1RowsCount += 1

Set data c1FlexGrid1(c1FlexGrid1RowsCount - 1 1) = New Row 3

VBNET

FlexGrid for WinForms

80 Copyright copy GrapeCity Inc All rights reserved

to remove a range of rows using a single call Similarly you can also use RemoveItem method of the C1FlexGridclass to remove a specific row In the unbound grid you can reduce the number of rows by changing the value ofCount property

Following code gives different approaches to delete row from the WinForms FlexGrid

Insert RowTo insert a row in FlexGrid at a specific location you can use Insert method of the RowCollection class which lets youspecify the position where rows are to be inserted You can also insert multiple rows in the grid by usingthe InsertRange method

Below code demonstrates how to insert a row at a particular position in the WinForms FlexGrid

Approach1 Remove second row using RowCollectionRemove methodc1FlexGrid1RowsRemove(2)

Approach1 Remove second row using the RemoveItem methodc1FlexGrid1RemoveItem(2)

Approach3 Remove 3 rows starting from second using the RemoveRange methodc1FlexGrid1RowsRemoveRange(2 3) Approach4 Remove last row using the RowCollectionCount property c1FlexGrid1RowsCount -= 1

C

Approach1 Remove second row using RowCollectionRemove method c1FlexGrid1RowsRemove(2)

Approach1 Remove second row using the RemoveItem method c1FlexGrid1RemoveItem(2)

Approach3 Remove 3 rows starting from second using the RemoveRange method c1FlexGrid1RowsRemoveRange(2 3)

Approach4 Remove last row using the RowCollectionCount property c1FlexGrid1RowsCount -= 1

VBNET

C1WinC1FlexGridRow r Approach1 Use the Insert method to insert row at second position r = c1FlexGrid1RowsInsert(2) r[1] = Inserted row Approach2

C

FlexGrid for WinForms

81 Copyright copy GrapeCity Inc All rights reserved

Set Data TypeIn case of a bound FlexGrid data type of each bound column is automatically picked from the data source dependingon the data However in the case of unbound mode you can set the data type of rows or columns by specifyingthe DataType property of Row or Column class respectively Note that when data type is set for both rows andcolumns column settings take preference over row settings

Use the code below to set data type of a WinForms FlexGrid row

Set Fixed RowFixed rows refer to the rows with non-editable cells which are always visible on top of the grid even when user scrollsdown the grid In FlexGrid fixed rows can be set using Fixed property of the RowCollection class This propertyaccepts an integer value that specifies the number of rows to be fixed

Set fixed rows in the WinForms FlexGrid using the code below

Set Frozen RowFrozen rows similar to fixed rows are non-scrollable but can be edited by the user In FlexGrid frozen rows can be set

Use the InsertRange method to add three rows at second position c1FlexGrid1RowsInsertRange(2 3)

Dim r As C1WinC1FlexGridRow Approach1 Use the Insert method to insert row at second position r = c1FlexGrid1RowsInsert(2) r(1) = Inserted row

Approach2 Use the InsertRange method to add three rows at second position c1FlexGrid1RowsInsertRange(2 3)

VBNET

C1WinC1FlexGridRow r r = c1FlexGrid1RowsAdd() rDataType = typeof(int)

C

Dim r As C1WinC1FlexGridRow r = c1FlexGrid1RowsAdd() rDataType = GetType(int)

VBNET

Set three rows as fixed c1FlexGrid1RowsFixed = 3

C

Set three rows as fixedc1FlexGrid1RowsFixed = 3

VBNET

FlexGrid for WinForms

82 Copyright copy GrapeCity Inc All rights reserved

by using Frozen property provided by the RowCollection class

Use the code below to set frozen rows in the WinForms FlexGrid

Set first two rows as frozen c1FlexGrid1RowsFrozen = 2

C

Set first two rows as frozen c1FlexGrid1RowsFrozen = 2

VBNET

ユーザー操作

This topic discusses how you can let end-users interact with the FlexGrid rows

Allow AddingBy default FlexGrid does not allow end-user to add new row to the grid To provide an option to add rows at runtimeyou can set AllowAddNew property of the C1FlexGrid class to true FlexGrid also provides a design-time optionEnable Adding Rows in C1FlexGrid Tasks menu to allow adding new row by the end-user For more information ontask menus see Tasks Menus Moreover you can also set watermark text to be displayed in the new row templatethrough NewRowWatermark property

Use the code below to allow users to add rows in WinForms FlexGrid at run-time

Allow user to add rows c1FlexGrid1AllowAddNew = true Set watermark in the template new row c1FlexGrid1NewRowWatermark = Add new row

C

Allow user to add rows c1FlexGrid1AllowAddNew = True

Set watermark in the template new row

VBNET

FlexGrid for WinForms

83 Copyright copy GrapeCity Inc All rights reserved

Allow DeletingFlexGrid by default does not allow end-user to delete rows from the grid However if your application requires youcan let the end-user delete the selected rows through Delete key by setting AllowDelete property to true You canalso enable row deletion by checking ON the Enable Deleting Rows checkbox on the C1FlexGrid Tasks menu

Following code shows how to allow users to delete rows from WinForms FlexGrid at run-time

Allow DraggingFlexGrid by default does not allow user to rearrange rows by dragging However you can change this behavior inunbound grid by using the FlexGridAllowDragging property and RowAllowDragging property To enable dragging ofgrid rows you can set the FlexGridAllowDragging property to either Rows or Both This property accepts the valuesfrom AllowDraggingEnum You can also disable dragging of a particular row by setting the RowAllowDraggingproperty to false

Note As moving a row is not allowed in bound mode the bound grid throws an exception on dragging arow To implement dragging in bound mode see the blog Drag and Drop Rows in C1Flexgrid

Let users drag the rows in an unbound WinForms FlexGrid at run-time by using the code below

Allow FreezingTo allow end user to freeze the rows at runtime you can use AllowFreezing property of the C1FlexGrid class whichaccepts values from AllowFreezingEnum When this property is set to Rows or Both a lock sign appears when mouseis hovered over the edge of header row End-user can click and drag the lock sign to freeze the rows

Use the code below to allow your users to freeze the WinForms FlexGrid rows at run-time

c1FlexGrid1NewRowWatermark = Add new row

Allow user to delete rowsc1FlexGrid1AllowDelete = true

C

Allow user to delete rowsc1FlexGrid1AllowDelete = True

VBNET

Allow dragging of all rows across the grid c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumRows Disable dragging of a particular row c1FlexGrid1Rows[3]AllowDragging = false

C

Allow dragging of all rows across the grid c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumRows

Disable dragging of a particular row c1FlexGrid1Rows(3)AllowDragging = False

VBNET

FlexGrid for WinForms

84 Copyright copy GrapeCity Inc All rights reserved

Allow ResizingBy default FlexGrid does not give option to resize the rows To change this behavior you can use AllowResizingproperty of the C1FlexGrid class This property accepts values from the AllowResizingEnum enumerationwhich enables end-user to change size of columns rows or both The enumeration also gives you options touniformly resize the rows columns or both that is if you resize one of the columns or rows the grid automaticallyresizes rest of the columns or rows as well FlexGrid also provides RowAllowResizing property which is Boolean typeand lets you enable or disable resizing of a particular row

Following code shows how to allow users to resize the WinForms FlexGrid rows at run-time

Allow freezing of rows at runtimec1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumRows

C

Allow freezing of rows at runtimec1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumRows

VBNET

Allow user to resize rows c1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumRows Stop user from resizing second row c1FlexGrid1Rows[2]AllowResizing = false

C

Allow user to resize rows c1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumRows

Stop user from resizing second row c1FlexGrid1Rows(2)AllowResizing = False

VBNET

ヘッダ

Row header refers to the fixed rows on the left hand side of the grid which may or may not contain the caption string

In FlexGrid by default the left most column with zero index is allocated for the row header However you can span theheader to other columns as well by specifying them as fixed To set more than one column as fixed you need toset the Fixed property of ColumnCollection class to an integer greater than 1

FlexGrid for WinForms

85 Copyright copy GrapeCity Inc All rights reserved

Set Header TextTo set the row header text you can set Caption property of the Row class Note that this property sets the value of cellsin the default header column at zero index To set value in the other fixed column cells you need to use the usual valueallocation ways of FlexGrid For more information on how to set cell values see Set Value in Cell

Specify the header column and set the header text in WinForms FlexGrid using the code below

Merge Row HeaderFlexGrid provides AllowMerging property of the Column class which specifies whether it is allowed to merge cells in aparticular column (in this case the header column) or not Once you have allowed merging in the header columnset either AllowMerging or AllowMergingFixed property of the C1FlexGrid class to FixedOnly Availability of these twoproperties in the FlexGrid control offers you more flexibility to implement multiple logics related to merging For moreinformation on merging cells see Merge

Set header for first rowc1FlexGrid1Rows[1]Caption = Row 1

Set header for all rowsfor (int i = c1FlexGrid1RowsFixed i lt c1FlexGrid1RowsCount i++) c1FlexGrid1[i 0] = Row + iToString()

Set column widthc1FlexGrid1Cols[0]Width = 85

C

Set header for first row c1FlexGrid1Rows(1)Caption = Row 1

Set header for all rows For i As Integer = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 c1FlexGrid1(i 0) = Row amp iToString() Next

Set column width c1FlexGrid1Cols(0)Width = 85

VBNET

FlexGrid for WinForms

86 Copyright copy GrapeCity Inc All rights reserved

Use the code below to merge row headers in the WinForms FlexGrid

Wrap Row Header TextTo wrap the text in row header access the CellStyle item Fixed of the CellStyleCollection class and set its WordWrapproperty to true Note that to view the wrapped text properly you need to adjust height of FlexGrid rows or just callthe AutoSizeRow() method to automatically resize the rows according to the length of text

Use the code below to wrap header text of the WinForms FlexGrid rows

Style Row HeaderTo style the row header you can access the CellStyle item Fixed of the CellStyleCollection class and set variousstyling related properties for same such as Font ForeColor and TextEffect

Allow merging on the header columnc1FlexGrid1Cols[0]AllowMerging = true

Set AllowMerging or AllowMergingFixed property of the grid to merge fixed rowcolumns only c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

Allow merging on the header columnc1FlexGrid1Cols(0)AllowMerging = True

Set AllowMerging or AllowMergingFixed property of the grid to merge fixed rowcolumns only c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

Set row captionc1FlexGrid1Rows[3]Caption = Large text to display text wrapping and mergingc1FlexGrid1Rows[4]Caption = Large text to display text wrapping and merging Set row heightc1FlexGrid1Rows[3]Height = 35c1FlexGrid1Rows[4]Height = 35

Set word wrapping for fixed rows and columnsc1FlexGrid1Styles[Fixed]WordWrap = true

C

Set row captionc1FlexGrid1Rows(3)Caption = Large text to display text wrapping and mergingc1FlexGrid1Rows(4)Caption = Large text to display text wrapping and merging

Set row heightc1FlexGrid1Rows(3)Height = 35c1FlexGrid1Rows(4)Height = 35

Set word wrapping for fixed rows and columnsc1FlexGrid1Styles(Fixed)WordWrap = True

VBNET

FlexGrid for WinForms

87 Copyright copy GrapeCity Inc All rights reserved

Customize row header of the WinForms FlexGrid using the code below

Set font of the header textc1FlexGrid1Styles[Fixed]Font = new Font(Tahoma 10 FontStyleBold) Set forecolor of the header textc1FlexGrid1Styles[Fixed]ForeColor = ColorPaleVioletRed Set backcolor of the header textc1FlexGrid1Styles[Fixed]BackColor = ColorLemonChiffon Apply text effect on the header textc1FlexGrid1Styles[Fixed]TextEffect = C1WinC1FlexGridTextEffectEnumInset

C

Set font of the header text c1FlexGrid1Styles(Fixed)Font = New Font(Tahoma 10 FontStyleBold)

Set forecolor of the header text c1FlexGrid1Styles(Fixed)ForeColor = ColorPaleVioletRed

Set backcolor of the header text c1FlexGrid1Styles(Fixed)BackColor = ColorLemonChiffon

Apply text effect on the header text c1FlexGrid1Styles(Fixed)TextEffect = C1WinC1FlexGridTextEffectEnumInset

VBNET

行の詳細

Row detail is a feature to provide additional information related to a row or record in the form of another expandablelayer In such case row which is the first layer contains the basic information while the second layer contains the detailedinformation This feature is specially useful when the additional information is too large to be displayed in the availablescreen space or it is not consistent for every record

FlexGrid for WinForms

88 Copyright copy GrapeCity Inc All rights reserved

FlexGrid provides the row detail feature using IC1FlexGridRowDetail interface which is implemented by the detail controls tobe hosted on detail row In addition FlexGrid also provides a separate assembly C1WinC1FlexGridRowDetails452dllto provide template user controls InputPanel and FlexGrid ready to be used in detail row You can add details section toany row in FlexGrid which enables you to group data in a template which is visible optionally This allows users to viewadditional data related to a row by simply selecting the row The grid also provides built-in expand or collapse buttons tocontrol the visibility of data within the expandable row

Some common use case scenarios of row detail feature are

1 In-form editing where an InputPanel control is hosted to get input from the user to fill information in a record2 Hierarchical grid which contains a master grid and a detail grid to show additional information about the record3 Custom row details where any control can be used to create row detail template

Detailed implementation of these scenarios is given in their respective sections below

In-form EditingFlexGrid supports in-form editing by hosting InputPanel control in detail row The InputPanel control contains data fieldswhere user can enter or edit the values like a form Once user finishes editing fields those values get reflected in theselected row

FlexGrid for WinForms

89 Copyright copy GrapeCity Inc All rights reserved

In FlexGrid you can implement in-form editing by adding reference to C1WinC1FlexGridRowDetails452dll and usingthe C1InputPanelRowDetail class which already implements the IC1FlexGridRowDetail interface The instance of this classis then assigned to RowDetailProvider property of the C1FlexGrid class which adds the InputPanel control to detail rowand enables the in-form editing

Hierarchical ViewHierarchical view refers to master-detail model where top level grid is the master grid and nested grid is the detail gridwhich displays additional information about expanded row of the master grid For instance example below demonstratesthe master-detail structure using Customer and Order tables respectively with CustomerID as common data element todefine a relation

flexGridRowDetailProvider = (g r) =gt new C1InputPanelRowDetail()flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected

C

flexGridRowDetailProvider = Function(g r) New C1InputPanelRowDetail()flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected

VBNET

FlexGrid for WinForms

90 Copyright copy GrapeCity Inc All rights reserved

In FlexGrid you can implement hierarchical grid by adding reference to C1WinC1FlexGridRowDetails452dll and usingthe C1FlexGridRowDetail class which already implements the IC1FlexGridRowDetail interface The instance of this class isthen assigned to RowDetailProvider property of the C1FlexGrid class to nest another grid in the detail row which enablesthe hierarchical grid interface

private void FlexGrid_Load(object sender EventArgs e) string conn = UtilGetConnectionString() var ds = new DataSet() string[] tables = Customers OrdersSplit() foreach (string tableName in tables) UtilFillTable(ds tableName conn) Defining relation between master and detail grid dsRelationsAdd(Customers_Orders dsTables[Customers]Columns[CustomerID] dsTables[Orders]Columns[CustomerID]) flexGridDataSource = ds flexGridDataMember = Customers flexGridRowDetailProvider = (g r) =gt new C1FlexGridRowDetail() flexGridAreRowDetailsFrozen = false

C

Private Sub FlexGrid_Load(ByVal sender As Object ByVal e As EventArgs) Dim conn As String = UtilGetConnectionString() Dim ds = New DataSet() Dim tables As String() = Customers OrdersSplit(c)

For Each tableName As String In tables UtilFillTable(ds tableName conn) Next Defining relation between master and detail grid dsRelationsAdd(Customers_Orders dsTables(Customers)Columns(CustomerID) dsTables(Orders)Columns(CustomerID))

VBNET

FlexGrid for WinForms

91 Copyright copy GrapeCity Inc All rights reserved

Custom Row DetailsIn addition to the InputPanel and FlexGrid control you can also host a custom control in the detail row of a grid Forinstance in the example below a text label control is attached to the row to enlist the additional information withoutaffecting the dimensions of the grid

To implement the custom row details in FlexGrid you need to create a user control which implementsthe IC1FlexGridRowDetail interface For instance here we have created a class named CustomRowDetail which representsthe text label control to be hosted in the detail row You then need to assign an object of this class to RowDetailProviderproperty of the C1FlexGrid class to enable the custom control to display additional information in the detail row

flexGridDataSource = ds flexGridDataMember = Customers flexGridRowDetailProvider = Function(g r) New C1FlexGridRowDetail() flexGridAreRowDetailsFrozen = False End Sub

private void CustomSample_Load(object sender EventArgs e) flexGridDataSource = DemoDataSource(Employees) flexGridRowDetailProvider = (g r) =gt new CustomRowDetail() flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected flexGridCols[Notes]Visible = false

Custom row detail class which shows label with notes about employee public class CustomRowDetail C1Label IC1FlexGridRowDetail Used to setup control before showing the FlexGrid detail control void IC1FlexGridRowDetailSetup(C1FlexGrid parentGrid int rowIndex) var bs = new BindingSource(parentGridDataSource parentGridDataMember) bsPosition = parentGridRows[rowIndex]DataIndex DataField = Notes DataSource = bs

C

FlexGrid for WinForms

92 Copyright copy GrapeCity Inc All rights reserved

Used to update size of the FlexGrid detail control void IC1FlexGridRowDetailUpdateSize(C1FlexGrid parentGrid int rowIndex Size proposedSize) var srSz = parentGridScrollableRectangleSize var sz = TextRendererMeasureText(Text Font srSz TextFormatFlagsWordBreak) szWidth = MathMax(szWidth srSzWidth) Size = sz

Private Sub CustomSample_Load(ByVal sender As Object ByVal e As EventArgs) flexGridDataSource = DemoDataSource(Employees) flexGridRowDetailProvider = Function(g r) New CustomRowDetail() flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected flexGridCols(Notes)Visible = False End Sub

Custom row detail class which shows label with notes about employee Public Class CustomRowDetail Inherits C1Label Implements IC1FlexGridRowDetail

Used to setup control before showing the FlexGrid detail control Private Sub Setup(ByVal parentGrid As C1FlexGrid ByVal rowIndex As Integer) Dim bs = New BindingSource(parentGridDataSource parentGridDataMember) bsPosition = parentGridRows(rowIndex)DataIndex DataField = Notes DataSource = bs End Sub

Used to update size of the FlexGrid detail control Private Sub UpdateSize(ByVal parentGrid As C1FlexGrid ByVal rowIndex As Integer ByVal proposedSize As Size) Dim srSz = parentGridScrollableRectangleSize Dim sz = TextRendererMeasureText(Text Font srSz TextFormatFlagsWordBreak) szWidth = MathMax(szWidth srSzWidth) Size = sz End Sub End Class

VBNET

サイズ変更

Set Row HeightFlexGrid provides DefaultSize property of the RowCollection class to set row height across the grid You can alsospecify the height of a particular row by setting Height property of the Row class Default value of the Heightproperty is -1 which indicates that the row is taking height specified by the DefaultSize property

Use the code below to set the default height of a row of the WinForms FlexGrid

Set the default size of all rowsc1FlexGrid1RowsDefaultSize = 50

C

FlexGrid for WinForms

93 Copyright copy GrapeCity Inc All rights reserved

Auto-adjust Row HeightTo adjust the row height according to text length and word wrapping options FlexGrid provides the AutoSizeRow()and AutoSizeRows() methods While AutoSizeRow() method automatically adjusts height of the specified row theAutoSizeRows() method is used for cell ranges

Following code shows how you can auto adjust the row height according to the text length in the WinForms FlexGrid

Set MinMax Row HeightFlexGrid allows you to set bounds to the row height by using the MinSize and MaxSize propertiesof the RowCollection class This feature is especially useful in scenarios such as when AllowResizing property is set totrue or while using the AutoSizeRow() or AutoSizeRows() method

Specify the bounds of row height in the WinForms FlexGrid using the code below

Set the height of a particular rowc1FlexGrid1Rows[1]Height = 55

Set the default size of all rowsc1FlexGrid1RowsDefaultSize = 50

Set the height of a particular rowc1FlexGrid1Rows(1)Height = 55

VBNET

Adjust the height of fourth row automaticallyc1FlexGrid1AutoSizeRow(4) Adjust the height of all rows automatically c1FlexGrid1AutoSizeRows() Adjust the height of cell range automaticallyc1FlexGrid1AutoSizeRows(2 4 5 6 10 C1WinC1FlexGridAutoSizeFlagsNone)

C

Adjust the height of fourth row automatically c1FlexGrid1AutoSizeRow(4)

Adjust the height of all rows automatically c1FlexGrid1AutoSizeRows()

Adjust the height of cell range automatically c1FlexGrid1AutoSizeRows(2 4 5 6 10 C1WinC1FlexGridAutoSizeFlagsNone)

VBNET

Set the maximum height of rowc1FlexGrid1RowsMaxSize = 50 Set the minimum height of rowc1FlexGrid1RowsMinSize = 20

C

FlexGrid for WinForms

94 Copyright copy GrapeCity Inc All rights reserved

Set the maximum height of rowc1FlexGrid1RowsMaxSize = 50

Set the minimum height of row c1FlexGrid1RowsMinSize = 20

VBNET

FlexGrid for WinForms

95 Copyright copy GrapeCity Inc All rights reserved

セル

Cell is the smallest unit of a grid Although in most common scenarios we prefer working on row or column levelthere are some operations which are required to be carried out on the cell level Getting setting or removing data arefew to name

Topic Snapshot Content

Basic Operations Discusses how to perform basic operations related to a cell

Set Value in CellSet Values in Cell RangeClear Value from Cell (Range)Set Image in CellDisplay Tooltip in CellRetrieve Cell Values

Cell Format Discusses how to format cell or cell data in various scenarios

Cell ContentCell AppearanceConditional FormattingOwner Drawn Cell

基本操作

Set Value in CellFlexGrid provides two ways to set values in cell You can either use Item property (indexer) or SetData method of the C1FlexGrid class

Use the code below to set a value in the WinForms FlexGrid cell

Set Values in Cell RangeTo set values in a cell range you can either use Data property of the CellRange class or SetData method of the C1FlexGrid class

Following code shows how to set values in a cell range in WinForms FlexGrid

インデックスを使用してデータを設定しますc1FlexGrid1[2 3] = 2nd col 3rd row SetDataメソッドを使用してデータを設定しますc1FlexGrid1SetData(2 4 2nd col 4th row)

C

インデックスを使用してデータを設定します c1FlexGrid1(2 3) = 2nd col 3rd row

SetDataメソッドを使用してデータを設定します c1FlexGrid1SetData(2 4 2nd col 4th row)

VBNET

セル範囲を取得しますC1WinC1FlexGridCellRange cr = c1FlexGrid1GetCellRange(2 3 5 6) 方法1dataプロパティを使用してセル範囲にデータを設定しますcrData = Cell Range

C

FlexGrid for WinForms

96 Copyright copy GrapeCity Inc All rights reserved

Clear Value from Cell (Range)There are two ways by which contents of cell or cell range can be cleared You can either chose to do it programmatically by setting thecontent of cell to an empty string using indexer or SetData method Or you can set the AutoClipboard property to true so that user candelete the values by pressing the Delete key

Below code demonstrates how to allow keyboard operations so that user can clear values from WinForms FlexGrid cells

Set Image in CellTo set image in a cell you can use SetCellImage method of the C1FlexGrid class You can also set an image in a cell range by using Imageproperty of the CellRange class By default text and image both are displayed in the cell However you can choose to display only image bysetting the ImageAndText property to false

Use the code below to set image in a WinForms FlexGrid cell

方法2SetDataメソッドを使用してセル範囲にデータを設定します c1FlexGrid1SetData(cr Cell Range)

セル範囲を取得します Dim cr As C1WinC1FlexGridCellRange = c1FlexGrid1GetCellRange(2 3 5 6)

方法1dataプロパティを使用してセル範囲にデータを設定します crData = Cell Range

方法2SetDataメソッドを使用してセル範囲にデータを設定します c1FlexGrid1SetData(cr Cell Range)

VBNET

ユーザーがDeleteキーを押してセルの内容をクリアするなどのキーボード操作を実行できるようにしますc1FlexGrid1AutoClipboard = true

コードを介して特定のセルのデータをクリアしますc1FlexGrid1SetData(3 4 )

C

ユーザーがDeleteキーを押してセルの内容をクリアするなどのキーボード操作を実行できるようにします c1FlexGrid1AutoClipboard = True

コードを介して特定のセルのデータをクリアします c1FlexGrid1SetData(3 4 )

VBNET

セル(36)に画像を設定しますc1FlexGrid1SetCellImage(3 6 ImageFromFile(masterpng))

C

FlexGrid for WinForms

97 Copyright copy GrapeCity Inc All rights reserved

Display Tooltip in CellTo display partially hidden content of cells as tooltip FlexGrid provides ShowCellLabels property of the C1FlexGrid class You can also showadditional information in the form of a tooltip by using the MouseEnterCell and MouseLeaveCell event

Below code shows how to display a tooltip on a WinForms FlexGrid cell

セル範囲(126)から(146)に画像を設定しますC1WinC1FlexGridCellRange crcr = c1FlexGrid1GetCellRange(12 6 14 6)crImage = ImageFromFile(amexjpg)

テキストなしで画像を表示しますc1FlexGrid1Rows[3]ImageAndText = false

セル(36)に画像を設定します c1FlexGrid1SetCellImage(3 6 ImageFromFile(masterpng))

セル範囲(126)から(146)に画像を設定します Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1GetCellRange(12 6 14 6) crImage = ImageFromFile(amexjpg)

テキストなしで画像を表示します c1FlexGrid1Rows(3)ImageAndText = False

VBNET

private void Form1_Load(object sender EventArgs e) このコードはデータを「c1NWindDataSetEmployees」テーブルにロードします 必要に応じて移動または削除できます thisemployeesTableAdapterFill(thisc1NWindDataSetEmployees) for (int i = c1FlexGrid1RowsFixed i lt c1FlexGrid1RowsCount i++) c1FlexGrid1Rows[i]UserData = Employee + c1FlexGrid1[i 2] + + c1FlexGrid1[i 3] private void C1FlexGrid1_MouseEnterCell(object sender C1WinC1FlexGridRowColEventArgs e) if (eRow gt= c1FlexGrid1RowsFixed) string tip tip = c1FlexGrid1Rows[eRow]UserDataToString() ツールチップを表示します toolTip1SetToolTip(c1FlexGrid1 tip)

private void C1FlexGrid1_MouseLeaveCell(object sender C1WinC1FlexGridRowColEventArgs e) ツールチップを非表示にします toolTip1SetToolTip(c1FlexGrid1 )

C

FlexGrid for WinForms

98 Copyright copy GrapeCity Inc All rights reserved

Retrieve Cell ValuesThere are numerous ways using which you can fetch the value of FlexGrid cells depending on your requirement Below tablediscusses several scenarios such as fetching the raw data or formatted data from a single cell or a cell range

Requirement MethodProperty Usage

Get the raw data Item property (indexer) ExampleCode

var data = c1FlexGrid1[1 1] SystemDiagnosticsDebugWriteLine($Cell data data)

GetData() method ExampleCode

var data1 = c1FlexGrid1GetData(1 1) SystemDiagnosticsDebugWriteLine($Cell data data1)

Get the formatted data GetDataDisplay() method ExampleCode

var data2 = c1FlexGrid1GetDataDisplay(1 1) SystemDiagnosticsDebugWriteLine($Display data data2)

Get values of a cell range Clip property ExampleCode

var data3 = c1FlexGrid1Clip SystemDiagnosticsDebugWriteLine($Clip data data3)

GetCellRange method ExampleCode

var data4 = c1FlexGrid1GetCellRange(1 1) SystemDiagnosticsDebugWriteLine($Cell Range data data4Clip)

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) このコードはデータを「c1NWindDataSetEmployees」テーブルにロードします 必要に応じて移動または削除できます MeemployeesTableAdapterFill(Mec1NWindDataSetEmployees)

For i As Integer = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 c1FlexGrid1Rows(i)UserData = Employee amp c1FlexGrid1(i 2) amp + c1FlexGrid1(i 3) Next End Sub

Private Sub C1FlexGrid1_MouseEnterCell(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) If eRow gt= c1FlexGrid1RowsFixed Then Dim tip As String tip = c1FlexGrid1Rows(eRow)UserDataToString() ツールチップを表示します toolTip1SetToolTip(c1FlexGrid1 tip) End If End Sub

Private Sub C1FlexGrid1_MouseLeaveCell(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) ツールチップを非表示にします toolTip1SetToolTip(c1FlexGrid1 ) End Sub

VBNET

FlexGrid for WinForms

99 Copyright copy GrapeCity Inc All rights reserved

セルの書式設定

Cell ContentTo control how content of the cells is formatted and displayed set the Format property of Row or Column object toformat string similar to the ones that are used with StringFormat property in the NET framework For instance thesample code below formats the third column as Date and fourth column as Currency

FlexGrid also provides design time option to set the Format property through the Format String dialog You canaccess the Format String dialog by clicking Ellipsis button against the Format String field in Column Tasks menu Oryou can also use the Format property in C1FlexGrid Column Editor

短い日付形式を設定しますc1FlexGrid1Cols[3]Format = D 通貨形式を設定しますc1FlexGrid1Cols[4]Format = c

C

短い日付形式を設定しますc1FlexGrid1Cols(3)Format = D

通貨形式を設定しますc1FlexGrid1Cols(4)Format = c

VBNET

FlexGrid for WinForms

100 Copyright copy GrapeCity Inc All rights reserved

Note that Format String dialog is specific to column and changes the Format property of the selected column only

Cell AppearanceFlexGrid provides CellStyle objects to handle the appearance aspects of cells such as alignment font colors bordersand so on The grid has Styles property that holds the collection of styles used to format the grid This collection hassome built-in members that define the appearance of grid elements such as fixed and scrollable cells selection focuscell and so on You can change these styles to modify the appearance of grid

Although changing the built-in styles is the simplest way to change appearance of the grid you can also create yourown custom styles and assign them to cells rows or columns

Use the code below to change appearance of the WinForms FlexGrid cells

組み込みのスタイルをカスタマイズしますCellStyle cs = c1FlexGrid1StylesFocus

C

FlexGrid for WinForms

101 Copyright copy GrapeCity Inc All rights reserved

Conditional FormattingTo format a cell according to its content you need to create a new style and apply it to the cells satisfying a particularcondition using SetCellStyle() method For instance to highlight the values greater than a specified value you canformat the cells containing them using different style

Following code shows how to apply conditional formatting on WinForms FlexGrid cells

csFont = new Font(c1FlexGrid1Font FontStyleBold)csForeColor = ColorGreencsBackColor = ColorRed

カスタムスタイルを作成します CellStyle cs1 = c1FlexGrid1StylesAdd(NewStyle)cs1BackColor = ColorAquacs1ForeColor = ColorBlue

カスタムスタイルを割り当てますc1FlexGrid1Cols[3]Style = cs1

Dim cs As CellStyle = c1FlexGrid1StylesFocus csFont = New Font(c1FlexGrid1Font FontStyleBold) csForeColor = ColorGreen csBackColor = ColorRed

Dim cs1 As CellStyle = c1FlexGrid1StylesAdd(NewStyle) cs1BackColor = ColorAqua cs1ForeColor = ColorBlue

c1FlexGrid1Cols(3)Style = cs1

VBNET

CellStyle cs 大きな値のカスタムスタイルを作成しますcs = c1FlexGrid1StylesAdd(LargeValue)csFont = new Font(Font FontStyleItalic)

C

FlexGrid for WinForms

102 Copyright copy GrapeCity Inc All rights reserved

Owner Drawn CellThe above sections explain how you can customize FlexGrid cells to change the appearance of grid using CellStyleobjects However for further customization of grid cells such as rendering gradient background custom graphics etcyou can use DrawMode property and OwnerDrawCell event of the C1FlexGrid class

The DrawMode property determines whether or not the OwnerDrawCell event is fired The event allows you tooverride every visual aspect of the cell You can change the text and image to be displayed in the cell by setting theeText and eImage parameters in the event handler You can also change the style that is used to display the cell bysetting the eStyle property

Note that you should not modify properties of the Style parameter as it might affect other cells Instead assign a newCellStyle object to the Style parameter For example instead of setting eStyleForeColor = ColorRed assign a wholenew style to the parameter using eStyle = c1FlexGrid1Styles[RedStyle]

You can also use your own drawing code to draw into the cell and even combine your custom code with calls to theeDrawCell method For example you can paint the cell background using GDI calls and then call eDrawCell todisplay the cell borders and content

In the example below WinForms FlexGrid uses a gradient brush to paint the background of the selected cell rangeFirst the sample code sets the DrawMode property to OwnerDraw and then declares a LinearGradientBrushobject

csBackColor = ColorGold

for (int row = 1 row lt c1FlexGrid1RowsCount row++)if (ConvertToDouble(c1FlexGrid1[row 4]) gt 80000)c1FlexGrid1SetCellStyle(row 4 cs)

Dim cs As CellStyle

cs = c1FlexGrid1StylesAdd(LargeValue) csFont = New Font(Font FontStyleItalic) csBackColor = ColorGold

For row As Integer = 1 To c1FlexGrid1RowsCount - 1

If ConvertToDouble(c1FlexGrid1(row 4)) gt 80000 Then c1FlexGrid1SetCellStyle(row 4 cs) End If Next

VBNET

SystemDrawingDrawing2DLinearGradientBrush m_GradientBrushprivate void Form1_Load(object sender EventArgs e)

C

FlexGrid for WinForms

103 Copyright copy GrapeCity Inc All rights reserved

所有者描画セルで使用するブラシ m_GradientBrush = new SystemDrawingDrawing2DLinearGradientBrush(ClientRectangle ColorSteelBlue ColorWhite 45)

グラデーションを追加するにはowner-drawを使用します c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw

private void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) グラデーションブラシを使用して選択したセルの背景を描画します if (c1FlexGrid1SelectionContains(eRow eCol)) 背景を描きますeGraphicsFillRectangle(m_GradientBrush eBounds)

グリッドにコンテンツを描画させますeDrawCell(C1WinC1FlexGridDrawCellFlagsContent)

このセルの描画は完了ですeHandled = true

Private m_GradientBrush As DrawingDrawing2DLinearGradientBrush

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) 所有者描画セルで使用するブラシ m_GradientBrush = New DrawingDrawing2DLinearGradientBrush(ClientRectangle ColorSteelBlue ColorWhite 45)

グラデーションを追加するにはowner-drawを使用します c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDrawEnd Sub

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) グラデーションブラシを使用して選択したセルの背景を描画します If c1FlexGrid1SelectionContains(eRow eCol) Then 背景を描きます eGraphicsFillRectangle(m_GradientBrush eBounds)

グリッドにコンテンツを描画させます eDrawCell(C1WinC1FlexGridDrawCellFlagsContent)

このセルの描画は完了です eHandled = True End IfEnd SubEnd IfEnd Sub

VBNET

FlexGrid for WinForms

104 Copyright copy GrapeCity Inc All rights reserved

グリッド

This section discusses about various operations that can be performed on the grid

Topic Snapshot Content

Basic Operations Discusses about basic operations that can be performed on the grid

Transpose Data in GridDisplay Context Menu

Keyboard Navigation Discusses about supperted keys and their operations in

Non-edit ModeEdit Mode

Improve Performance Provides tips and tricks to get best out of your grid by improving its performance

Use Data VirtualizationUse BeginUpdate and EndUpdate MethodsKeep AutoResize Property to False (default)Assign Styles DynamicallyAvoid Modifying Styles in the OwnerDrawCell EventShow Ellipses in a Single ColumnShow Multi-line Text in a CellRetrieve Data Sorting When Bound to a Data TableSpecify Character Limit for Column

基本操作

This topic discusses about various operations that require handling at the grid level

Transpose Data in GridTransposing data refers to swapping column data and row data In WinForms FlexGrid this can be achieved usingTranspose() method of the C1FlexGrid class as shown in the code below

Note that data can be transposed only in the case of unbound grid Also if grid has sorting applied on a column theTranspose() method removes sorting before transposing the data

Display Context MenuContext menus can be helpful to user as they provide shortcuts for actions that are frequently used In FlexGrid therecan be two scenarios to display a context menu

Display context menu in non-edit modeDisplay context menu in edit mode

Display Context Menu in Non-edit Mode

To display context menu when grid is in non-edit mode you need to create an instance of ContextMenuStrip controladd the menu items and assign the instance to ContextMenuStrip property of the Control class

c1FlexGrid1Transpose()

C

C1FlexGrid1Transpose()

VBNET

FlexGrid for WinForms

105 Copyright copy GrapeCity Inc All rights reserved

Refer to the code below to see how to display a context menu in WinForms FlexGrid in non-edit mode

Display Context Menu in Edit Mode

To display context menu in edit mode you need to display the context menu on editor by using StartEdit event ofthe C1FlexGrid class In the StartEdit event instantiate the editor and the ContextMenuStrip add menu items andthen assign it to ContextMenuStrip property of the editor

Create an instance of ContextMenuStrip controlContextMenuStrip cm = new ContextMenuStrip()

Add menu items to the context menucmItemsAdd(Add Above)cmItemsAdd(Add Below)cmItemsAdd(Add Left)cmItemsAdd(Add Right)

Assign the instance to ContextMenuStrip property c1FlexGrid1ContextMenuStrip = cm

C

Create an instance of ContextMenuStrip controlDim cm As ContextMenuStrip = New ContextMenuStrip()

Add menu items to the context menucmItemsAdd(Add Above)cmItemsAdd(Add Below)cmItemsAdd(Add Left)cmItemsAdd(Add Right)

Assign the instance to ContextMenuStrip property c1FlexGrid1ContextMenuStrip = cm

VBNET

FlexGrid for WinForms

106 Copyright copy GrapeCity Inc All rights reserved

Use the code below to display context menu in WinForms FlexGrid in edit mode

private void C1FlexGrid1_StartEdit(object sender C1WinC1FlexGridRowColEventArgs e) TextBox tb = (TextBox)c1FlexGrid1Editor

Create context menu ContextMenuStrip cm2 = new ContextMenuStrip() cm2ItemsAdd(Cut) cm2ItemsAdd(Copy) cm2ItemsAdd(Paste) Set context menu tbContextMenuStrip = cm2

C

Private Sub C1FlexGrid1_StartEdit(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) Dim tb As TextBox = CType(c1FlexGrid1Editor TextBox)

Create context menu Dim cm2 As ContextMenuStrip = New ContextMenuStrip() cm2ItemsAdd(Cut) cm2ItemsAdd(Copy) cm2ItemsAdd(Paste)

Set context menu tbContextMenuStrip = cm2End Sub

VBNET

キーボードによる移動

With built-in keyboard support FlexGrid lets you perform the basic navigation operations such as moving the focusentering or exiting the edit mode etc with a perfect ease just by using keys Below tables list the supported keys andtheir corresponding operations in non-edit as well as in edit mode of the cell

Non-edit Mode

Key Sequence Key Action

FlexGrid for WinForms

107 Copyright copy GrapeCity Inc All rights reserved

uarr

larr rarr

darr

Moves focus to the adjacent cell in direction indicated by the arrow key

Shift + ArrowSelects adjacent cells in direction indicated by the arrow key

F2Grid is editable Toggles the cell to edit mode If a value exists in the cell it getsselected Else the grid simply displays a cursor in the cell

Grid is not editable No action

EnterGrid is editable Toggles the cell to edit mode If a value exists in the cell it getsselected Else the grid simply displays a cursor in the cell

Grid is not editable Moves the selection down to the next visible row

You can also change default behavior of Enter key press by using the KeyActionEnterproperty

HomeMoves focus to the first cell of row

EndMoves focus to the last cell of row

Ctrl + HomeMoves focus to the first cell of column

Ctrl + EndMoves focus to the last cell of column

TabBy default grid ignores the Tab key press and lets it cycle through the controls on theform However you can define the action to be performed on Tab key press by usingthe KeyActionTab property

Ctrl + C

Ctrl + X

Ctrl + V

Performs usual clipboard operations that is copy(Ctrl+C) cut(Ctrl+X) and paste(Ctrl+V)when AutoClipboard property is set to true (Default value is false)

Edit Mode

Key Sequence Key Action

uarr

darr

Moves focus to the adjacent cell in the direction indicated by arrow key

FlexGrid for WinForms

108 Copyright copy GrapeCity Inc All rights reserved

larr rarrMoves cursor by one character in the direction indicated by arrow key When cursor is onthe first or last character moves focus to the adjacent cell in the direction of arrow key

EnterToggles the cell to non-edit mode and moves focus to the cell below You can also changedefault behavior of Enter key press by using the KeyActionEnter property

EscCancels editing and exits the edit mode

TabBy default grid ignores the Tab key press and lets it cycle through the controls on theform However you can define the action to be performed on Tab key press by usingthe KeyActionTab property

パフォーマンスの向上

Use Data VirtualizationTo efficiently render large data sets FlexGrid supports data vitualization in which data is fetched in pages as the user scrolls down The gridknows the total number of rows but only loads and displays those that are visible to the user For instance you can use C1DataCollectionpackage to implement virtualizable data source Create a class inherited from the C1VirtualDataCollection and implement GetPageAsyncmethod which returns one page of data from data source you have assigned The following GIF shows how FlexGrid appears in the virtualscrolling mode

public class VirtualModeCollectionView C1VirtualDataCollectionltCustomergt public int TotalCount get set = 1_000 protected override async TaskltTupleltint IReadOnlyListltCustomergtgtgt GetPageAsync(int pageIndex int startingIndex int count IReadOnlyListltSortDescriptiongt sortDescriptions = null FilterExpression filterExpression = null CancellationToken cancellationToken = default(CancellationToken)) await TaskDelay(500 cancellationToken)Simulates network traffic return new Tupleltint IReadOnlyListltCustomergtgt(TotalCount EnumerableRange(startingIndex count)Select(i =gt new Customer(i))ToList())

C

Public Class VirtualModeCollectionView

VBNET

FlexGrid for WinForms

109 Copyright copy GrapeCity Inc All rights reserved

Use BeginUpdate and EndUpdate MethodsThe BeginUpdate and EndUpdate methods are used to optimize the performance of the grid Call BeginUpdate before making extensivechanges and call EndUpdate when done to suspend repainting This reduces flicker and increases performance This optimization is especiallyeffective when adding large number of rows to the grid because it needs to recalculate ranges and update scrollbars each time a row is added

The code below shows how to add a large number of rows to the WinForms FlexGrid efficiently Note how the EndUpdate method is calledinside a finally block to ensure repainting is properly restored

Keep AutoResize Property to False (default)In case of bound grid if AutoResize property is set to true the control automatically resizes its columns to fit the widest entry every time newdata is read from the data source If the data source contains a large number of rows and columns the automatic resizing may take a relativelylong time In such cases you should consider setting AutoResize to false and setting the column widths directly in code

Assign Styles DynamicallyFlexGrid allows you to create cell styles and assign them to rows columns and arbitrary cell ranges You can use this feature to format the gridcells conditionally Usually you do this by using the SetCellStyle() method However in that case you have to update the style whenever the cellvalue changes Also if the grid is bound to a data source styles are lost whenever data source is reset after operations such as sorting andfiltering A better alternative in these cases is to use the OwnerDraw feature and select styles dynamically based on the cell values For example

Inherits C1VirtualDataCollection(Of Customer)

Public Property TotalCount As Integer = 1_000

Protected Overrides Async Function GetPageAsync(ByVal pageIndex As Integer ByVal startingIndex As Integer ByVal count As Integer ByVal Optional sortDescriptions As IReadOnlyList(Of SortDescription) = Nothing ByVal Optional filterExpression As FilterExpression = Nothing ByVal Optional cancellationToken As CancellationToken = DirectCast(Nothing CancellationToken)) As Task(Of Tuple(Of Integer IReadOnlyList(Of Customer))) Await TaskDelay(500 cancellationToken) Simulates network traffic Return New Tuple(Of Integer IReadOnlyList(Of Customer))(TotalCount EnumerableRange(CInt(startingIndex) CInt(count))[Select](Function(i) New Customer(i))ToList()) End FunctionEnd Class

void UpdateGrid(C1FlexGrid c1FlexGrid1) try c1FlexGrid1BeginUpdate() suspend painting to avoid flicker c1FlexGrid1RowsCount = 1 for (int i = 1 i lt 10000 i++) c1FlexGrid1AddItem(Row + iToString()) finally c1FlexGrid1EndUpdate() always restore painting

C

Private Sub UpdateGrid(ByVal c1FlexGrid1 As C1FlexGrid) Try c1FlexGrid1BeginUpdate() suspend painting to avoid flicker c1FlexGrid1RowsCount = 1

For i As Integer = 1 To 10000 - 1 c1FlexGrid1AddItem(Row amp iToString()) Next

Finally c1FlexGrid1EndUpdate() always restore painting End TryEnd Sub

VBNET

FlexGrid for WinForms

110 Copyright copy GrapeCity Inc All rights reserved

the sample code shows how to display negative values in red color and values above 1000 in green color in the WinForms FlexGrid

Avoid Modifying Styles in the OwnerDrawCell EventAnother way to improve performance is not to modify the CellStyle object passed as a parameter in the OwnerDrawCell event Instead assign anew value to the eStyle parameter This is important because the CellStyle passed to the event handler is often used by other cells Forexample you could unintentionally change a normal style of the WinForms FlexGrid which would affect other similar cells as well in the grid

private void Form1_Load(object sender EventArgs e) Fill a column with random values c1FlexGrid1Cols[1]DataType = typeof(int) Random rnd = new Random() for (int r = 1 r lt c1FlexGrid1RowsCount r++) c1FlexGrid1[r 1] = rndNext(-10000 10000) Create style used to show negative values c1FlexGrid1StylesAdd(Red)ForeColor = ColorRed Enable OwnerDraw by setting the DrawMode property c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw c1FlexGrid1OwnerDrawCell += new C1WinC1FlexGridOwnerDrawCellEventHandler(C1FlexGrid1_OwnerDrawCell)

private void C1FlexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if(eMeasuring) Check that the row and column contain integer data if (eRow gt 0 ampamp c1FlexGrid1Cols[eCol]DataType == typeof(int)) Apply the style Red eStyle = c1FlexGrid1Styles[Red]

C

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) Fill a column with random values c1FlexGrid1Cols(1)DataType = GetType(Integer) Dim rnd As Random = New Random()

For r As Integer = 1 To c1FlexGrid1RowsCount - 1 c1FlexGrid1(r 1) = rnd[Next](-10000 10000) Next

Create style used to show negative values c1FlexGrid1StylesAdd(Red)ForeColor = ColorRed

Enable OwnerDraw by setting the DrawMode property c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw c1FlexGrid1OwnerDrawCell += New C1WinC1FlexGridOwnerDrawCellEventHandler(AddressOf C1FlexGrid1_OwnerDrawCell) End Sub

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If Not eMeasuring Then

Check that the row and column contain integer data If eRow gt 0 AndAlso c1FlexGrid1Cols(eCol)DataType Is GetType(Integer) Then Apply the style Red eStyle = c1FlexGrid1Styles(Red) End If End If End Sub

VBNET

FlexGrid for WinForms

111 Copyright copy GrapeCity Inc All rights reserved

Show Ellipses in a Single ColumnThe Trimming property should be used to show ellipses in a single column of the grid To determine how long strings are trimmed to fit the cellthe Trimming property can be set to either None Character Word EllipsisCharacter EllipsisWord or EllipsisPath For more information ontrimming see Display Trimmed Text

The following code sets the Trimming property to show ellipses at the end of the second WinForms Flexgrid column with the text trimmed tothe nearest character

Show Multi-line Text in a CellWhen showing multiple lines of text in a cell use the WordWrap and Height properties The WordWrap property determines whether the gridshould automatically break long strings that contain spaces and display them in multiple lines Strings that contain hard line breaks (vbCrLf ornr) are always displayed in multiple lines Multiple line text can be displayed in both fixed and scrollable cells For more information on wordwrapping see Wrap Text

Refer to code below to see how a multi-line text should be effectively displayed in the WinForms FlexGrid

CORRECT APPROACHprivate void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) Select style to use when painting this cell eStyle = MyStyleSelector(eRow eCol) WRONG APPROACHprivate void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) Select style to use when painting this cell This is wrong because changing any CellStyle objects invalidates the grid which would cause this event handler to be called over and over again eStyleColor = MyColorSelector(eRow eCol)

C

CORRECT APPROACHPrivate Sub C1FlexGrid1_OwnerDrawCellMethod(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) Select style to use when painting this celleStyle = MyStyleSelector(eRow eCol)End Sub

WRONG APPROACHPrivate Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) Select style to use when painting this cell This is wrong because changing any CellStyle objects invalidates the grid which would cause this event handler to be called over and over againeStyleColor = MyColorSelector(eRow eCol)End Sub

VBNET

c1FlexGrid1Cols[1]StyleNewTrimming =StringTrimmingEllipsisCharacter

C

c1FlexGrid1Cols(1)StyleNewTrimming = StringTrimmingEllipsisCharacter

VBNET

Set the WordWrap property

C

FlexGrid for WinForms

112 Copyright copy GrapeCity Inc All rights reserved

Retrieve Data Sorting When Bound to a Data TableTo maintain the way the grid is sorted when data is refreshed you can use the default views Sort property and a sort expression The Sortproperty uses a string containing the column name followed by ASC(default) or DESC to sort the column in ascending or descending orderrespectively Multiple columns can be sorted by specifying each column name separated by a comma A sort expression can include names ofgrid columns or a calculation Setting the sort expression at run time immediately reflects the changes in the data view

Below code shows how to use the sort expression with Sort property in the WinForms FlexGrid

Specify Character Limit for ColumnTo set the maximum number of characters a user can enter for any given column use the SetupEditor event You must declare an externaleditor such as C1TextBox in the StartEdit event of the C1FlexGrid class Then in the SetupEditor event you can set the maximum number ofcharacters that are allowed in a column cell

Use the code below to set the character limit for a WinForms FlexGrid column

c1FlexGrid1Styles[Normal]WordWrap = true Set the row heightc1FlexGrid1Rows[1]Height = 2 fgRowsDefaultSize Add text to the cellc1FlexGrid1[1 2] = This is the first line rn This is the second line

Set the WordWrap property c1FlexGrid1Styles(Normal)WordWrap = True

Set the row height c1FlexGrid1Rows(1)Height = 2 fgRowsDefaultSize

Add text to the cell c1FlexGrid1(1 2) = This is the first line amp vbCrLf amp This is the second line

VBNET

Sort the data by the UnitsInStock column then by the ProductID column thisproductsBindingSourceSort = UnitsInStock ASC ProductID ASC

C

Sort the data by the UnitsInStock column then by the ProductID columnMeproductsBindingSourceSort = UnitsInStock ASC ProductID ASC

VBNET

private void C1FlexGrid1_StartEdit(object sender C1WinC1FlexGridRowColEventArgs e) c1FlexGrid1Editor = c1TextBox private void C1FlexGrid1_SetupEditor(object sender RowColEventArgs e) Set the 3rd column to allow 20 characters and the rest only 10 if (eCol == 2) c1TextBoxMaxLength = 20 else c1TextBoxMaxLength = 10

C

Private Sub C1FlexGrid1_StartEdit(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs)

VBNET

FlexGrid for WinForms

113 Copyright copy GrapeCity Inc All rights reserved

c1FlexGrid1Editor = c1TextBox End Sub

Private Sub C1FlexGrid1_SetupEditor(ByVal sender As Object ByVal e As RowColEventArgs)

Set the 3rd column to allow 20 characters and the rest only 10 If eCol = 2 Then c1TextBoxMaxLength = 20 Else c1TextBoxMaxLength = 10 End If End Sub

FlexGrid for WinForms

114 Copyright copy GrapeCity Inc All rights reserved

スクロールバー

Display or Hide the Scroll BarIn FlexGrid you can manage the display of scroll bars using the ScrollBars property which lets you choose whether todisplay horizontal vertical both or no scroll bar through the ScrollBars enumeration

Below code shows how to always display both the scrollbars in the WinForms FlexGrid

Set Scroll PositionTo scroll FlexGrid to a specified location you can set TopRow and LeftCol property of the C1FlexGrid class TopRowproperty scrolls the grid vertically while LeftCol sets the horizontal scroll position of the grid The maximum value ofthese properties depends on the total number of rows or columns and the count that can be displayed in the gridThis feature is really useful in scenarios like synchronized scrolling of multiple grids

Use the code below to set scroll position of the WinForms FlexGrid

水平および垂直スクロールバーを表示しますc1FlexGrid1ScrollBars = ScrollBarsBoth 常にスクロールバーを表示しますc1FlexGrid1ScrollOptions = ScrollFlagsAlwaysVisible

C

水平および垂直スクロールバーを表示しますc1FlexGrid1ScrollBars = ScrollBarsBoth

常にスクロールバーを表示しますc1FlexGrid1ScrollOptions = ScrollFlagsAlwaysVisible

VBNET

スクロール位置を設定しますc1FlexGrid1TopRow = 3c1FlexGrid1LeftCol = 2

C

スクロール位置を設定しますc1FlexGrid1TopRow = 3

VBNET

FlexGrid for WinForms

115 Copyright copy GrapeCity Inc All rights reserved

Other Scroll OptionsFlexGrid also provides more options to handle various aspects of displaying a scroll bar through ScrollOptionsproperty This property accepts the values from ScrollFlags enumeration which lets you customize the scroll baroptions as described in the table below

Value Scroll Operation

AlwaysVisible Displays the scroll bar even when they are disable or there is no scrollable area

DelayedScroll Scrolls the content only after user has released the scrollbar thumb

KeepMergedRangePosition Can not set scroll position to the first cell of a merged range

None Uses the default scrolling behavior

ScrollByRowColumn Scrolls the content in units of rows or columns instead of scrolling by pixels

ShowScrollTips Fires the ShowScrollTip event and displays a tooltip next to the vertical scrollbarwhile scrolling vertically

Following code shows how to scroll the WinForms FlexGrid by rows or columns only

c1FlexGrid1LeftCol = 2

行や列単位でスクロールします c1FlexGrid1ScrollOptions = ScrollFlagsScrollByRowColumn

C

行や列単位でスクロールしますc1FlexGrid1ScrollOptions = ScrollFlagsScrollByRowColumn

VBNET

FlexGrid for WinForms

116 Copyright copy GrapeCity Inc All rights reserved

選択

Selection ModesFlexGrid by default allows to select a continuous batch of cells using mouse or keyboard and entire row or column by clicking thecorresponding header However the default behavior can be changed to allow selection in units of cell row column etc byusing SelectionMode property of the C1FlexGrid class The property accepts values from the SelectionModeEnumenumeration Below table gives a quick snapshot of how selection looks like in each of these modes

Value Description Snapshot

Default Allows selection of continuous batch of cells using mouse orkeyboard Also lets the user select entire row or column onclicking the respective header

Cell Allows selection of single cell at a time

CellRange Allows selection of continuous batch of cells using mouse orkeyboard

Column Allows selection of single column at a time

ColumnRange Allows selection of multiple contiguous columns at a time

ListBox Allows selection of multiple non-contiguous rows using the Ctrlkey

FlexGrid for WinForms

117 Copyright copy GrapeCity Inc All rights reserved

Row Allows selection of single row at a time

RowRange Allows selection of multiple contiguous rows at a time

Set SelectionFlexGrid provides various ways to set the selection through code You can use any of these methods depending on the requirementsuch as selecting the single cell cell range or rows

Selection MethodProperty Sample code

Single cell Set the Row and Col property Default value of both of theseproperties is 1 Hence by default selection is set to the firstscrollable cell on top left of the grid

Example Title

c1FlexGrid1Row = 2c1FlexGrid1Col = 1

Call the Select(rowIndex colIndex) method to select a singlecell

Example Title

c1FlexGrid1Select(2 1)

Cell range Set the RowSel and ColSel property These properties set theselection starting from value set in Row and Col property tothe specified row and column Note that to specify a blockselection you must set Row and before setting RowSel andColSel

Example Title

c1FlexGrid1Row = 2c1FlexGrid1Col = 1c1FlexGrid1RowSel = 4c1FlexGrid1ColSel = 3

Call the Select(CellRange Boolean) method to select a cellrange in a single call

Example Title

CellRange cellRange = new CellRange()cellRanger1 = 2cellRanger2 = 4cellRangec1 = 1cellRangec2 = 3c1FlexGrid1Select(cellRange)

Rows

(If SelectionModes =

SelectionModesEnum

ListBox)

Set the RowSelected property to true for individual rowobjects to select the non-continuous rows

Example Title

c1FlexGrid1SelectionMode = SelectionModeEnumListBoxc1FlexGrid1Rows[1]Selected = truec1FlexGrid1Rows[4]Selected =

Value Description Snapshot

FlexGrid for WinForms

118 Copyright copy GrapeCity Inc All rights reserved

true

Get Selection To get selected range of the WinForms FlexGrid you can use Selection property of the C1FlexGrid class

Select Text on Double ClickBy default double click on a grid cell changes the cell state to edit mode and shows the cursor at position of the mouse pointerHowever you can change this behavior and select the cell value on double click of a cell This can be done by detecting anddisabling the double click in BeforeDoubleClick event Then call the StartEditing method to enter the edit mode change theeditor to a TextBox and call the SelectAll method to select the cell value

Following code shows how you can select text of the WinForms FlexGrid cell on a double click

private void Button1_Click(object sender EventArgs e) C1WinC1FlexGridCellRange cr cr = c1FlexGrid1Selection MessageBoxShow(Selected rangen + crr1 + + crc1 + to + crr2 + + crc2)

C

Private Sub Button1_Click(ByVal sender As Object ByVal e As EventArgs) Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1Selection MessageBoxShow(Selected range amp vbLf amp crr1 amp + crc1 amp to + crr2 amp + crc2)End Sub

VBNET

private void C1FlexGrid1_BeforeDoubleClick(object sender BeforeMouseDownEventArgs e) デフォルトのダブルクリックを無効にします eCancel = true 編集モードに入ります c1FlexGrid1StartEditing() TextBoxクラスに変換しSelectAllメソッドを使用して選択します TextBox tb = (TextBox)c1FlexGrid1Editor tbSelectAll()

C

Private Sub C1FlexGrid1_BeforeDoubleClick(ByVal sender As Object ByVal e As BeforeMouseDownEventArgs) デフォルトのダブルクリックを無効にします eCancel = True 編集モードに入ります c1FlexGrid1StartEditing() TextBoxクラスに変換しSelectAllメソッドを使用して選択します Dim tb As TextBox = CType(c1FlexGrid1Editor TextBox) tbSelectAll()End Sub

VBNET

Selection MethodProperty Sample code

FlexGrid for WinForms

119 Copyright copy GrapeCity Inc All rights reserved

編集

This topic discusses about various events and methods which are related to editing and also about how to disableediting

Topic Content

Edit Mode Discusses various events and methods related to editing

Disable Editing Discusses how to disable editing in grid at various levels

Disable Grid EditingDisable Row or Column EditingDisable Cell Editing

編集モード

In FlexGrid edit mode can be invoked at runtime using mouse click or even keyboard To determineprogrammatically whether the grid is in edit mode you can read the value of Editor property If the grid is in editmode the property returns a reference to the control that is being used as editor such as TextBox or ComboBoxHowever if the grid is not in edit mode the property returns null

To put the grid in edit mode programmatically you can use the StartEditing method and to finish editing you can callthe FinishEditing method You can also retain the state of edit mode in grid while navigating through the cells byusing the PreserveEditMode property

In addition FlexGrid fires various events to facilitate better control on the editing process Below table lists thesequence of events which are fired by the grid during the editing process

Event Name Description

BeforeEdit The event fires whenever an editable cell is selected It allows you to prevent the cell from beingedited by setting the events Cancel parameter to true You can also modify the ComboList propertyso the appropriate drop-down button gets painted in the cell Note that the user might not actuallystart editing after this he could simply move the selection to a different cell or control

StartEdit The event is similar to BeforeEdit except the user has actually typed a key or clicked the dropdownbutton in the cell and really is about to start editing You can still cancel the editing at this point Notethat the Editor property is still null at this point because the control hasnt yet determined the typeof editor that should be used You can assign custom editors to the Editor property at this point

ChangeEdit The event is a wrapper of editorTextChanged event The event fires when the contents of the editorchange You can use this event to keep track of the current content in editor

SetupEditor The event fires after the editor control has been created and configured to edit the cell but before itis displayed You can change the editor properties at this point (for example set the maximum lengthor password character to be used in a TextBox editor) You can also attach your own event handlers tothe editor

ValidateEdit The event fires when the user is done editing before the editor value gets copied back into the gridYou can examine the original value by retrieving it from the grid (the event provides the coordinatesof the cell) You can examine the new value about to be assigned to the grid through the Editorproperties (for example EditorText) If the new value is not valid for the cell set the Cancel parameterto true and the grid remains in edit mode If instead of keeping the cell in edit mode you wouldrather restore the original value and leave edit mode set Cancel parameter to true and then call theFinishEditing method

LeaveEdit This event fires after the grid control leaves edit mode You can use this event to approve or deny the

FlexGrid for WinForms

120 Copyright copy GrapeCity Inc All rights reserved

new cell content or to change the editor content about to be committed

AfterEdit This event fires after the new value has been applied to the cell and the editor has been deactivatedYou can use this event to update anything that depends on the cell value (for example subtotals orsorting)

Also there are few events which are related to keyboard operations and are fired when a key is pressed They aresimilar to their counterparts from SystemWindowsFormsControl class apart from the fact that they occur when thegrid is in edit mode

Event Description

KeyDownEdit This event fires when grid is in edit mode and a key is pressed You can use this event toperform an action once or even multiple times while the key is held down such as movinga cursor

KeyPressEdit This event fires when grid is in edit mode and a character key is pressed You can use thisevent to perform any operation related to typing such as handling input in the cell editor

KeyUpEdit This event fires when grid is in edit mode and key is released You can use this event toplace a logic that executes after KeypressEdit logic has taken effect

Event Name Description

編集の無効化

FlexGrid by default allows end-user to edit the cell values at runtime However with FlexGrid you can easily managehow much control you want to give to the end-users using various properties provided by the FlexGrid

Disable Grid EditingTo disable editing of the whole WinForms FlexGrid you need to set AllowEditing property of the C1FlexGrid class tofalse as shown in the code below

Disable Row or Column EditingTo disable the editing of a particular row or column of the WinForms FlexGrid you can set the AllowEditing propertyof Row or Column object to false as shown in the code below

グリッドで編集を無効にします c1FlexGrid1AllowEditing = false

C

グリッドで編集を無効にしますc1FlexGrid1AllowEditing = False

VBNET

3行目の編集を無効にしますc1FlexGrid1Rows[3]AllowEditing = false 3列目の編集を無効にしますc1FlexGrid1Cols[3]AllowEditing = false

C

FlexGrid for WinForms

121 Copyright copy GrapeCity Inc All rights reserved

Disable Cell EditingTo disable editing of a particular cell you can use the BeforeEdit event and set the Cancel parameter for thatparticular cell to true

3行目の編集を無効にしますc1FlexGrid1Rows(3)AllowEditing = False

3列目の編集を無効にしますc1FlexGrid1Cols(3)AllowEditing = False

VBNET

セル編集を無効にしますprivate void C1FlexGrid1_BeforeEdit(object sender RowColEventArgs e) if ((eCol == 4) ampamp (eRow == 2)) eCancel = true

C

セル編集を無効にしますPrivate Sub C1FlexGrid1_BeforeEdit(ByVal sender As Object ByVal e As RowColEventArgs) If eCol = 4 AndAlso eRow = 2 Then eCancel = True End IfEnd Sub

VBNET

FlexGrid for WinForms

122 Copyright copy GrapeCity Inc All rights reserved

並べ替え

Sorting is one of the basic features a grid must have and FlexGrid provides you complete control on how data can besorted in ascending or descending order for easier data analysis This topic discusses about sorting in FlexGrid andother related operations

Topic Snapshot Content

Sort Operations Discusses various operations related to sorting

Sorting through CodeSort Multiple ColumnsRevertUndo SortingDisable Sort on a Particular ColumnSort OrderCustom Sorting

Sort Indicator Discusses how to hide position and customize sort indicator

HideDisplay Sort IndicatorPosition Sort IndicatorCustomize Sort Indicator

並べ替えの操作

FlexGrid by default allows end-users to apply sorting on a single column by clicking the column header in ascending ordescending order However the grid also provides you flexibility so that you can sort your data according to yourrequirement Below sections take you through the ways to perform various operations related to sorting

Sorting through CodeYou can apply sorting through code by calling Sort method of the C1FlexGrid class The method takes SortFlagsenumeration as its parameter which lets you provide the various sort options such as setting the sort order and ignorecasing The method has various overloads which gives you flexibility to apply sorting either on a column or a range ofcells rows or columns

Use the code below to sort columns and apply sorting options through code in the WinForms FlexGrid

FlexGrid for WinForms

123 Copyright copy GrapeCity Inc All rights reserved

Sort Multiple ColumnsTo apply sorting on multiple columns through code you can use the Sort property of Column class and then call theSort() method with SortFlags set to UseColSort The Sort property accepts values from SortFlags enumeration

Following code shows how to sort multiple columns of the WinForms FlexGrid through code

To allow user to sort multiple columns at runtime set AllowSorting property of the C1FlexGrid class to MultiColumn Theproperty accepts values from the AllowSortingEnum enumeration

Following code shows how to let user sort multiple columns of the WinForms FlexGrid at run-time

方法1 2番目の列を降順で並べ替えますc1FlexGrid1Sort(C1WinC1FlexGridSortFlagsDescending 2) 方法 2SortFlagを使用して複数の並べ替えオプションを指定しますC1WinC1FlexGridSortFlags order = C1WinC1FlexGridSortFlagsAscending | C1WinC1FlexGridSortFlagsIgnoreCase Sortメソッドを呼び出しますc1FlexGrid1Sort(order 2)

C

方法1 2番目の列を降順で並べ替えますc1FlexGrid1Sort(C1WinC1FlexGridSortFlagsDescending 2)

方法2 SortFlagを使用して複数の並べ替えオプションを指定しますDim order As C1WinC1FlexGridSortFlags = C1WinC1FlexGridSortFlagsAscending Or C1WinC1FlexGridSortFlagsIgnoreCase

Sortメソッドを呼び出しますc1FlexGrid1Sort(order 2)

VBNET

複数列を並べ替えますc1FlexGrid1Cols[2]Sort = SortFlagsAscendingc1FlexGrid1Cols[3]Sort = SortFlagsDescending Sortメソッドを呼び出しますc1FlexGrid1Sort(SortFlagsUseColSort 2 3)

C

複数列を並べ替えますc1FlexGrid1Cols(2)Sort = SortFlagsAscendingc1FlexGrid1Cols(3)Sort = SortFlagsDescending

Sortメソッドを呼び出しますc1FlexGrid1Sort(SortFlagsUseColSort 2 3)

VBNET

グリッドの複数の列での並べ替えを許可します c1FlexGrid1AllowSorting = AllowSortingEnumMultiColumn

C

FlexGrid for WinForms

124 Copyright copy GrapeCity Inc All rights reserved

RevertUndo SortingTo remove sorting from the grid you can set SortDefinition property of the C1FlexGrid class to an empty string

Below code how to remove sorting from the WinForms FlexGrid

Disable Sort on a Particular ColumnTo disable sorting on a particular column you need to set the AllowSorting property of that Column object to false

Use the code below to disable sorting on a particular column of the WinForms FlexGrid

Sort OrderOrder of sorting usually varies in case of bound and unbound mode When a column header is clicked in case of boundmode sorting is done same as DefaultViewSort property of the data table However in case of unbound mode columnis sorted either according to StringCompare method or by differentiating the lower and upper case according to theculture

Refer to the code below to specify sorting order of a WinForms FlexGrid column

グリッドの複数の列での並べ替えを許可しますc1FlexGrid1AllowSorting = AllowSortingEnumMultiColumn

VBNET

並べ替えを削除します c1FlexGrid1SortDefinition = stringEmpty

C

並べ替えを削除しますc1FlexGrid1SortDefinition = StringEmpty

VBNET

グリッドの特定の列での並べ替えを無効にしますc1FlexGrid1Cols[2]AllowSorting = false

C

グリッドの特定の列での並べ替えを無効にしますc1FlexGrid1Cols(2)AllowSorting = False

VBNET

C1WinC1FlexGridSortFlags order = C1WinC1FlexGridSortFlagsAscending | C1WinC1FlexGridSortFlagsIgnoreCase c1FlexGrid1Sort(order 2)

C

Dim order As C1WinC1FlexGridSortFlags = C1WinC1FlexGridSortFlagsAscending Or C1WinC1FlexGridSortFlagsIgnoreCasec1FlexGrid1Sort(order 2)

VBNET

FlexGrid for WinForms

125 Copyright copy GrapeCity Inc All rights reserved

Custom SortingFlexGrid provides several sorting options which are required for most commonly used scenarios such as ignore case usethe display value etc However if you need to have more flexibility and control over sort operation you can even writeyour own custom logic using the IComparer class For instance the example below sorts the Name column by fileextensions In the sample code custom logic to sort by file extension is implemented in the FileNameComparer class whichis then passed as parameter to Sort() method of the C1FlexGrid class

The code below demonstrates how to apply custom sorting on the WinForms FlexGrid columns

c1FlexGrid1Sort(new FileNameComparer(c1FlexGrid1 eOrder)) class FileNameComparer IComparer C1FlexGrid c1FlexGrid1 bool _desc

ctor public FileNameComparer(C1FlexGrid flex SortFlags order) c1FlexGrid1 = flex _desc = ((order amp SortFlagsDescending) = 0) IComparer public int Compare(object r1 object r2) ファイル名を取得します string s1 = (string)c1FlexGrid1[((Row)r1)Index Name] string s2 = (string)c1FlexGrid1[((Row)r2)Index Name]

拡張機能を比較します int icmp = stringCompare(PathGetExtension(s1) PathGetExtension(s2) true)

並べ替え順(昇順または降順)を返します return (_desc) -icmp icmp

C

C1FlexGrid1Sort(New FileNameComparer(C1FlexGrid1 SortFlagsAscending))

Public Class FileNameComparer Implements IComparer

Private c1FlexGrid1 As C1FlexGrid Private _desc As Boolean

Public Sub New(ByVal flex As C1FlexGrid ByVal order As SortFlags) c1FlexGrid1 = flex _desc = ((order And SortFlagsDescending) ltgt 0) End Sub

Public Function Compare(r1 As Object r2 As Object) As Integer Implements IComparerCompare Dim s1 As String = CStr(c1FlexGrid1((CType(r1 Row))Index Name)) Dim s2 As String = CStr(c1FlexGrid1((CType(r2 Row))Index Name)) Dim icmp As Integer = StringCompare(PathGetExtension(s1) PathGetExtension(s2) True) Return If((_desc) -icmp icmp) End Function

VBNET

FlexGrid for WinForms

126 Copyright copy GrapeCity Inc All rights reserved

For detailed implementation of custom sorting see the product sample named Custom Sort

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing WinFormsEdition using ComponentOneControlPanelexe

並べ替えのインジケータ

FlexGrid displays sort indicator a small triangular arrow sign to indicate the direction of sorting The grid alsoprovides flexibility to hide display position or customize the indicator

Hide or Display Sort IndicatorFlexGrid by default displays the sort indicator when a column header is clicked to sort the columns However you canhide the indicator by setting the ShowSortPosition property to None The property accepts valuesfrom ShowSortPositionEnum enumeration

Use the code below to hide the sort indicator displayed on the sorted WinForms FlexGrid column

Position Sort IndicatorSort indicator by default gets displayed towards the right side of the header cell However when the filtering isapplied on a column the sort indicator displays on top of the header cell to give place to the filtering icon You can fixthe position of sort indicator by setting value of ShowSortPosition property to Top or Right

Customize the position of column sort indicator in WinForms FlexGrid using the code below

Customize Sort IndicatorFlexGrid provides the GlyphEnum enumeration which lets you specify the image to be used for sort indicator Formore information on the GlyphEnum and glyph customization see Custom Glyphs

並べ替えインジケータを非表示にしますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumNone

C

並べ替えインジケータを非表示にしますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumNone

VBNET

並べ替えインジケータの位置を上に変更しますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumTop

C

並べ替えインジケータの位置を上に変更しますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumTop

VBNET

FlexGrid for WinForms

127 Copyright copy GrapeCity Inc All rights reserved

フィルタ

Grid filtering lets you narrow down display records according to a specified condition applied on a column It is especially useful in case of large data sets asit lets you easily analyze data by displaying a specific type of records only

This section discusses about the process types and customization of filters

Topic Snapshot Content

Filter Operations Discusses about how to enable or apply filtering and other related operations

Allow FilteringFiltering through CodeCustom FilteringRemove FilteringTypes of Filters

Filter UI Discusses about filtering icon its customization and how to set the filter language

Show Filter IconUse Custom IconsChange Filter Language

フィルタの操作

Data filtering in a grid can be performed in two ways

Header-based Filter

In header-based filtering an icon is displayed in the header cell of column which gives you options to specify the filter in a drop-down and alsoindicates if the filter is applied on a particular column In FlexGrid this behavior can be achieved by simply using AllowFiltering property of the gridIn this case filter does not require any extra real estate on the screen This approach also gives you flexibility to customize and create better filtereditors More details about same is given in the sections below

Filter Row

Filter row is a row dedicated for displaying the filtering criteria and appears just below the column header So in this case user can always see thefiltered columns and their current filtering criteria But this added advantage comes at the cost of extra screen real estate that a filter row needs InFlexGrid you can easily achieve filter row using the custom implementation For implementation see the product sample named Filter Row

Note The Filter Row sample is located at DocumentsComponentOne SamplesWinFormsv452C1FlexGridCS on your system if you haveinstalled the samples while installing WinForms Edition using ComponentOneControlPanelexe

Allow FilteringIn FlexGrid filtering can be enabled by setting the C1FlexGridAllowFiltering property to true This enables the default ColumnFilter on allcolumns of the grid The ColumnFilter lets the users choose from ValueFilter and ConditionFilter at runtime

FlexGrid for WinForms

128 Copyright copy GrapeCity Inc All rights reserved

You can also specify the filter types for each column by setting the AllowFiltering property of each Column object AllowFiltering property ofcolumn lets you choose from any of the following values

Value Description

Default Enables the ColumnFilter which is a combination of ValueFilter and ConditionFilter and gives user a runtime option to choose eitherof them

ByValue Enables ValueFilter which contains a checkbox list of values present in that column User can check off the values that should not bedisplayed in the filtered output

ByCondition Enables ConditionFilter which lets you specify combination of two conditions such as equals greater than contains etc Youcan combine the specified conditions using And and Or operator

Custom Lets you instantiate a custom filter and explicitly assign it to Filter property of the column

None Disables filtering for that column

Use the following code snippet to enable a condition filter on first column of the WinForms FlexGrid

For more details regarding abovementioned filter types see Types of Filters

Filtering through CodeAlthough AllowFiltering property of grid enables grid filtering and can be used in most common scenarios there may be cases where you need tofurther fine tune the filter options This can be achieved by modifying AllowFiltering and Filter properties of individual columns For example thecode below enables filtering in the WinForms FlexGrid but restricts the filtering to columns of type string

You can also customize the filtering process further by creating filters and assigning them to columns or by retrieving existing filters and modifyingtheir properties For example the code below creates a ConditionFilter in the WinForms FlexGrid configures it to select all items that are equal toGermany and then assigns the new filter to the ShipCountry column

グリッドでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = true 列1に対してフィルタを指定しますc1FlexGrid1Cols[1]AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

C

グリッドでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = True

列1に対してフィルタを指定しますc1FlexGrid1Cols(1)AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

VBNET

文字列型の列にフィルタリングを制限します foreach (Column c in c1FlexGrid1Cols) cAllowFiltering = cDataType == typeof(string) AllowFilteringDefault AllowFilteringNone

C

文字列型の列にフィルタリングを制限しますFor Each c As Column In c1FlexGrid1Cols cAllowFiltering = If(cDataType Is GetType(String) AllowFilteringDefault AllowFilteringNone)Next

VBNET

グリッドでフィルタリングを有効にします c1FlexGrid1AllowFiltering = true 新しいConditionFilterを作成します C1WinC1FlexGridConditionFilter Filter Filter = new C1WinC1FlexGridConditionFilter()

C

FlexGrid for WinForms

129 Copyright copy GrapeCity Inc All rights reserved

Custom FilteringWhen filtering is applied to FlexGrid it hides the rows that do not qualify the filtering criteria by setting their Visible property to false However insome cases you may want to customize this behavior For such scenarios you can use the BeforeFilter and AfterFilter events fired by FlexGridThe below example customizes the filtering behavior of WinForms FlexGrid by applying a different style to non-qualifying rows instead of hidingthem

Germanyのアイテムを絞り込むためのフィルタを作成します FilterCondition1Operator = C1WinC1FlexGridConditionOperatorEquals FilterCondition1Parameter = Germany 「ShipCountry」列に新しいフィルタを割り当てます c1FlexGrid1Cols[ShipCountry]Filter = Filter フィルタを適用します c1FlexGrid1ApplyFilters()

グリッドでフィルタリングを有効にしますc1FlexGrid1AllowFiltering = True

新しいConditionFilterを作成しますDim Filter As C1WinC1FlexGridConditionFilterFilter = New C1WinC1FlexGridConditionFilter()

Germanyのアイテムを絞り込むためのフィルタを作成しますFilterCondition1[Operator] = C1WinC1FlexGridConditionOperatorEqualsFilterCondition1Parameter = Germany

「ShipCountry」列に新しいフィルタを割り当てますc1FlexGrid1Cols(ShipCountry)Filter = Filter

フィルタを適用しますc1FlexGrid1ApplyFilters()

VBNET

private void c1FlexGrid1_BeforeFilter(object sender CancelEventArgs e) c1FlexGrid1BeginUpdate()

private void c1FlexGrid1_AfterFilter(object sender EventArgs e) フィルタリングされた行を表示するために使用されるスタイルを取得します var cs = c1FlexGrid1Styles[filteredOut]

すべての行にスタイルを適用します

C

FlexGrid for WinForms

130 Copyright copy GrapeCity Inc All rights reserved

The above code uses a custom style named filteredout which can be defined as shown in the code below

Remove FilteringUser can remove column filtering at runtime by using Clear option given in the filter UI of each column You can also remove filtering of the wholegrid programmatically by passing the empty string in FilterDefinition property of FlexGrid

Below code demonstrates how to clear all the filters from the WinForms FlexGrid

for (int r = c1FlexGrid1RowsFixed r lt c1FlexGrid1RowsCount r++) var row = c1FlexGrid1Rows[r] if (rowVisible) 通常の行スタイルをリセットします rowStyle = null else フィルタリングされた行 見えるようにしスタイルを適用します rowVisible = true rowStyle = cs

更新を再開します c1FlexGrid1EndUpdate()

Private Sub c1FlexGrid1_BeforeFilter(ByVal sender As Object ByVal e As CancelEventArgs) c1FlexGrid1BeginUpdate()End Sub

Private Sub c1FlexGrid1_AfterFilter(ByVal sender As Object ByVal e As EventArgs) フィルタリングされた行を表示するために使用されるスタイルを取得します Dim cs = c1FlexGrid1Styles(filteredOut)

すべての行にスタイルを適用します For r = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 Dim row = c1FlexGrid1Rows(r)

If rowVisible Then 通常の行スタイルをリセットします rowStyle = Nothing Else フィルタリングされた行 見えるようにしスタイルを適用します rowVisible = True rowStyle = cs End If Next

更新を再開します c1FlexGrid1EndUpdate()End Sub

VBNET

フィルタによって除外された行のスタイルを作成しますvar cs = c1FlexGrid1StylesAdd(filteredOut)csBackColor = ColorLightGraycsForeColor = ColorDarkGray

C

フィルタによって除外された行のスタイルを作成しますDim cs = c1FlexGrid1StylesAdd(filteredOut)csBackColor = ColorLightGraycsForeColor = ColorDarkGray

VBNET

フィルタ定義を空の文字列に設定してフィルタリングを削除しますc1FlexGrid1FilterDefinition = stringEmpty

C

FlexGrid for WinForms

131 Copyright copy GrapeCity Inc All rights reserved

フィルタ定義を空の文字列に設定してフィルタリングを削除しますc1FlexGrid1FilterDefinition = StringEmpty

VBNET

フィルタの種類

FlexGrid not only provides built-in filters such as Column filter Value filter and Condition Filter but also lets youcreate your own custom filter The built-in filters are provided through AllowFiltering property of Column class whichlets you set the type of filter to be applied on a particular column On the other hand the custom filters make use ofthe IC1ColumnFilter interface and the IC1ColumnFilterEditor interface This topic discusses the implementation ofbuilt-in and custom filters in detail

Column FilterColumn filter is the default filter that is applied to all the columns automatically when AllowFiltering property of thegrid is set to true The ColumnFilter is a combination of ValueFilter and ConditionFilter (discussed below) and givesuser an option to choose either of them at runtime While working with code you can use its ValueFilterand ConditionFilter properties to access the two types of filters The filter also provides Apply method to apply filterto a value and Reset method to reset the filter and hence making it inactive

Use the below code to apply column filter on ProductName column of the WinForms FlexGrid

列フィルタ(ProductNameが「C」で始まる製品をフィルター処理します)ColumnFilter colFilter = new ColumnFilter()colFilterConditionFilterCondition1Parameter = CcolFilterConditionFilterCondition1Operator = ConditionOperatorBeginsWithc1FlexGrid1Cols[ProductName]Filter = colFilter

C

列フィルタ(ProductNameが「C」で始まる製品をフィルター処理します) Dim colFilter As ColumnFilter = New ColumnFilter()

VBNET

FlexGrid for WinForms

132 Copyright copy GrapeCity Inc All rights reserved

Value FilterValue filter refers to the value based filter which gets enabled on setting the AllowFiltering property of column toByValue The ValueFilter provides the dropdown list of all values with checkbox which lets the user select the valueswhich are to be displayed in the output These values can be get or set through the ShowValues property You canalso set a limit on number of values to be displayed in the dropdown list by setting the ValuesLimit property Just likecolumn filter value filter also provides Apply method to apply filter to a value and Reset method to reset the filter

Below code shows how to apply ValueFilter on a column of the WinForms FlexGrid

Condition FilterCondition filter refers to a filter based on one or two logical conditions which can be enabled by setting theAllowFiltering property to ByCondition The ConditionFilter gives user an option to set the conditionsthrough Condition1 and Condition2 properties which can be combined using ANDOR operator by settingthe AndConditions property to filter the records Similar to other filters this class also provides Apply and Resetmethod

colFilterConditionFilterCondition1Parameter = C colFilterConditionFilterCondition1[Operator] = ConditionOperatorBeginsWith c1FlexGrid1Cols(ProductName)Filter = colFilter

値フィルタ(CategoryIdが12358である製品をフィルタ処理します)ValueFilter valueFilter = new ValueFilter()valueFilterShowValues = new object[] 1 2 3 5 8 c1FlexGrid1Cols[CategoryId]Filter = valueFilter

C

値フィルタ(CategoryIdが12358である製品をフィルタ処理します) Dim valueFilter As ValueFilter = New ValueFilter() valueFilterShowValues = New Object() 1 2 3 5 8 c1FlexGrid1Cols(CategoryId)Filter = valueFilter

VBNET

FlexGrid for WinForms

133 Copyright copy GrapeCity Inc All rights reserved

Below code demonstrates how to apply a ConditionFilter on a WinForms FlexGrid column

Custom FilterThe abovementioned filters provide you enough flexibility to implement most common filtering scenarios efficientlyIn addition custom filter option also lets you create your own filter to meet any other specialized requirements ofyour application To create a custom filter you need to create a filter class that implements the IC1ColumnFilterinterface and an editor class that implements the IC1ColumnFilterEditor interface Below example shows theimplementation of a custom string filter which lets you filter based on ranges

条件フィルタ(UnitPricegt = 50およびlt= 100の製品をフィルタ処理します)ConditionFilter conditionFilter = new ConditionFilter()conditionFilterCondition1Parameter = 50conditionFilterCondition1Operator = ConditionOperatorGreaterThanOrEqualToconditionFilterCondition2Parameter = 100conditionFilterCondition2Operator = ConditionOperatorLessThanOrEqualToconditionFilterAndConditions = truec1FlexGrid1Cols[UnitPrice]Filter = conditionFilter

C

条件フィルタ(UnitPricegt = 50およびlt= 100の製品をフィルタ処理します) Dim conditionFilter As ConditionFilter = New ConditionFilter() conditionFilterCondition1Parameter = 50 conditionFilterCondition1[Operator] = ConditionOperatorGreaterThanOrEqualTo conditionFilterCondition2Parameter = 100 conditionFilterCondition2[Operator] = ConditionOperatorLessThanOrEqualTo conditionFilterAndConditions = True c1FlexGrid1Cols(UnitPrice)Filter = conditionFilter

VBNET

FlexGrid for WinForms

134 Copyright copy GrapeCity Inc All rights reserved

Following is the code of a custom filter created for the WinForms FlexGrid Note that the class implementsIC1CustomFilter interface

StringFiltercs

class StringFilter C1WinC1FlexGridIC1ColumnFilter

ListltPointgt _ranges = new ListltPointgt()

ltsummarygt このフィッタが受け入れる文字列を定義するポイントのリストを取得します ltsummarygt public ListltPointgt Ranges get return _ranges

範囲リストが空でない場合フィルタはアクティブです public bool IsActive get return _rangesCount gt 0

フィルタをリセットします public void Reset() _rangesClear()

指定された日付にフィルタを適用します public bool Apply(object value) if (value = null)

C

FlexGrid for WinForms

135 Copyright copy GrapeCity Inc All rights reserved

var s = valueToString() if (sLength gt 0) int c = charToUpperInvariant(s[0]) foreach (var cr in _ranges) if (c gt= charToUpperInvariant((char)crX) ampamp c lt= charToUpperInvariant((char)crY)) return true return false

このフィルタのエディタコントロールを返します public C1WinC1FlexGridIC1ColumnFilterEditor GetEditor() return new StringFilterEditor()

Friend Class StringFilter Implements C1WinC1FlexGridIC1ColumnFilter Private _ranges As List(Of Point) = New List(Of Point)()

ltsummarygt このフィッタが受け入れる文字列を定義するポイントのリストを取得します ltsummarygt Public ReadOnly Property Ranges As List(Of Point) Get Return _ranges End Get End Property

範囲リストが空でない場合フィルタはアクティブです Public ReadOnly Property IsActive As Boolean Implements C1WinC1FlexGridIC1ColumnFilterIsActive Get Return _rangesCount gt 0 End Get End Property

フィルタをリセットします Public Sub Reset() Implements C1WinC1FlexGridIC1ColumnFilterReset _rangesClear() End Sub

指定された日付にフィルタを適用します Public Function Apply(ByVal value As Object) As Boolean Implements C1WinC1FlexGridIC1ColumnFilterApply If value IsNot Nothing Then Dim s = valueToString()

If sLength gt 0 Then Dim c As Integer = AscW(CharToUpperInvariant(s(0)))

VBNET

FlexGrid for WinForms

136 Copyright copy GrapeCity Inc All rights reserved

Following is the code of a custom class that implements IC1CustomFilterEditor interface

StringFilterEditorcs

For Each cr In _ranges

If c gt= AscW(CharToUpperInvariant(MicrosoftVisualBasicChrW(crX))) AndAlso c lt= AscW(CharToUpperInvariant(MicrosoftVisualBasicChrW(crY))) Then Return True End If Next End If End If

Return False End Function

このフィルタのエディタコントロールを返します Public Function GetEditor() As C1WinC1FlexGridIC1ColumnFilterEditor Implements C1WinC1FlexGridIC1ColumnFilterGetEditor Return New StringFilterEditor() End Function

End Class

public partial class StringFilterEditor UserControl C1WinC1FlexGridIC1ColumnFilterEditor StringFilter _filter

public StringFilterEditor() InitializeComponent()

public void Initialize(C1WinC1FlexGridC1FlexGridBase grid int columnIndex C1WinC1FlexGridIC1ColumnFilter filter) _filter = (StringFilter)filter

チェックボックスの値を初期化します foreach (var pt in _filterRanges) switch ((char)ptX) case A _chkAEChecked = true break case F _chkFJChecked = true break case K _chkKOChecked = true break case P _chkPTChecked = true

C

FlexGrid for WinForms

137 Copyright copy GrapeCity Inc All rights reserved

break case U _chkUZChecked = true break public void ApplyChanges() フィルタをリセットします _filterRangesClear()

選択した範囲を追加します foreach (Control ctl in thisControls) var cb = ctl as CheckBox if (cb = null ampamp cbChecked) var pt = new Point((int)cbText[0] (int)cbText[cbTextLength - 1]) _filterRangesAdd(pt) public bool KeepFormOpen get return false void _chkAE_CheckedChanged(object sender EventArgs e) var cb = sender as CheckBox cbFont = new Font(Font cbChecked FontStyleBold FontStyleRegular)

Public Partial Class StringFilterEditor Inherits UserControl Implements C1WinC1FlexGridIC1ColumnFilterEditor

Private _filter As StringFilter Public Sub New() InitializeComponent() End Sub

Public Sub Initialize(ByVal grid As C1WinC1FlexGridC1FlexGridBase ByVal columnIndex As Integer ByVal filter As C1WinC1FlexGridIC1ColumnFilter) Implements C1WinC1FlexGridIC1ColumnFilterEditorInitialize _filter = CType(filter StringFilter)

チェックボックスの値を初期化します For Each pt In _filterRanges

Select Case MicrosoftVisualBasicChrW(ptX) Case Ac _chkAEChecked = True Case Fc _chkFJChecked = True Case Kc _chkKOChecked = True Case Pc

VBNET

FlexGrid for WinForms

138 Copyright copy GrapeCity Inc All rights reserved

_chkPTChecked = True Case Uc _chkUZChecked = True End Select Next End Sub

Public Sub ApplyChanges() Implements C1WinC1FlexGridIC1ColumnFilterEditorApplyChanges フィルタをリセットします _filterRangesClear()

選択した範囲を追加します For Each ctl As Control In Controls Dim cb = TryCast(ctl CheckBox)

If cb IsNot Nothing AndAlso cbChecked Then Dim pt = New Point(MicrosoftVisualBasicAscW(cbText(0)) MicrosoftVisualBasicAscW(cbText(cbTextLength - 1))) _filterRangesAdd(pt) End If Next End Sub

Public ReadOnly Property KeepFormOpen As Boolean Implements C1WinC1FlexGridIC1ColumnFilterEditorKeepFormOpen Get Return False End Get End Property

Private Sub _chkAE_CheckedChanged(ByVal sender As Object ByVal e As EventArgs) Dim cb = TryCast(sender CheckBox) cbFont = New Font(MyBaseFont If(cbChecked FontStyleBold FontStyleRegular)) End Sub

End Class

フィルタUI

FlexGrid provides several options to flexibly customize the filtering UI and lets you create your own unique filter for yourapplication The control allows you to show hide and customize the filtering icon You can even change the language displaying infilter to meet your localization requirements

Show Filter Icon

FlexGrid by default shows the filtering icon( ) when mouse hovers over the filterable column header However you can chooseto display the filtering icon always by setting ShowFilterIcon property of the C1FlexGrid class to Always The property accepts thevalues from FilterIconVisibility enumeration

FlexGrid for WinForms

139 Copyright copy GrapeCity Inc All rights reserved

Use the code below to always display the filter icon on filtered columns of the WinForms FlexGrid

Use Custom IconsFlexGrid also lets you customize the filtering icon by using Glyphs property of the C1FlexGrid class which accepts an imagethrough GlyphEnum enumeration You can also change icon displayed on the current filtered column using the same enumerationFor more information about custom glyphs see Custom Glyphs

常にフィルタのアイコンを表示しますc1FlexGrid1ShowFilterIcon = C1WinC1FlexGridFilterIconVisibilityAlways

C

常にフィルタのアイコンを表示しますc1FlexGrid1ShowFilterIcon = C1WinC1FlexGridFilterIconVisibilityAlways

VBNET

FlexGrid for WinForms

140 Copyright copy GrapeCity Inc All rights reserved

Following code displays how to apply custom icons on filtered columns of the WinForms FlexGrid

Change Filter LanguageBy default FlexGrid localizes the column filter editor to use language specified by the CurrentUICulture setting However you canuse the Language property to override the default and specify the language to be used when grid displays the column filter editor

Use the below code to change the display language of filter in the WinForms FlexGrid

フィルタのアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilterEditor] = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilteredColumn] = ImageFromFile(filterico)

C

フィルタのアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilterEditor) = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilteredColumn) = ImageFromFile(filterico)

VBNET

フィルタ言語を日本語に設定しますc1FlexGrid1Language = C1UtilLocalizationLanguageJapanese

C

フィルタ言語を日本語に設定しますc1FlexGrid1Language = C1UtilLocalizationLanguageJapanese

VBNET

FlexGrid for WinForms

141 Copyright copy GrapeCity Inc All rights reserved

検索

With FlexGrid you can easily perform search either on the entire grid or just a specific column This topic discusseshow you can enable search in FlexGrid

Search in Entire GridTo search the entire FlexGrid you need to add the C1FlexGridSearchPanel control to the form and associate it with thegrid to be searched using SetC1FlexGridSearchPanel method The C1FlexGridSearchPanel control highlights thesearch results and filters the records having search results automatically However you can choose not to highlight theresults by setting the HighlightSearchResults to false It also provides a SearchMode property to set whether tostart the search automatically or on hitting the Search button or Enter key You can also set the watermark in searchbox as well as a time delay in search

Use the code below to search the entire WinForms FlexGrid using SearchPanel

検索パネルを検索対象のFlexGridに関連付けますc1FlexGridSearchPanel1SetC1FlexGridSearchPanel(c1FlexGrid1 c1FlexGridSearchPanel1)

検索を構成しますc1FlexGridSearchPanel1HighlightSearchResults = truec1FlexGridSearchPanel1SearchMode = C1WinC1FlexGridSearchModeAlways c1FlexGridSearchPanel1Watermark = Search productsc1FlexGridSearchPanel1SearchDelay = 2

C

検索パネルを検索対象のFlexGridに関連付けます

VBNET

FlexGrid for WinForms

142 Copyright copy GrapeCity Inc All rights reserved

Search in ColumnTo enable column-wise search FlexGrid provides AutoSearch property of the C1FlexGrid class which accepts valuesfrom AutoSearchEnum enumeration The enumeration lets you start downward column search from the first scrollablerow or from the current cursor position To search a value in a particular column you need to keep the cursor in thatcolumn and type the value to be searched and grid automatically jumps to the search result in that column You canalso set delay in search by setting the AutoSearchDelay property

Following code enables column-wise search in the WinForms FlexGrid

c1FlexGridSearchPanel1SetC1FlexGridSearchPanel(c1FlexGrid1 c1FlexGridSearchPanel1)

検索を構成しますc1FlexGridSearchPanel1HighlightSearchResults = Truec1FlexGridSearchPanel1SearchMode = C1WinC1FlexGridSearchModeAlwaysc1FlexGridSearchPanel1Watermark = Search productsc1FlexGridSearchPanel1SearchDelay = 2

一番上の行からの列単位の検索を有効にしますc1FlexGrid1AutoSearch = C1WinC1FlexGridAutoSearchEnumFromTopc1FlexGrid1AutoSearchDelay = 2

C

一番上の行からの列単位の検索を有効にしますc1FlexGrid1AutoSearch = C1WinC1FlexGridAutoSearchEnumFromTopc1FlexGrid1AutoSearchDelay = 2

VBNET

FlexGrid for WinForms

143 Copyright copy GrapeCity Inc All rights reserved

マージ

FlexGrid allows you to merge cells with same values making them span multiple rows or columns This capability is useful for enhancing appearance andclarity of data displayed in the grid The effect of these settings is similar to the HTML ltROWSPANgt and ltCOLSPANgt tags

Cell merging has several possible uses For example you can use it to create merged table headers merged data views or grids where the text spills intoadjacent columns This section discusses these scenarios in the topics below

Topic Snapshot Content

Auto-merge Discusses about how to enable automatic merging in grid

Free auto-mergeRestricted auto-mergeMerge table headers

Handle Spilling Text Discusses how to display long texts in normal and node rows

Handle Spill in Normal CellsHandle Text in Node Rows

Custom Merge Discusses about ways to customize the default merging behavior

Method 1 Use IComparer interfaceMethod 2 Override the GetMergedRange method

自動マージ

FlexGrid lets you enable automatic cell merging in the grid by setting the AllowMerging property to a value other than None Inaddition you need to set the AllowMerging property of each target row or column to true Merging occurs only if adjacent cellscontain the same non-empty string There is no method to force a pair of cells to merge The merging is done automaticallybased on the cell contents This feature makes it easy to provide merged views of sorted data where values in adjacent rowspresent repeated data

Free Auto-mergeFree auto-merge refers to merging of cells with just one pre-condition of having same values in adjacent cells To automaticallymerge the cells in a row or a column you simply need to set AllowMerging property of the C1FlexGrid class to Free and setAllowMerging property of the target row or column object to true

FlexGrid for WinForms

144 Copyright copy GrapeCity Inc All rights reserved

Below code shows how to apply free merging on a WinForms FlexGrid column

Restricted Auto-mergeIn most of the scenarios you would want the grid to merge the grid cells with same values only if cells above or in left directionare also merged This behavior is called restricted auto-merge and can be achieved by setting the C1FlexGridAllowMergingproperty to RestrictAll RestrictRows or RestrictCols This is required in addition to setting the AllowMerging property oftarget row or column to true

Use the code below to allow restricted auto-merging on a WinForms FlexGrid column

Merge Table HeadersMerging the header cells specially in case of multi-row header is another very common scenario used in grids and tables Tomerge the header cells you must set the C1FlexGridAllowMerging property to FixedOnly You must also set theAllowMerging property of designated row and columns to true In this case headers cells with same value merge together togive a simplified appearance

許可される結合の種類を指定しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFree 結合を許可する列を指定しますc1FlexGrid1Cols[2]AllowMerging = true

C

許可される結合の種類を指定しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFree

結合を許可する列を指定しますc1FlexGrid1Cols(2)AllowMerging = True

VBNET

結合を許可する列を指定しますc1FlexGrid1Cols[3]AllowMerging = true 左側のセルが結合されている場合にのみ列を結合しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumRestrictCols

C

結合を許可する列を指定しますc1FlexGrid1Cols(3)AllowMerging = True

左側のセルが結合されている場合にのみ列を結合しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumRestrictCols

VBNET

FlexGrid for WinForms

145 Copyright copy GrapeCity Inc All rights reserved

Following code demonstrates how to apply merging only on table headers of the WinForms FlexGrid

Custom Auto-mergeFlexGrid also provides a Custom option through AllowMerging enumeration In this case auto-merge is performed on cellrange collection provided using MergedRanges property of the C1FlexGrid class The custom auto-merge is performedindependent of cell content For instance below image shows the merging of two specified cell ranges despite of the differentcell values

固定の行と列の結合を許可しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

固定の行と列の結合を許可しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

FlexGrid for WinForms

146 Copyright copy GrapeCity Inc All rights reserved

Use the following code snippet to apply custom merge on the WinForms FlexGrid

結合のモードをアクティブにしますthisc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumCustom

いくつかのマージされた範囲を定義します 2つのセルは幅が広く1つのセルは高いですthisc1FlexGrid1MergedRangesAdd(2 2 2 3)

3つのセルは幅が広く3つのセルは高さですthisc1FlexGrid1MergedRangesAdd(5 2 7 4)

C

結合のモードをアクティブにしますMec1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumCustom

いくつかのマージされた範囲を定義します 2つのセルは幅が広く1つのセルは高いですMec1FlexGrid1MergedRangesAdd(2 2 2 3)

3つのセルは幅が広く3つのセルは高さですMec1FlexGrid1MergedRangesAdd(5 2 7 4)

VBNET

はみ出して表示されるセルの処理

In FlexGrid you can create the same behavior as excel for handling long text entries by spilling them into emptyadjacent cells This behavior not only helps you in handling long text entries of usual cells but also in displayingoutline nodes which are different from data rows This topic discusses these two scenarios in the following sectionsThese settings work on the grid level and does not need you to set AllowMerging property of specific row or column

Handle Spill in Normal CellsThis FlexGrid setting causes text that is too long to fit in a cell to spill into empty adjacent cells If you have a longentry in a cell and the adjacent cell is empty the entry spills onto the adjacent cells to occupy as much room as

FlexGrid for WinForms

147 Copyright copy GrapeCity Inc All rights reserved

needed This behavior can be achieved by setting the AllowMerging property to Spill For instance in the imagebelow long data strings from TestGroup column cells spill to the empty Flag column cells giving a better visibility ofdata while using the available space on the grid

Following code enables spilling of long text to adjacent empty cell in the WinForms FlexGrid

Handle Text in Node RowsThe Nodes setting is similar to Spill but only applies to outline nodes This setting is useful when data is organizedinto groups and the node rows contain information in a format different from the data rows For this you must setthe C1FlexGridAllowMerging property to Nodes

長いテキストを隣接する空のセルにこぼしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumSpill

C

長いテキストを隣接する空のセルにこぼしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumSpill

VBNET

FlexGrid for WinForms

148 Copyright copy GrapeCity Inc All rights reserved

Following code shows how to handle long text in node rows of the WinForms FlexGrid

ノード行の長いテキストを隣接する空のセルにスピルします c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumNodes

C

ノード行の長いテキストを隣接する空のセルにスピルしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumNodes

VBNET

カスタムのマージ

FlexGrid by default gives you enough options to merge in most common scenarios using AllowMerging propertyHowever there may be instances where you want to customize the merging options to get more out of your grid Youcan customize the default merging behavior in two ways

Method 1 Use IComparer InterfaceBy default the grid merges adjacent cells containing same non-null value In default scenario string comparisons arecase-sensitive and blanks are included However you can also merge cells using a case-insensitive comparison andtrimming blanks by writing a custom class that implements IComparer interface and assign it to CustomComparerproperty of the C1FlexGrid class

Method 2 Override the GetMergedRange MethodAnother way is to create a new class that derives from the C1FlexGrid class and overrides the GetMergedRangeand GetData methods to provide your own custom merging logic It merges the cells based on contextual

FlexGrid for WinForms

149 Copyright copy GrapeCity Inc All rights reserved

understanding of data in FlexGrid which is implemented through the overridden methods in the sample The belowexample demonstrates custom merging in timetable of each lecturer using the WinForms FlexGrid

public override CellRange GetMergedRange(int row int col bool clip) 結合のロジックで使用するID列のインデックスを保存します _colIndex = ColsIndexOf(LecturerID)

結合する時にカスタムデータを使用するようにフラグを設定します _doingMerge = true

基本クラスの結合のロジックを呼び出します(GetDataメソッドを使用してデータを取得します) CellRange cellRange = baseGetMergedRange(row col clip)

GetDataが通常どおりに動作するようにフラグをリセットします _doingMerge = false

結合された範囲を返します return cellRange

public override Object GetData(int row int col) 結合範囲を決定するためのデータを取得します ID列のコンテンツを追加して異なるIDの行のセルがマージされないようにします if (_doingMerge ampamp _colIndex gt -1 ampamp col = _colIndex) SystemDiagnosticsDebugWriteLine($rowcol) return baseGetDataDisplay(row col) + baseGetDataDisplay(row _colIndex)

C

FlexGrid for WinForms

150 Copyright copy GrapeCity Inc All rights reserved

For detailed implementation of more scenarios of custom merging see the product Projects named CustomMergeCustomMerge2 CustomMerge3 CustomMerge4

Note The abovementioned product samples are located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installingWinForms Edition using ComponentOneControlPanelexe

表示測定編集などするデータを取得します 基本クラスに通常どおり処理させます return baseGetData(row col)

Public Overrides Function GetMergedRange(ByVal row As Integer ByVal col As Integer ByVal clip As Boolean) As CellRange 結合のロジックで使用するID列のインデックスを保存します _colIndex = ColsIndexOf(LecturerID)

結合する時にカスタムデータを使用するようにフラグを設定します _doingMerge = True

基本クラスの結合のロジックを呼び出します(GetDataメソッドを使用してデータを取得します) Dim cellRange As CellRange = MyBaseGetMergedRange(row col clip)

GetDataが通常どおりに動作するようにフラグをリセットします _doingMerge = False

結合された範囲を返します Return cellRangeEnd Function

Public Overrides Function GetData(ByVal row As Integer ByVal col As Integer) As Object 結合範囲を決定するためのデータを取得します ID列のコンテンツを追加して異なるIDの行のセルがマージされないようにします If _doingMerge AndAlso _colIndex gt -1 AndAlso col ltgt _colIndex Then DebugWriteLine($rowcol) Return MyBaseGetDataDisplay(row col) + MyBaseGetDataDisplay(row _colIndex) End If

表示測定編集などするデータを取得します 基本クラスに通常どおり処理させます Return MyBaseGetData(row col)End Function

VBNET

FlexGrid for WinForms

151 Copyright copy GrapeCity Inc All rights reserved

グループ

Grouping refers to organizing the grid data into a hierarchical structure where rows with common column value aredisplayed as a group The feature also lets you expand or collapse the groups to facilitate easier analysis of grid data

In FlexGrid grouping can be achieved through code as well as through user interaction via column context menuand FlexGridGroupPanel control This topic discusses these ways and additional operations related to grouping

Grouping through CodeFlexGrid provides GroupDescriptions property to describe how data source items are grouped in the grid Thisproperty accepts the instance of any collection which implements IList interface (eg List) as its value The items of thecollection describe grouping using a property name as the criterion

Following code shows how to apply grouping in the WinForms FlexGrid through code

Grouping through Group Panel

CustomerIDでデータをグループ化しますc1FlexGrid1GroupDescriptions = new ListltGroupDescriptiongt() new GroupDescription(CustomerID)

C

CustomerIDでデータをグループ化しますc1FlexGrid1GroupDescriptions = New List(Of GroupDescription)() From New GroupDescription(CustomerID)

VBNET

FlexGrid for WinForms

152 Copyright copy GrapeCity Inc All rights reserved

FlexGrid also lets you create groups at runtime using an extension control named C1FlexGridGroupPanel which isprovided by the C1WinC1FlexGridGroupPanel assembly

To achieve grouping in FlexGrid at runtime add the C1FlexGridGroupPanel control to the form and bind it with thegrid to be bound using FlexGrid property of the C1FlexGridGroupPanel class Once a grid is bound to the grouppanel control you can drag and drop the columns to panel in order to group the grid by that column To create anested hierarchy of dragged columns you can drag multiple columns in the desired order You can also set themaximum number of groups allowed within FlexGrid using MaxGroups property of the C1FlexGridGroupPanel classBy default all the created groups appear in the expanded state To change this setting and display the groups incollapsed state by default you can set the AutoExpandAllGroups property to false The group panel control alsoprovides the Text property to display a string when no columns are dropped on the panel

Use the code below to apply grouping in WinForms FlexGrid through the FlexGridGroupPanel control

C1FlexGridGroupPanel c1FlexGridGroupPanel = new C1FlexGridGroupPanel()c1FlexGridGroupPanelBounds = new SystemDrawingRectangle(00 650 150)thisControlsAdd(c1FlexGridGroupPanel) C1FlexGridGroupPanelの一般プロパティを設定しますc1FlexGridGroupPanelFlexGrid = c1FlexGrid1c1FlexGridGroupPanelText = Drag the columns herec1FlexGridGroupPanelMaxGroups = 5c1FlexGridGroupPanelAutoExpandAllGroups = true

C

Dim c1FlexGridGroupPanel As C1FlexGridGroupPanel = New C1FlexGridGroupPanel() c1FlexGridGroupPanelBounds = New DrawingRectangle(0 0 650 150) MeControlsAdd(c1FlexGridGroupPanel)

VBNET

FlexGrid for WinForms

153 Copyright copy GrapeCity Inc All rights reserved

Grouping through Context MenuFlexGrid provides support for column context menu at run-time to facilitate quick actions related to columnoperations One of these context menu options is Group By This Column You can use this context menu option togroup the grid data by any of the columns at run-time Once grouping is applied you also get the Ungroup option toremove grouping To enable the column context menu you need to set ColumnContextMenuEnabled propertyprovided by the C1FlexGrid class to true By default this property is set to false

Grouping and MoreApart from the default features grouping in FlexGrid comes with many other options to give you ample flexibility tomeet your requirements

Use the SubtotalPosition property to change the position of group row which gets displayed above the groupby defaultSet the HideGroupedColumns property to true to hide the columns by which grid is groupedChange the format of group header by using the GroupHeaderFormat property By default the group row

C1FlexGridGroupPanelの一般プロパティを設定します c1FlexGridGroupPanelFlexGrid = c1FlexGrid1 c1FlexGridGroupPanelText = Drag the columns here c1FlexGridGroupPanelMaxGroups = 5 c1FlexGridGroupPanelAutoExpandAllGroups = True

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = true

C

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = True

VBNET

FlexGrid for WinForms

154 Copyright copy GrapeCity Inc All rights reserved

displays a string of namevalue formatSet the C1FlexGridAllowMerging property to AllowMergingEnumNodes to spill the long group headercontent into the adjacent empty cells For more information see Handle Text in Node RowsDisplay aggregate value of columns in group header by using Aggregate property of the Column classUse AllowSorting property to sort the groups based on their valuesUse the GridTreeStyle property to customize the appearance of outline tree that shows the grouping inFlexGrid For more information see Style the Tree Grid

FlexGrid for WinForms

155 Copyright copy GrapeCity Inc All rights reserved

集計

Summarizing data is one of the most important features of the grid where you can easily group the similar data andcalculate various types of aggregates such as Sum Average Count Max Min and more

In FlexGrid you can easily summarize data by using SubTotal method of the C1FlexGrid class It adds subtotal rows thatcontain aggregate data for the regular (non-subtotal) rows and also supports the hierarchical aggregates The method hasvarious overloads which gives you enough flexibility to deal with multiple summarizing related scenarios All theseoverloads have one parameter in common that is AggregateEnum which lets you set the type of aggregate you want toimplement Other parameters in various overloads let you set the outline level start and end column and column thatcontains values to be aggregated

Create SubtotalsBelow example demonstrates the use of SubTotal method in the WinForms FlexGrid for calculation of average aggregatebased on Score column

Style SubtotalsWhen the Subtotal method adds the rows with the aggregate information it automatically assigns in-built subtotal styles

グリッドに存在する既存の小計をすべてクリアしますc1FlexGrid1Subtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加しますc1FlexGrid1Subtotal(AggregateEnumAverage 1 3 3 4 Average for 0)

C

グリッドに存在する既存の小計をすべてクリアしますc1FlexGrid1Subtotal(AggregateEnumClear)

レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加しますc1FlexGrid1Subtotal(AggregateEnumAverage 1 3 3 4 Average for 0)

VBNET

FlexGrid for WinForms

156 Copyright copy GrapeCity Inc All rights reserved

to the new rows You can customize the appearance of the subtotal rows by changing the properties of the outline stylesin the designer with the Style Editor or using the code Below example demonstrates styling of subtotals at three levels inthe WinForms FlexGrid

Customize SubtotalsFlexGrid in addition to built-in aggregate options lets you create custom expressions in bound mode and use them assubtotals in groups along with aggregates You can specify the custom expressions for a column using GroupExpressionproperty of the Column class Below example demonstrates how to create a custom expression as a subtotal for Qualifiedcolumn of the WinForms FlexGrid

小計をレベル0でスタイル設定しますCellStyle s = c1FlexGrid1Styles[CellStyleEnumSubtotal0]sBackColor = ColorBlacksForeColor = ColorWhitesFont = new Font(c1FlexGrid1Font FontStyleBold) 小計をレベル1でスタイル設定しますs = c1FlexGrid1Styles[CellStyleEnumSubtotal1]sBackColor = ColorDarkBluesForeColor = ColorWhite

小計をレベル2でスタイル設定しますs = c1FlexGrid1Styles[CellStyleEnumSubtotal2]sBackColor = ColorDarkRedsForeColor = ColorWhitec1FlexGrid1AutoSizeCols()

C

Dim s As CellStyle = c1FlexGrid1Styles(CellStyleEnumSubtotal0) sBackColor = ColorBlack sForeColor = ColorWhite sFont = New Font(c1FlexGrid1Font FontStyleBold)

s = c1FlexGrid1Styles(CellStyleEnumSubtotal1) sBackColor = ColorDarkBlue sForeColor = ColorWhite

s = c1FlexGrid1Styles(CellStyleEnumSubtotal2) sBackColor = ColorDarkRed sForeColor = ColorWhite c1FlexGrid1AutoSizeCols()

VBNET

FlexGrid for WinForms

157 Copyright copy GrapeCity Inc All rights reserved

public void CustomizeSubTotal(C1FlexGrid c1FlexGrid1) ListltGroupDescriptiongt grps = new ListltGroupDescriptiongt() 列「Course」のグループを作成します GroupDescription grp = new GroupDescription(Course ListSortDirectionDescending true) grpsAdd(grp) 上記のグループに従ってFlexGridをグループ化します c1FlexGrid1GroupDescriptions = grps カスタムの計算式を使用してFlexGridに新しい列を追加します var column = c1FlexGrid1ColsAdd() columnName = Qualified columnDataType = typeof(object) columnCaption = Qualified(gt5000) columnAllowEditing = false columnExpression = [Attendance] [Score] GroupExpression の実装 c1FlexGrid1Cols[Score]GroupExpression = =Average([Score]) c1FlexGrid1Cols[Attendance]GroupExpression = =Average([Attendance]) c1FlexGrid1Cols[Qualified]GroupExpression = =iif(Average([Score][Attendance])lt5000falsetrue) c1FlexGrid1AutoSizeCols()

C

Public Sub CustomizeSubTotal(ByVal c1FlexGrid1 As C1FlexGrid) Dim grps As List(Of GroupDescription) = New List(Of GroupDescription)() 列「Course」のグループを作成します Dim grp As GroupDescription = New GroupDescription(Course ListSortDirectionDescending True) grpsAdd(grp)

上記のグループに従ってFlexGridをグループ化します c1FlexGrid1GroupDescriptions = grps

カスタムの計算式を使用してFlexGridに新しい列を追加します Dim column = c1FlexGrid1ColsAdd()

VBNET

FlexGrid for WinForms

158 Copyright copy GrapeCity Inc All rights reserved

columnName = Qualified columnDataType = GetType(Object) columnCaption = Qualified(gt5000) columnAllowEditing = False columnExpression = [Attendance] [Score]

GroupExpression の実装 c1FlexGrid1Cols(Score)GroupExpression = =Average([Score]) c1FlexGrid1Cols(Attendance)GroupExpression = =Average([Attendance]) c1FlexGrid1Cols(Qualified)GroupExpression = =iif(Average([Score][Attendance])lt5000falsetrue) c1FlexGrid1AutoSizeCols()End Sub

FlexGrid for WinForms

159 Copyright copy GrapeCity Inc All rights reserved

ツリーグリッド

OverviewOne of the unique and popular features of the FlexGrid control is the ability to add hierarchical grouping to regulardata grid and display it in a tree like structure called Tree Grid The Tree Grid control is very similar to the one you seein a TreeView control It shows an indented structure with collapse or expand icon next to each node row so the usercan expand and collapse the outline to see the desired level of detail by clicking on the nodes

Although you can create simple outline trees using FlexGrid grouping Tree Grid helps you implement more advanceduse cases such as displaying customer and order details In a usual grid showing such data it is difficult to see thedetails of each customer and order In such case you can create a Tree Grid to group the data in a hierarchicalstructure for better view and accessibility of information

Quick BindingLoading data in a Tree Grid is exactly the same as loading in a regular grid If the data source is available at designtime you can use the Visual Studio Property Window to set the grids DataSource property of the C1FlexGrid class andbind the grid to the data without writing even a single line of code For detailed steps see Bound Mode

You can also set the DataSource property through code Following code shows how to use the DataSource propertyto populate data in the WinForms Tree Grid

private void Bound_Node_Load(object sender EventArgs e) FlexGridを連結します BindGrid(_gridBound)

public void BindGrid(C1FlexGrid grid) DataTable _dt = new DataTable() データを取得します var fields = Country City SalesPerson Quantity ExtendedPrice var sql = stringFormat(SELECT 0 FROM Invoices ORDER BY 0 fields)

C

FlexGrid for WinForms

160 Copyright copy GrapeCity Inc All rights reserved

The code uses an OleDbDataAdapter to fill a DataTable with data then assigns datatable to DataSource property ofthe grid To turn this regular grid in a Tree grid you need to insert the node rows which is discussed in the sectionbelow

Create Nodes (Bound and Unbound Mode)To create a Tree Grid FlexGrid introduces a concept of Node rows These rows do not contain regular data and aresimply header rows under which similar data is grouped just like nodes in a usual TreeView control You can alsodefine the hierarchy of these nodes by setting the Level property These nodes can be collapsed and expanded to hideor show the data they contain The Tree Grid can be displayed in any column defined by the GridTreeColumnproperty By default this property is set to -1 which causes the tree not to be displayed at all

Bound Mode (Using InsertNode Method)

You can create node rows using InsertNode method of the RowCollection class which inserts a new node row at a

var da = new OleDbDataAdapter(sql GetConnectionString()) daFill(_dt) グリッドにデータを連結します gridDataSource = _dt ExtendedPrice 列を書式設定します gridCols[ExtendedPrice]Format = n2

static string GetConnectionString() string path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) + ComponentOne SamplesCommon string conn = provider=microsoftjetoledb40data source=0c1nwindmdb return stringFormat(conn path)

Private Sub Bound_Node_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを連結します BindGrid(_gridBound) End Sub

Public Sub BindGrid(ByVal grid As C1FlexGrid) Dim _dt As DataTable = New DataTable() データを取得します Dim fields = Country City SalesPerson Quantity ExtendedPrice Dim sql = StringFormat(SELECT 0 FROM Invoices ORDER BY 0 fields) Dim da = New OleDbDataAdapter(sql GetConnectionString()) daFill(_dt) グリッドにデータを連結します gridDataSource = _dt ExtendedPrice 列を書式設定します gridCols(ExtendedPrice)Format = n2 End Sub

Private Shared Function GetConnectionString() As String Dim path As String = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) amp ComponentOne SamplesCommon Dim conn As String = provider=microsoftjetoledb40data source=0c1nwindmdb Return StringFormat(conn path) End Function

VBNET

FlexGrid for WinForms

161 Copyright copy GrapeCity Inc All rights reserved

specified index This is the low-level way of inserting totals and building outlines

The GroupBy method used here inserts node rows by grouping identical values To obtain a Node object you caneither use return value of the InsertNode method or retrieve the node for an existing row using the IsNode property

Use the following code to create nodes using InsertNode method in the bound WinForms Tree Grid

private void Bound_Node_Load(object sender EventArgs e) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) GroupBy(_gridBound Country 0) GroupBy(_gridBound City 1) public void CreateTree(C1FlexGrid grid) gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)

void GroupBy(C1FlexGrid grid string columnName int level) レベル0でグループのスタイル設定します CellStyle s0 = gridStylesAdd(Group0) s0BackColor = ColorGray s0ForeColor = ColorWhite s0Font = new Font(gridFont FontStyleBold) レベル1でグループのスタイル設定します CellStyle s1 = gridStylesAdd(Group1) s1BackColor = ColorLightGray s1ForeColor = ColorBlack object current = null for (int r = gridRowsFixed r lt gridRowsCount r++)

C

FlexGrid for WinForms

162 Copyright copy GrapeCity Inc All rights reserved

if (gridRows[r]IsNode) var value = grid[r columnName] if (objectEquals(value current)) 値が変更されました ノードを挿入します gridRowsInsertNode(r level) if (level == 0) gridRows[r]Style = s0 else if (level == 1) gridRows[r]Style = s1 最初のスクロール可能な列にグループ名を表示します grid[r gridColsFixed] = value 現在の値を更新します current = value gridAutoSizeCols()

Private Sub Bound_Node_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) GroupBy(_gridBound Country 0) GroupBy(_gridBound City 1)End Sub

Public Sub CreateTree(ByVal grid As C1FlexGrid) gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)End Sub

Private Sub GroupBy(ByVal grid As C1FlexGrid ByVal columnName As String ByVal level As Integer) レベル0でグループのスタイル設定します Dim s0 As CellStyle = gridStylesAdd(Group0) s0BackColor = ColorGray s0ForeColor = ColorWhite s0Font = New Font(gridFont FontStyleBold) レベル1でグループのスタイル設定します Dim s1 As CellStyle = gridStylesAdd(Group1) s1BackColor = ColorLightGray s1ForeColor = ColorBlack Dim current As Object = Nothing Dim r As Integer = gridRowsFixed

While r And lt gridRowsCount End While

r += 1

If True Then

If Not gridRows(r)IsNode Then Dim value = grid(r columnName)

VBNET

FlexGrid for WinForms

163 Copyright copy GrapeCity Inc All rights reserved

The code also calls the AutoSizeCols method to ensure that the column is wide enough to accommodate the TreeGrid Finally it calls the GridTreeShow method to display the nodes

Also the Node class provides following methods and properties based on TreeView object model which can be usedto manage the Tree Grid

Checked Gets or sets the check state of cell defined by NodeRow and GridTreeColumnCollapsedExpanded Gets or sets collapsed or expanded state of the nodeData Gets or sets value in the cell defined by NodeRow and GridTreeColumnImage Gets or sets image in the cell defined by NodeRow and GridTreeColumnLevel Gets or sets node level in the Tree Grid

You can also explore the outline structure using the following properties and methods

Children Gets number of child nodes under this nodeGetCellRange Gets the CellRange object that described range of rows that belong to this nodeGetNode Gets the node that has a given relationship to this node (parent first child next sibling and so on)Nodes Gets a node array containing child nodes of this node

Bound Mode (Using Subtotal Method)

In bound mode another way to create nodes is using the Subtotal method To make the Tree Grid really useful thenode rows must include summary information for the data they contain

If you create Tree Grid using the Subtotal method the subtotals are added automatically The method scans theentire grid and automatically inserts node rows with optional subtotals at locations where the grid data changes

This is the high-level way of inserting totals and building outlines

If Not ObjectEquals(value current) Then 値が変更されました ノードを挿入します gridRowsInsertNode(r level)

If level = 0 Then gridRows(r)Style = s0 ElseIf level = 1 Then gridRows(r)Style = s1 End If

最初のスクロール可能な列にグループ名を表示します grid(r gridColsFixed) = value 現在の値を更新します current = value End If End IfEnd If gridAutoSizeCols()End Sub

FlexGrid for WinForms

164 Copyright copy GrapeCity Inc All rights reserved

The first parameter of the Subtotal method is AggregateEnum enumeration which calculates various types ofaggregates like Sum Average Count Max Min and others In the code below Subtotal method of the C1FlexGridclass is used for creating nodes in a bound WinForms Tree Grid

private void SubtotalNode_Bound_Load(object sender EventArgs e) FlexGridを取得します BindGrid(_gridBound) shows Tree in Bound FlexGrid CreateTree(_gridBound) 連結されたFlexGridに小計を作成します CreateSubTotal(_gridBound)public void BindGrid(C1FlexGrid grid) DataTable dt = new DataTable() dtColumnsAdd(ID typeof(int)) dtColumnsAdd(Name typeof(string)) dtColumnsAdd(Course typeof(string)) dtColumnsAdd(Score typeof(int)) dtColumnsAdd(Attendance typeof(int)) dtColumnsAdd(Country typeof(string)) サンプルデータ dtRowsAdd(1 Helen Bennett ComputerScience 79 84 Spain) dtRowsAdd(2 Ana Trujillo Biology 78 87 Mexico) dtRowsAdd(3 Antonio Moreno Aeronautics 71 70 Spain) dtRowsAdd(4 Paolo Accorti Biology 74 63 Spain) dtRowsAdd(5 Elizabeth Brown ComputerScience 80 93 Mexico) dtRowsAdd(6 Jaime Yorres Biology 61 48 Spain) dtRowsAdd(7 Yvonne Moncada Aeronautics 85 78 Mexico) dtRowsAdd(8 Martine Ranceacute Aeronautics 67 81 Spain) dtRowsAdd(9 Sergio Gutieacuterrezy ComputerScience 62 58 Mexico) dtRowsAdd(10 Thomas Hardy Aeronautics 94 92 Mexico) dtRowsAdd(11 Patricio Simpson Aeronautics 46 52 Spain) dtRowsAdd(12 Maria Anders ComputerScience 85 73 Spain) gridDataSource = dt gridAutoSizeCols() (gridDataSource as DataTable)DefaultViewSort = Course

C

FlexGrid for WinForms

165 Copyright copy GrapeCity Inc All rights reserved

FlexGridでツリーを作成しますpublic void CreateTree(C1FlexGrid grid) gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1) gridAutoSizeCols()public void CreateSubTotal(C1FlexGrid grid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加します gridSubtotal(AggregateEnumAverage 1 3 3 4 Average for 0) gridAutoSizeCols()

Private Sub SubtotalNode_Bound_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) Creates Subtotal(s) in Bound FlexGrid CreateSubTotal(_gridBound)End Sub

Public Sub BindGrid(ByVal grid As C1FlexGrid) Dim dt As DataTable = New DataTable() dtColumnsAdd(ID GetType(Integer)) dtColumnsAdd(Name GetType(String)) dtColumnsAdd(Course GetType(String)) dtColumnsAdd(Score GetType(Integer)) dtColumnsAdd(Attendance GetType(Integer)) dtColumnsAdd(Country GetType(String))

サンプルデータ dtRowsAdd(1 Helen Bennett ComputerScience 79 84 Spain) dtRowsAdd(2 Ana Trujillo Biology 78 87 Mexico) dtRowsAdd(3 Antonio Moreno Aeronautics 71 70 Spain) dtRowsAdd(4 Paolo Accorti Biology 74 63 Spain) dtRowsAdd(5 Elizabeth Brown ComputerScience 80 93 Mexico) dtRowsAdd(6 Jaime Yorres Biology 61 48 Spain) dtRowsAdd(7 Yvonne Moncada Aeronautics 85 78 Mexico) dtRowsAdd(8 Martine Ranceacute Aeronautics 67 81 Spain) dtRowsAdd(9 Sergio Gutieacuterrezy ComputerScience 62 58 Mexico) dtRowsAdd(10 Thomas Hardy Aeronautics 94 92 Mexico) dtRowsAdd(11 Patricio Simpson Aeronautics 46 52 Spain) dtRowsAdd(12 Maria Anders ComputerScience 85 73 Spain) gridDataSource = dt gridAutoSizeCols() TryCast(gridDataSource DataTable)DefaultViewSort = CourseEnd Sub

FlexGridでツリーを作成しますPublic Sub CreateTree(ByVal grid As C1FlexGrid) gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)

VBNET

FlexGrid for WinForms

166 Copyright copy GrapeCity Inc All rights reserved

Unbound Mode (Using Subtotal Method)

The Subtotal method is a very convenient and flexible way to create a tree grid It has a number of overloads thatallow you to specify which columns are to be grouped on and totaled on by index or by name whether to include acaption in the node rows that it inserts how to perform the grouping and so on

In the code below Subtotal method of the C1FlexGrid class is used for creating nodes in an unbound WinForms TreeGrid

gridAutoSizeCols()End Sub

Public Sub CreateSubTotal(ByVal grid As C1FlexGrid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加します gridSubtotal(AggregateEnumAverage 1 3 3 4 Average for 0) gridAutoSizeCols()End Sub

private void Unbound_Subtotal_Load(object sender EventArgs e) 連結されていないFlexGridにデータを追加します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) 連結されていないFlexGridに小計を作成します CreateSubTotal(_gridUnbound) public void PopulateGrid(C1FlexGrid grid) グリッドにデータを入力します Random rnd = new Random() gridRowsCount = 14 grid[0 1] = Direction grid[0 2] = Region CellRange rg = gridGetCellRange(0 3 0 gridColsCount - 1) rgData = Rnd

C

FlexGrid for WinForms

167 Copyright copy GrapeCity Inc All rights reserved

for (int r = 1 r lt gridRowsCount r++) grid[r 0] = r grid[r 1] = (r lt 7) Inbound Outbound grid[r 2] = (r lt 3) North (r lt 7) South (r lt 10) East West for (int c = 3 c lt gridColsCount c++) grid[r c] = rndNext(1000) gridCols[c]Format = gridAutoSizeCols()

FlexGridでツリーを作成しますprivate void ShowTreeNode(C1FlexGrid grid) ツリーを作成します gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols()

Creates Subtotal in FlexGridpublic void CreateSubTotal(C1FlexGrid grid) Clears any existing subtotal(s) present in grid gridSubtotal(AggregateEnumClear) for (int c = 3 c lt gridColsCount c++) Adds subtotals in grid gridSubtotal(AggregateEnumSum 0 -1 c Grand Total) gridSubtotal(AggregateEnumSum 2 2 c Total for 0) gridAutoSizeCols()

Private Sub Unbound_Subtotal_Load(ByVal sender As Object ByVal e As EventArgs) 連結されていないFlexGridにデータを追加します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) 連結されていないFlexGridに小計を作成します CreateSubTotal(_gridUnbound) End Sub

Public Sub PopulateGrid(ByVal grid As C1FlexGrid) グリッドにデータを入力します Dim rnd As Random = New Random() gridRowsCount = 14 grid(0 1) = Direction grid(0 2) = Region Dim rg As CellRange = gridGetCellRange(0 3 0 gridColsCount - 1) rgData = Rnd Dim r As Integer = 1

While r And lt gridRowsCount End While

VBNET

FlexGrid for WinForms

168 Copyright copy GrapeCity Inc All rights reserved

r += 1

If True Then grid(r 0) = r grid(r 1) = r And lt 7 Inbound Outbound grid(r 2) = r And lt 3 North r And lt 7 South r And lt 10 East West Dim c As Integer = 3

While c And lt gridColsCount End While

c += 1

If True Then grid(r c) = rnd[Next](1000) gridCols(c)Format = End If End If

gridAutoSizeCols() End Sub

FlexGridでツリーを作成します Private Sub ShowTreeNode(ByVal grid As C1FlexGrid) ツリーを作成しますFlexGridでツリーを作成します gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols() End Sub

FlexGridで小計を作成します Public Sub CreateSubTotal(ByVal grid As C1FlexGrid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) Dim c As Integer = 3

While c And lt gridColsCount End While

c += 1

If True Then グリッドに小計を追加します gridSubtotal(AggregateEnumSum 0 -1 c Grand Total) gridSubtotal(AggregateEnumSum 2 2 c Total for 0) End If

gridAutoSizeCols() End Sub

FlexGrid for WinForms

169 Copyright copy GrapeCity Inc All rights reserved

Unbound Mode(Using IsNode Property)

In an unbound grid you can turn regular rows into node rows by simply setting the IsNode property to true If youtry to turn a regular data bound row into a node it causes the grid to throw an exception

Use the following code to create nodes using IsNode property in an unbound WinForms Tree Grid

private void Unbound_Row_Load(object sender EventArgs e) 連結されていないFlexGridにデータを入力します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound)

private void PopulateGrid(C1FlexGrid grid) FlexGridをリセットします gridRowsCount = 0 gridColsCount = 2 string fileName = testxml xmlドキュメントをロードします XmlDocument xdoc = new XmlDocument() xdocLoad(fileName) XMLドキュメントを読み取りFlexGridのノードとして表示します ShowNode(_gridUnbound xdocChildNodes[1] 0) gridAutoSizeCols() FlexGridでツリーを作成しますprivate void ShowTreeNode(C1FlexGrid grid) ツリーを作成します gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols()

FlexGridにxmlノードを追加しますprivate void ShowNode(C1FlexGrid grid XmlNode node int level)

C

FlexGrid for WinForms

170 Copyright copy GrapeCity Inc All rights reserved

コメントノードをスキップします if (nodeNodeType == XmlNodeTypeComment) return 読み取りxmlノードの新しい行を追加します int row = gridRowsCount gridRowsAdd() グリッドのセルにxmlノードデータを割り当てます grid[row 0] = nodeName xmlノードに子が1つしかないかどうかを確認します if (nodeChildNodesCount == 1) グリッドのセルにノード値を設定します grid[row 1] = nodeInnerText 新しい行をノードにします gridRows[row]IsNode = true gridRows[row]NodeLevel = level ノードに子がある場合はそれらも取得します if (nodeChildNodesCount gt 1) 子を取得するために再帰します foreach (XmlNode child in nodeChildNodes) ShowNode(_gridUnbound child level + 1)

Private Sub Unbound_Row_Load(ByVal sender As Object ByVal e As EventArgs) 連結されていないFlexGridにデータを入力します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) End Sub

Private Sub PopulateGrid(ByVal grid As C1FlexGrid) FlexGridをリセットします gridRowsCount = 0 gridColsCount = 2 Dim fileName As String = testxml xmlドキュメントをロードします Dim xdoc As XmlDocument = New XmlDocument() xdocLoad(fileName) XMLドキュメントを読み取りFlexGridのノードとして表示します ShowNode(_gridUnbound xdocChildNodes(1) 0) gridAutoSizeCols() End Sub

FlexGridでツリーを作成します Private Sub ShowTreeNode(ByVal grid As C1FlexGrid) ツリーを作成します gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols() End Sub

FlexGridにxmlノードを追加します Private Sub ShowNode(ByVal grid As C1FlexGrid ByVal node As XmlNode ByVal level As Integer) コメントノードをスキップします If nodeNodeType Is XmlNodeTypeComment Then Return

VBNET

FlexGrid for WinForms

171 Copyright copy GrapeCity Inc All rights reserved

読み取りxmlノードの新しい行を追加します Dim row As Integer = gridRowsCount gridRowsAdd() グリッドのセルにxmlノードデータを割り当てます grid(row 0) = nodeName

xmlノードに子が1つしかないかどうかを確認します If nodeChildNodesCount = 1 Then グリッドのセルにノード値を設定します grid(row 1) = nodeInnerText End If

新しい行をノードにします gridRows(row)IsNode = True gridRows(row)NodeLevel = level

ノードに子がある場合はそれらも取得します If nodeChildNodesCount And gt Then End If

1

If True Then

子を取得するために再帰します For Each child As XmlNode In nodeChildNodes ShowNode(_gridUnbound child level + 1) Next End If End Sub

ノードの操作

Tree Grid not only allows you to present the data in a structured form but it also supports performing variousoperations with the nodes You can add delete move and fetch nodes by using various methods provided bythe Node class

FlexGrid for WinForms

172 Copyright copy GrapeCity Inc All rights reserved

Add NodeYou can add a node at a specific position in the Tree Grid using AddNode method of the Node class This appends anew node row to the collection The method takes NodeTypeEnum enumeration as its argument which lets youspecify a node with respect to another given node

The code below shows how to add a node in the WinForms Tree Grid at a specific location

private void cmbAdd_SelectionChangeCommitted(object sender SystemEventArgs e) 現在の行ノードを取得します Node nd = flexRows[flexRow]Node ユーザーの要求に応じて相対を追加します (could be a child or a sibling) ndAddNode((NodeTypeEnum)(cmbAddSelectedIndex + 2) cmbAddText) flexFocus()

C

Private Sub cmbAdd_SelectionChangeCommitted(ByVal sender As Object ByVal e As EventArgs) 現在の行ノードを取得します Dim nd As Node = flexRows(flexRow)Node ユーザーの要求に応じて相対を追加します (could be a child or a sibling) ndAddNode(CType(cmbAddSelectedIndex + 2 NodeTypeEnum) cmbAddText)

VBNET

FlexGrid for WinForms

173 Copyright copy GrapeCity Inc All rights reserved

Delete NodeYou can delete a selected node from the Tree Grid using RemoveNode method of the Node class

Following code demonstrates how to delete a node from the WinForms Tree Grid

Move NodeThe Tree Grid allows you to move the node rows to a new position using Move method of the Node class Themethod takes NodeMoveEnum enumeration as an argument which lets you specify the direction in which node hasto be moved

Use the code below to move a node of the WinForms Tree Grid to a new position

flexFocus()End Sub

private void btnDelete_Click(object sender SystemEventArgs e) 現在のノードを取得します Node nd = null if ( flexRowsCount gt 0 ampamp flexRow gt= 0 ampamp flexRow lt flexRowsCount) nd = flexRows[flexRow]Node if (nd = null) FlexGridからノードを削除します ndRemoveNode() flexFocus()

C

Private Sub btnDelete_Click(ByVal sender As Object ByVal e As EventArgs) 現在のノードを取得します Dim nd As Node = Nothing

If flexRowsCount gt 0 AndAlso flexRow gt= 0 AndAlso flexRow lt flexRowsCount Then nd = flexRows(flexRow)Node End If

If nd IsNot Nothing Then FlexGridからノードを削除します ndRemoveNode() flexFocus() End IfEnd Sub

VBNET

private void btnMove_Click(object sender SystemEventArgs e) 現在の行のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択した動きを適用します

C

FlexGrid for WinForms

174 Copyright copy GrapeCity Inc All rights reserved

Select NodesIn Tree Grid you can select the nodes to perform different operations using GetNode method of the Node class Themethod takes a parameter called NodeTypeEnum enumeration which specifies a node with respect to another givennode

The code below specifies how to fetch a specific node of the WinForms Tree Grid and show it in selected state

(これにより選択したノードが移動します) if (sender == btnMoveOut) ndMove(NodeMoveEnumOut) else if (sender == btnMoveIn) ndMove(NodeMoveEnumIn) else if (sender == btnMoveUp) ndMove(NodeMoveEnumUp) else if (sender == btnMoveDown) ndMove(NodeMoveEnumDown) else if (sender == btnMoveFirst) ndMove(NodeMoveEnumFirst) else if (sender == btnMoveLast) ndMove(NodeMoveEnumLast) ノードがまだ表示されていることを確認します ndEnsureVisible() flexFocus()

Private Sub btnMove_Click(ByVal sender As Object ByVal e As EventArgs) 現在の行のノードを取得します Dim nd As Node = flexRows(flexRow)Node

ユーザーが選択した動きを適用します (これにより選択したノードが移動します) If sender Is btnMoveOut Then ndMove(NodeMoveEnumOut) ElseIf sender Is btnMoveIn Then ndMove(NodeMoveEnum[In]) ElseIf sender Is btnMoveUp Then ndMove(NodeMoveEnumUp) ElseIf sender Is btnMoveDown Then ndMove(NodeMoveEnumDown) ElseIf sender Is btnMoveFirst Then ndMove(NodeMoveEnumFirst) ElseIf sender Is btnMoveLast Then ndMove(NodeMoveEnumLast) End If

ノードがまだ表示されていることを確認します ndEnsureVisible() flexFocus()End Sub

VBNET

private void cmbSelect_SelectionChangeCommitted(object sender SystemEventArgs e) 現在の行のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択したノードを取得します nd = ndGetNode((NodeTypeEnum)cmbSelectSelectedIndex) 失敗した場合はメッセージを表示します if (nd == null) MessageBoxShow(Cant find + cmbSelectText + for this node) return ノードを選択しそれが表示されていることを確認します(スクロールして表示します)

C

FlexGrid for WinForms

175 Copyright copy GrapeCity Inc All rights reserved

Expand and Collapse NodesYou can expand and collapse all nodes in your Tree Grid application using the Collapsed property of Node class asshown in the code below This feature makes it convenient to navigate through node headers as a group whenrequired

Following code shows how to expand and collapse nodes of the WinForms Tree Grid

ndSelect() ndEnsureVisible() flexFocus()

Private Sub cmbSelect_SelectionChangeCommitted(ByVal sender As Object ByVal e As EventArgs) 現在の行のノードを取得します Dim nd As Node = flexRows(flexRow)Node ユーザーが選択したノードを取得します nd = ndGetNode(CType(cmbSelectSelectedIndex NodeTypeEnum))

失敗した場合はメッセージを表示します If nd Is Nothing Then MessageBoxShow(Cant find amp cmbSelectText amp for this node) Return End If

ノードを選択しそれが表示されていることを確認します(スクロールして表示します) nd[Select]() ndEnsureVisible() flexFocus()End Sub

VBNET

foreach (Row row in flexRowsCastltRowgt()Where(rw =gt rwIsNode == true)) Node node = rowNode nodeCollapsed = false

foreach (Row row in flexRowsCastltRowgt()Where(rw =gt rwIsNode == true)) Node node = rowNode nodeCollapsed = true

C

For Each row As Row In flexRowsCast(Of Row)()Where(Function(rw) rwIsNode = True) Dim node As Node = rowNode nodeCollapsed = False Next

For Each row As Row In flexRowsCast(Of Row)()Where(Function(rw) rwIsNode = True) Dim node As Node = rowNode nodeCollapsed = True Next

VBNET

FlexGrid for WinForms

176 Copyright copy GrapeCity Inc All rights reserved

Drag and Drop NodesIn Tree Grid you can drag and drop a selected node to a specific position by handling the MouseUp MouseDownand MouseMove events

The code below lets the user drag and drop nodes of the WinForms Tree Grid

private void flex_MouseDown(object sender MouseEventArgs e) m_DragInfocheckDrag = false 左ボタンを押すと移動しません ドラッグするマウスの追跡を開始します if (eButton = MouseButtonsLeft) return if (chkDragChecked || m_DragInfodragging) return if (flexMouseRow lt flexRowsFixed || flexMouseCol = 0) return 現在の行とマウスの位置を保存します m_DragInforow = flexRow m_DragInfomouseDown = new Point(eX eY) チェックを開始します m_DragInfocheckDrag = true

private void flex_MouseMove(object sender MouseEventArgs e) チェックしてユーザーが許容範囲を超えた場合はドラッグを開始します if (m_DragInfocheckDrag || eButton = MouseButtonsLeft) return if (MathAbs(eX - m_DragInfomouseDownX) + MathAbs(eY - m_DragInfomouseDownY) lt= DRAGTOL) return フラグを更新します m_DragInfodragging = true Sets cursor and highlight node CellStyle cs = flexStyles[SourceNode] flexCursor = CursorsNoMove2D flexSetCellStyle(m_DragInforow 0 cs) ここにドロップできるかどうかを確認します Cursor c = (NoDropHere()) CursorsNo CursorsNoMove2D if (c = flexCursor) flexCursor = c private bool NoDropHere() カーソルの下の行は無効です if (flexMouseRow lt flexRowsFixed) return true カーソルの下の列が無効です if (flexMouseCol lt flexColsFixed) return true if (flexGetDataDisplay(flexRow 0) == SKU) return true return false private void flex_MouseUp(object sender MouseEventArgs e) マウスが再び下がるまでチェックしないでください m_DragInfocheckDrag = false Not dragging were done if (m_DragInfodragging) return ドラッグを停止します m_DragInfodragging = false flexSetCellStyle(m_DragInforow 0 (CellStyle)null) flexCursor = CursorsDefault ドロップが許可されているかどうかをテストします

C

FlexGrid for WinForms

177 Copyright copy GrapeCity Inc All rights reserved

if (NoDropHere()) return ノードを新しい親ノードに移動します Node ndSrc = flexRows[m_DragInforow]Node Node ndDst = flexRows[flexRow]Node ndSrcMove(NodeMoveEnumChildOf ndDst) ndSrcSelect()

internal struct DRAGINFO public bool dragging 現在ドラッグ中 public bool checkDrag 現在マウスをチェックしてドラッグを開始しています public int row ドラッグされている行のインデックス public Point mouseDown マウスダウンの位置

Private Sub flex_MouseDown(ByVal sender As Object ByVal e As MouseEventArgs) m_DragInfocheckDrag = False 左ボタンを押すと移動しません ドラッグするマウスの追跡を開始します If eButton IsNot MouseButtonsLeft Then Return If Not chkDragChecked OrElse m_DragInfodragging Then Return If flexMouseRow lt flexRowsFixed OrElse flexMouseCol ltgt 0 Then Return 現在の行とマウスの位置を保存します m_DragInforow = flexRow m_DragInfomouseDown = New Point(eX eY) チェックを開始します m_DragInfocheckDrag = True End Sub

Private Sub flex_MouseMove(ByVal sender As Object ByVal e As MouseEventArgs) チェックしてユーザーが許容範囲を超えた場合はドラッグを開始します If Not m_DragInfocheckDrag OrElse eButton IsNot MouseButtonsLeft Then Return If MathAbs(eX - m_DragInfomouseDownX) + MathAbs(eY - m_DragInfomouseDownY) lt= DRAGTOL Then Return フラグを更新します m_DragInfodragging = True カーソルを設定しノードを強調表示します Dim cs As CellStyle = flexStyles(SourceNode) flexCursor = CursorsNoMove2D flexSetCellStyle(m_DragInforow 0 cs) ここにドロップできるかどうかを確認します Dim c As Cursor = If((NoDropHere()) CursorsNo CursorsNoMove2D) If c IsNot flexCursor Then flexCursor = c End Sub

Private Function NoDropHere() As Boolean カーソルの下の行は無効です If flexMouseRow lt flexRowsFixed Then Return True カーソルの下の列が無効です If flexMouseCol lt flexColsFixed Then Return True If flexGetDataDisplay(flexRow 0) Is SKU Then Return True Return False End Function

Private Sub flex_MouseUp(ByVal sender As Object ByVal e As MouseEventArgs) マウスが再び下がるまでチェックしないでください m_DragInfocheckDrag = False If Not m_DragInfodragging Then Return ドラッグを停止します m_DragInfodragging = False

VBNET

FlexGrid for WinForms

178 Copyright copy GrapeCity Inc All rights reserved

flexSetCellStyle(m_DragInforow 0 CType(Nothing CellStyle)) flexCursor = Cursors[Default] ドロップが許可されているかどうかをテストします If NoDropHere() Then Return ノードを新しい親ノードに移動します Dim ndSrc As Node = flexRows(m_DragInforow)Node Dim ndDst As Node = flexRows(flexRow)Node ndSrcMove(NodeMoveEnumChildOf ndDst) ndSrc[Select]() End Sub

Friend Structure DRAGINFO Public dragging As Boolean 現在ドラッグ中 Public checkDrag As Boolean 現在マウスをチェックしてドラッグを開始しています Public row As Integer ドラッグされている行のインデックス Public mouseDown As Point マウスダウンの位置 End Structure

データの操作

In Tree Grid just like a usual grid you can also perform various operations at data level such as sorting and retainingthe changes

SortingTo apply sorting in Tree Grid you can select the parent node and sort the child nodes using Sort Method of the NodeClass You can specify the sorting order by using the SortFlags enumeration

Following code applies sorting on the WinForms Tree Grid

FlexGrid for WinForms

179 Copyright copy GrapeCity Inc All rights reserved

Retain the ChangesSo far we have discussed how to create trees and totals using the high-level Subtotal method as well as lower-level InsertNode and Aggregate methods

At this point it is important to remember that the Tree Grid is created based on the data but is not bound to it in anyway and is not automatically maintained when there are changes to the grid or to the data

For example if the user modifies a value in the column the subtotals will not be automatically updated If the usersorts the grid it refreshes the data and the subtotals disappear

There are two common ways to maintain the Tree Grid

1 Prevent the user from making any changes that would invalidate the tree This is the easiest option You can setthe grids AllowEditing AllowDragging and AllowSorting properties to false and prevent any changes thatwould affect the tree

2 Update the tree when there are changes to the data or to the grid You can attach handlers to thegrids AfterDataRefresh AfterSort and AfterEdit events and re-generate the outline appropriately

The second option is usually more interesting as it provides a quick and simple tool for dynamic data analysis Thisapproach is illustrated by a product sample Analyze shipped with the FlexGrid control The sample creates an initialoutline and allows users to reorder the columns When the column order changes the sample automatically re-sortsthe data and re-creates the outline

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing

private void btnSort_Click(object sender SystemEventArgs e) 現在のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択した並べ替えを適用します (これにより選択したノードの子が並べ替えられます) if (sender == btnSortAscending) ndSort(SortFlagsAscending) else ndSort(SortFlagsDescending) 完了 flexFocus()

C

Private Sub btnSort_Click(ByVal sender As Object ByVal e As EventArgs) 現在のノードを取得します Dim nd As Node = flexRows(flexRow)Node

ユーザーが選択した並べ替えを適用します (これにより選択したノードの子が並べ替えられます) If sender Is btnSortAscending Then ndSort(SortFlagsAscending) Else ndSort(SortFlagsDescending) End If

完了 flexFocus()End Sub

VBNET

FlexGrid for WinForms

180 Copyright copy GrapeCity Inc All rights reserved

WinForms Edition using ComponentOneControlPanelexe

In Create Nodes section we also learnt about implementing GroupBy method that inserts node rows groupingidentical values on a given column The code scans all the columns skipping existing node rows so it can be called toadd several levels of nodes and keeps track of the current value for the column being grouped on When the currentvalue changes a node row is inserted showing the new group name in the first scrollable column

However there are some challenges to maintain the grouping like the method assumes that data is sorted accordingto the outline structure Also the GroupBy method may insert rows which would cause the grid to flicker To avoidthis you would normally set the Redraw property to false before making the updates and set it back to true whendone

The DeferRefresh class is a simple utility that sets the grids Redraw property to false and restores its original valuewhen it is disposed This ensures that Redraw is properly restored even when exceptions happen during the updatesThe BindGrid method ensures that the grid is sorted in the order required by our outline structure

ツリーグリッドのカスタマイズ

FlexGrid allows you to customize Tree Grid by styling as well as by using various elements like checkboxes toexpandcollapse nodes or images as node icons A customized Tree Grid can make the outline tree nodes look moredistinctive and structured making it visually appealing and more understandable

Style Tree GridStyling a Tree Grid is similar to styling the FlexGrid control The Tree property returns a reference to a GridTree objectthat exposes several methods and properties used to customize the Tree Grid Following is the list of some commonlyused properties

Column Gets or sets the index of the column that contains the outline tree Setting this property to -1 causesthe outline tree to be hidden from the usersIndent Gets or sets the indent in pixels between adjacent node levels Higher indent levels cause the tree tobecome widerStyle Gets or sets the type of outline tree to display Use this property to determine whether the tree shouldinclude a button bar at the top to allow users to collapseexpand the entire tree whether lines andor symbolsshould be displayed and whether lines should be displayed connecting the tree to data rows as well as noderowsLineColor Gets or sets the color of the connecting linesLineStyle Gets or sets the style of the connecting lines

For more information on styling the tree grid see Styling and Appearance topic in FlexGrid documentation

Display Tree with CheckBoxesTo create a custom Tree Grid with checkbox and images you need to first initialize FlexGrid for creating Tree Grid andthen add nodes to the tree by using AddNode method of the RowCollection class

Now to implement checkboxes in Tree Grid you need to maintain the checkboxes in parent and child nodes Thismethod uses Checked property of the Node class which defines whether to show a checkbox for the node or not

FlexGrid for WinForms

181 Copyright copy GrapeCity Inc All rights reserved

The code below shows how to display checkboxes on tree nodes of the WinForms Tree Grid

void c1FlexGrid1_CellChecked(object sender C1WinC1FlexGridRowColEventArgs e) すべての子にチェック値を適用します var node = thisc1FlexGrid1Rows[eRow]Node UpdateCheckChildren(node) 親にチェック値を適用します UpdateCheckParent(node)

void UpdateCheckChildren(C1WinC1FlexGridNode node) var checkState = nodeChecked foreach (C1WinC1FlexGridNode child in nodeNodes) childChecked = checkState UpdateCheckChildren(child)

void UpdateCheckParent(C1WinC1FlexGridNode node) このノードの親を取得します var parent = nodeParent if (parent = null)

C

FlexGrid for WinForms

182 Copyright copy GrapeCity Inc All rights reserved

チェックされたチェックされていない子をカウントします int cntChecked = 0 int cntUnchecked = 0 int cntGrayed = 0 foreach (C1WinC1FlexGridNode child in parentNodes) switch (childChecked) case C1WinC1FlexGridCheckEnumChecked cntChecked++ break case C1WinC1FlexGridCheckEnumUnchecked cntUnchecked++ break case C1WinC1FlexGridCheckEnumGrayed cntGrayed++ break 親のチェック状態を更新します if (cntGrayed gt 0 || (cntChecked gt 0 ampamp cntUnchecked gt 0)) parentChecked = C1WinC1FlexGridCheckEnumGrayed else if (cntChecked gt 0 ampamp cntUnchecked == 0) parentChecked = C1WinC1FlexGridCheckEnumChecked else if (cntUnchecked gt 0 ampamp cntChecked == 0) parentChecked = C1WinC1FlexGridCheckEnumUnchecked 祖父も更新します UpdateCheckParent(parent)

Private Sub c1FlexGrid1_CellChecked(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) すべての子にチェック値を適用します Dim node = Mec1FlexGrid1Rows(eRow)Node UpdateCheckChildren(node) 親にチェック値を適用します UpdateCheckParent(node) End Sub

Private Sub UpdateCheckChildren(ByVal node As C1WinC1FlexGridNode) Dim checkState = nodeChecked

For Each child As C1WinC1FlexGridNode In nodeNodes childChecked = checkState MeUpdateCheckChildren(child) Next End Sub

Private Sub UpdateCheckParent(ByVal node As C1WinC1FlexGridNode) このノードの親を取得します Dim parent = nodeParent

If parent IsNot Nothing Then チェックされたチェックされていない子をカウントします

VBNET

FlexGrid for WinForms

183 Copyright copy GrapeCity Inc All rights reserved

Display Tree with ImagesTo add the images as your Tree Grid node icons you can use the AddImageFolder method for creating nodes relatedto files and assigning images to the nodes

Dim cntChecked As Integer = 0 Dim cntUnchecked As Integer = 0 Dim cntGrayed As Integer = 0

For Each child As C1WinC1FlexGridNode In parentNodes

Select Case childChecked Case C1WinC1FlexGridCheckEnumChecked cntChecked += 1 Case C1WinC1FlexGridCheckEnumUnchecked cntUnchecked += 1 Case C1WinC1FlexGridCheckEnumGrayed cntGrayed += 1 End Select Next

親のチェック状態を更新します If cntGrayed gt 0 OrElse cntChecked gt 0 AndAlso cntUnchecked gt 0 Then parentChecked = C1WinC1FlexGridCheckEnumGrayed ElseIf cntChecked gt 0 AndAlso cntUnchecked = 0 Then parentChecked = C1WinC1FlexGridCheckEnumChecked ElseIf cntUnchecked gt 0 AndAlso cntChecked = 0 Then parentChecked = C1WinC1FlexGridCheckEnumUnchecked End If

祖父も更新します UpdateCheckParent(parent) End If End Sub

FlexGrid for WinForms

184 Copyright copy GrapeCity Inc All rights reserved

Use the code below to display images or icons along with nodes of the WinForms Tree Grid

void AddImageFolder(string path int level) int cnt = 0 try ディレクトリ内のすべてのファイルをループします foreach (string file in DirectoryGetFiles(path)) ファイルごとにノードを作成しFlexGridに追加します var node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(file) 画像をノードに割り当てるためのコード ShowImage(node file) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt++ if (cnt gt 20) break catch try パスのすべてのサブディレクトリをループします foreach (string subPath in DirectoryGetDirectories(path))

C

FlexGrid for WinForms

185 Copyright copy GrapeCity Inc All rights reserved

ファイルごとにノードを作成しFlexGridに追加します var node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(subPath) 画像をノードに割り当てるためのコード ShowImage(node subPath) 現在のディレクトリのサブディレクトリファイルをトラバースします AddImageFolder(subPath level + 1) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt++ if (cnt gt 20) break catch

Private Sub AddImageFolder(ByVal path As String ByVal level As Integer) Dim cnt As Integer = 0

Try

ディレクトリ内のすべてのファイルをループします For Each file As String In DirectoryGetFiles(path) ファイルごとにノードを作成しFlexGridに追加します Dim node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(file)

画像をノードに割り当てるためのコード ShowImage(node file) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt += 1 If cnt gt 20 Then Exit For Next

Catch End Try

Try

パスのすべてのサブディレクトリをループします For Each subPath As String In DirectoryGetDirectories(path) ファイルごとにノードを作成しFlexGridに追加します Dim node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(subPath) 画像をノードに割り当てるためのコード ShowImage(node subPath) 現在のディレクトリのサブディレクトリファイルをトラバースします AddImageFolder(subPath level + 1) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt += 1 If cnt gt 20 Then Exit For Next

Catch End TryEnd Sub

VBNET

FlexGrid for WinForms

186 Copyright copy GrapeCity Inc All rights reserved

The above code uses a custom method called ShowImage to set the image for nodes based on its file extensions

public void ShowImage(C1WinC1FlexGridNode node string path) パスからファイル拡張子を取得します string extension = PathGetExtension(path) パスがファイルに属している場合 if (extension = ) ファイル拡張子に基づいてノードの画像を設定します switch (extension) case txt nodeImage = PropertiesResourcesTxt break case resx nodeImage = PropertiesResourcesTxt break case licx nodeImage = PropertiesResourcesTxt break case cs nodeImage = PropertiesResourcesTxt break case vb nodeImage = PropertiesResourcesTxt break case exe nodeImage = PropertiesResourcesExe break case dll nodeImage = PropertiesResourcesDll break case sln nodeImage = PropertiesResourcesVS break case csproj nodeImage = PropertiesResourcesVS break case bmp nodeImage = PropertiesResourcesImg break case png nodeImage = PropertiesResourcesImg break case gif nodeImage = PropertiesResourcesVideo break case accdb nodeImage = PropertiesResourcesAccess break default nodeImage = PropertiesResourcesUnknown break それ以外のパスはディレクトリフォルダに属しています else nodeImage = PropertiesResourcesFolder

C

FlexGrid for WinForms

187 Copyright copy GrapeCity Inc All rights reserved

Public Sub ShowImage(ByVal node As C1WinC1FlexGridNode ByVal path As String) パスからファイル拡張子を取得します Dim extension As String = PathGetExtension(path)

パスがファイルに属している場合 If Not Equals(extension ) Then

ファイル拡張子に基づいてノードの画像を設定します Select Case extension Case txt nodeImage = PropertiesResourcesTxt Case resx nodeImage = PropertiesResourcesTxt Case licx nodeImage = PropertiesResourcesTxt Case cs nodeImage = PropertiesResourcesTxt Case vb nodeImage = PropertiesResourcesTxt Case exe nodeImage = PropertiesResourcesExe Case dll nodeImage = PropertiesResourcesDll Case sln nodeImage = PropertiesResourcesVS Case csproj nodeImage = PropertiesResourcesVS Case bmp nodeImage = PropertiesResourcesImg Case png nodeImage = PropertiesResourcesImg Case gif nodeImage = PropertiesResourcesVideo Case accdb nodeImage = PropertiesResourcesAccess Case Else nodeImage = PropertiesResourcesUnknown それ以外のパスはディレクトリフォルダに属しています End Select Else nodeImage = PropertiesResourcesFolder End IfEnd Sub

VBNET

FlexGrid for WinForms

188 Copyright copy GrapeCity Inc All rights reserved

クリップボード

FlexGrid provides flexibility to perform various clipboard operations such as cut copy and paste on the editable griddata To enable automatic handling of common clipboard keys you need to set the AutoClipboard property to trueThe property handles following clipboard operations and their corresponding keys

Copy CTRL+C Ctrl+INS

Cut CTRL+X SHIFT+DEL

Paste CTRL+V SHIFT+INS

Delete DEL

The abovementioned clipboard operations do not have any affect on the styles and images and only work on gridheaders and data You can choose which part of the selected content to copy out of row header column headerand data by using the ClipboardCopyMode property When a datamap or multicolumn combobox exists in thecopied range only the display value is copied Also note that hidden cells are also copied when copying a cellrange To exclude hidden cells from copying see Exclude Hidden Cells

The code below demonstrates how to enable clipboard operations in the WinForms FlexGrid

Clipboard Operations through CodeYou can also perform clipboard operations through code The example below shows how to perform copying andpasting operations on button click

Use the code below to perform the clipboard operations through code in the WinForms FlexGrid

キーボードからクリップボード操作を有効にします c1FlexGrid1AutoClipboard = true データとすべてのヘッダーをコピーするようにコピーモードを設定します c1FlexGrid1ClipboardCopyMode = C1WinC1FlexGridClipboardCopyModeEnumDataAndAllHeaders

C

キーボードからクリップボード操作を有効にしますc1FlexGrid1AutoClipboard = True

データとすべてのヘッダーをコピーするようにコピーモードを設定しますc1FlexGrid1ClipboardCopyMode = C1WinC1FlexGridClipboardCopyModeEnumDataAndAllHeaders

VBNET

private void CopyButton_Click(object sender EventArgs e) クリップボードにコピーするグリッドのデータのみをコピーできるようにします c1FlexGrid1ClipboardCopyMode = ClipboardCopyModeEnumDataOnly

Clipプロパティに改行コードを追加しクリップボードに設定します ClipboardSetDataObject(c1FlexGrid1Clip + r) MessageBoxShow($Copied Range [c1FlexGrid1Rowc1FlexGrid1Col]-[c1FlexGrid1RowSelc1FlexGrid1ColSel])

C

FlexGrid for WinForms

189 Copyright copy GrapeCity Inc All rights reserved

Exclude Hidden CellsIn FlexGrid by default hidden cells are also copied when copying a cell range through keyboard operations enabledusing the AutoClipboard property However you can exclude the hidden rows and columns by using the code below

Following code shows how you can exclude the hidden cells from clipboard operations performed on the WinFormsTree Grid

private void PasteButton_Click(object sender EventArgs e) クリップボードのテキストを取得します IDataObject data = ClipboardGetDataObject() if (dataGetDataPresent(DataFormatsText)) string str1 str2 クリップボードからデータを取得します str1 = (string)dataGetData(DataFormatsText)

クリップボードから最後の行のフィードコードを削除します str2 = str1Remove(str1Length - 1 1)

範囲を選択してデータを貼り付けます c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col c1FlexGrid1RowsCount - 1 c1FlexGrid1ColsCount - 1 true) c1FlexGrid1Clip = str2 c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col)

Private Sub CopyButton_Click(ByVal sender As Object ByVal e As EventArgs) クリップボードにコピーするグリッドのデータのみをコピーできるようにします c1FlexGrid1ClipboardCopyMode = ClipboardCopyModeEnumDataOnly

Clipプロパティに改行コードを追加しクリップボードに設定します ClipboardSetDataObject(c1FlexGrid1Clip amp MicrosoftVisualBasicConstantsvbCr) MessageBoxShow($Copied Range [c1FlexGrid1Rowc1FlexGrid1Col]-[c1FlexGrid1RowSelc1FlexGrid1ColSel])End Sub

Private Sub PasteButton_Click(ByVal sender As Object ByVal e As EventArgs) クリップボードのテキストを取得します Dim data As IDataObject = ClipboardGetDataObject()

If dataGetDataPresent(DataFormatsText) Then Dim str1 str2 As String クリップボードからデータを取得します str1 = CStr(dataGetData(DataFormatsText))

クリップボードから最後の行のフィードコードを削除します str2 = str1Remove(str1Length - 1 1)

範囲を選択してデータを貼り付けます c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col c1FlexGrid1RowsCount - 1 c1FlexGrid1ColsCount - 1 True) c1FlexGrid1Clip = str2 c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col) End If

VBNET

C

FlexGrid for WinForms

190 Copyright copy GrapeCity Inc All rights reserved

列を非表示にしますc1FlexGrid1Cols[2]Visible = falsec1FlexGrid1AutoClipboard = true

次にCtrl + Cを押す前に非表示の列を含むいくつかのセルを選択しますprivate void c1FlexGrid1_KeyDown_1(object sender KeyEventArgs e) [Ctrl + C]でコピーします if ((eControl == true) ampamp (eKeyCode == KeysC)) 自動処理が行われないためキー入力を無効にします eHandled = true 選択したセル範囲のCellRangeオブジェクトを取得します C1WinC1FlexGridCellRange cr cr = c1FlexGrid1Selection

string StrCopy = for (int i = crr1 i lt= crr2 i++) if (c1FlexGrid1Rows[i]Visible == true) for (int j = crc1 j lt= crc2 j++) if (c1FlexGrid1Cols[j]Visible == true) StrCopy = StrCopy + c1FlexGrid1[i j]ToString() if (j = crc2) StrCopy = StrCopy + t StrCopy = StrCopy + n クリップボードに設定します ClipboardSetDataObject(StrCopy) MessageBoxShow(Copied data n + StrCopy)

列を非表示にします c1FlexGrid1Cols(2)Visible = False c1FlexGrid1AutoClipboard = True

次にCtrl + Cを押す前に非表示の列を含むいくつかのセルを選択しますPrivate Sub c1FlexGrid1_KeyDown_1(ByVal sender As Object ByVal e As KeyEventArgs)

[Ctrl + C]でコピーします If eControl = True AndAlso eKeyCode = KeysC Then 自動処理が行われないためキー入力を無効にします eHandled = True 選択したセル範囲のCellRangeオブジェクトを取得します Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1Selection Dim StrCopy =

VBNET

FlexGrid for WinForms

191 Copyright copy GrapeCity Inc All rights reserved

For i = crr1 To crr2

If c1FlexGrid1Rows(i)Visible = True Then For j = crc1 To crc2

If c1FlexGrid1Cols(j)Visible = True Then StrCopy = StrCopy amp c1FlexGrid1(i j)ToString()

If j ltgt crc2 Then StrCopy = StrCopy amp MicrosoftVisualBasicConstantsvbTab End If End If Next

StrCopy = StrCopy amp MicrosoftVisualBasicConstantsvbLf End If Next クリップボードに設定します ClipboardSetDataObject(StrCopy) MessageBoxShow(Copied data amp MicrosoftVisualBasicConstantsvbLf amp StrCopy) End IfEnd Sub

FlexGrid for WinForms

192 Copyright copy GrapeCity Inc All rights reserved

保存ロードと印刷

FlexGrid provides various built-in options so that you can easily save a grid and its content in a text excel or an XML file You can even load these saved filesto another grid or can save it as backup of a particular state of the grid You can also save the grid image in your desired format Not just this you can alsoprint the grid or selected areas of the grid if you need to have a hard copy This topic discusses various options related save load and print available in thegrid

Topic Content

Save Discusses about how to save the grid and its contents in different formats

Save as Text FileSave as Excel FileSave as XMLSave as Image

Load Discusses about how to load grid content from various file formats

Load from Text FileLoad from Excel FileLoad from DatabaseLoad from XML

Print Discusses about how to print the grid and other print related options

Print GridPrint OptionsCustomize Print Preview Dialog

保存

FlexGrid provides various methods to save the grid in the desired format such as text excel xml and image formatsThis feature is enabled through an assembly named C1WinC1FlexGridImportExportdll hence you need to addreference to this assembly to save the grid

Save as Text FileTo save grid content as a text file you can use the SaveGrid method of the Extensions class The method hasparameters that let you choose delimiter encoding and also lets you specify which portion of grid should be savedThe resulting text files can later be loaded back into the control or into other applications that support comma or tab-delimited files such as Microsoft Excel

Following code shows how to save content of the WinForms FlexGrid as a text file

private void btnSaveTxt_Click(object sender EventArgs e) c1FlexGrid1SaveGrid(ExportedGridtxt FileFormatEnumTextComma FileFlagsAsDisplayed | FileFlagsIncludeFixedCells)

C

Private Sub btnSaveTxt_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1SaveGrid(ExportedGridtxt FileFormatEnumTextComma FileFlagsAsDisplayed Or FileFlagsIncludeFixedCells)End Sub

VBNET

FlexGrid for WinForms

193 Copyright copy GrapeCity Inc All rights reserved

Save as Excel FileTo save grid as an excel file you can use the abovementioned SaveGrid method and simply set the format parameterto FileFormatEnumExcel You dont need to have Microsoft Excel installed on your computer However SaveGridmethod can only save the data in a workbook with single worksheet

To get an additional control over how you save your data to an excel file you can use the SaveExcel method insteadIn this case the process of saving excel files converts most data types and formatting information including row andcolumn dimensions fonts colors formats and cell alignment However some other features such as frozen andmerged cells images data maps and cell borders are not translated while converting to an excel file

Use the code below to save the WinForms FlexGrid as an Excel file

Save as XMLTo serialize grid contents into an XML document you can simply call WriteXML method of the C1FlexGrid class andparse path of the XML document as a parameter The method serializes all grid contents into the Xml documentincluding the data stored in the cells row and column properties styles and images Objects of custom types storedin the grid are also serialized as long as they have an associated SystemComponentModelTypeConverter thatprovides conversions to and from string

Below code demonstrates how to save contents of the WinForms FlexGrid to an XML document

Save as ImageTo save a grid as an image you can create the grid image using CreateImage method of the C1FlexGrid class andsave that image object at the specified path You can also specify a cell range or pass a cell range object as itsparameter to save a specific portion of the grid as an image

Use the code below to save the WinForms FlexGrid as an image

private void btnSaveExcl_Click(object sender EventArgs e) c1FlexGrid1SaveExcel(ExportedGridxlsx FileFlagsAsDisplayed | FileFlagsIncludeFixedCells)

C

Private Sub btnSaveExcl_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1SaveExcel(ExportedGridxlsx FileFlagsAsDisplayed Or FileFlagsIncludeFixedCells)End Sub

VBNET

private void btnSaveXML_Click(object sender EventArgs e) c1FlexGrid1WriteXml(ExportedGridxml)

C

Private Sub btnSaveXML_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1WriteXml(ExportedGridxml)End Sub

VBNET

FlexGrid for WinForms

194 Copyright copy GrapeCity Inc All rights reserved

private void btnSaveImg_Click(object sender EventArgs e) Image gridImage = c1FlexGrid1CreateImage() gridImageSave(ExportedGridpng)

C

Private Sub btnSaveImg_Click(ByVal sender As Object ByVal e As EventArgs) Dim gridImaage As Image = c1FlexGrid1CreateImage() gridImaageSave(ExportedGridpng)End Sub

VBNET

ロード

FlexGrid not only lets you save the grid to various formats but also lets you load data from various formats such textexcel XML or databases This feature is enabled through an assembly named C1WinC1FlexGridImportExportdllhence you need to add reference to this assembly to load the grid with data from these sources

Load from Text FileTo load data from a text file FlexGrid provides LoadGrid method of the Extensions class The method has parametersthat let you choose delimiter encoding etc You can also load text files saved using SaveGrid method When loadingtext files rows and columns are added to the grid if needed to accommodate the file contents The method supportsformats such as comma-delimited text files (CSV format) tab-delimited text files and even MS Excel files (xls)

Following code shows how to populate data in the WinForms FlexGrid by loading it from a text file

Load from Excel FileTo load grid from an excel file you can use the abovementioned LoadGrid method and simply set the formatparameter to FileFormatEnumExcel You dont need to have Microsoft Excel installed on your computer However theLoadGrid method can only load the data from first worksheet of a workbook

To get an additional control over how you load your data from an excel file you can use the LoadExcel methodinstead In this case the process of loading excel files converts most data types and formatting information includingrow and column dimensions fonts colors formats and cell alignment However there are still some exceptions Forexample the grid loads the values in excel cells but cannot load the underlying formulas Other features such asfrozen and merged cells images data maps and cell borders are not translated either

Use the code below to load contents in the WinForms FlexGrid from an excel file

private void btnLoadTxt_Click(object sender EventArgs e) c1FlexGrid1LoadGrid(ExportedGridtxt FileFormatEnumTextComma )

C

Private Sub btnLoadTxt_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1LoadGrid(ExportedGridtxt FileFormatEnumTextComma)End Sub

VBNET

FlexGrid for WinForms

195 Copyright copy GrapeCity Inc All rights reserved

Load from DatabaseTo load grid data from a database you can use the DataReader objects This process is different from data bindingwhich keeps a live connection between one or more controls and the underlying data source

Below code demonstrates how to load contents in the WinForms FlexGrid from the database

private void btnLoadExcl_Click(object sender EventArgs e) c1FlexGrid1LoadExcel(ExportedGridxlsx)

C

Private Sub btnLoadExcl_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1LoadExcel(ExportedGridxlsx)End Sub

VBNET

private void btnLoadDB_Click(object sender EventArgs e) DataReaderを準備します string strConn = data source=MYMACHINEinitial catalog=Northwind SystemDataSqlClientSqlConnection myConn = new SystemDataSqlClientSqlConnection(strConn) SystemDataSqlClientSqlCommand myCMD = new SystemDataSqlClientSqlCommand(SELECT FROM Employees myConn) myConnOpen() SystemDataSqlClientSqlDataReader myReader = myCMDExecuteReader()

DBスキーマからグリッド構造を構築します DataTable dt = myReaderGetSchemaTable() c1FlexGrid1ColsCount = 1 foreach (DataRow dr in dtRows) Column c =c1FlexGrid1ColsAdd() cCaption = cName = (string)dr[ColumnName] cDataType = (Type)dr[DataType]

グリッドにデータを入力します c1FlexGrid1RowsCount = 1 int row = 1 int cols = dtColumnsCount object[] v = (object[])ArrayCreateInstance(typeof(object) cols) while (myReaderRead()) myReaderGetValues(v) c1FlexGrid1AddItem(v row++ 1)

クリーンアップします c1FlexGrid1AutoSizeCols() myReaderClose() myConnClose()

C

FlexGrid for WinForms

196 Copyright copy GrapeCity Inc All rights reserved

Load from XMLTo deserialize grid contents from an XML document you can simply call ReadXML method of the C1FlexGrid classand parse path of the XML document as a parameter

Use the code below to load contents for the WinForms FlexGrid from an XML document

Private Sub btnLoadDB_Click(ByVal sender As Object ByVal e As EventArgs) DataReaderを準備します Dim strConn As String = data source=MYMACHINEinitial catalog=Northwind Dim myConn As New SqlClientSqlConnection(strConn) Dim myCMD As New SqlClientSqlCommand(SELECT FROM Employees myConn) myConnOpen() Dim myReader As SqlClientSqlDataReader = myCMDExecuteReader() DBスキーマからグリッド構造を構築します Dim dt As DataTable = myReaderGetSchemaTable() _flexColsCount = 1 Dim dr As DataRow For Each dr In dtRows Dim c As C1WinC1FlexGridColumn = _flexColsAdd() cCaption =(cName lt= CStr(dr(ColumnName))) cDataType = CType(dr(DataType) Type) Next dr グリッドにデータを入力します _flexRowsCount = 1 Dim row As Integer = 1 Dim cols As Integer = dtColumnsCount Dim v As Object() = CType(ArrayCreateInstance(GetType(Object) cols) Object()) While myReaderRead() myReaderGetValues(v) _flexAddItem(v row + 1 1) End While クリーンアップします _flexAutoSizeCols() myReaderClose() myConnClose()End Sub

VBNET

private void btnLoadXML_Click(object sender EventArgs e) c1FlexGrid1ReadXml(ExportedGridxml)

C

Private Sub btnLoadXML_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1ReadXml(ExportedGridxml)End Sub

VBNET

FlexGrid for WinForms

197 Copyright copy GrapeCity Inc All rights reserved

印刷

FlexGrid lets you print the grid and perform various basic and advanced print settings using its built-in methods andproperties

Print GridFlexGrid provides PrintGrid method of the C1FlexGrid class which lets you print the grid contents with some basicprinting options The method has an optional parameter PrintGridFlags that allows you to specify how to print thegrid such as its scaling mode and whether to display various print related dialog boxes You can also set text in headerand footer of the printed grid using this method

Following code shows how to use PrintGrid method to print the WinForms FlexGrid

Print OptionsTo set advanced printing options such as header and footer fonts page margins and page orientation you can usePrintParameter property of the C1FlexGrid class

Use the code below to print the WinForms FlexGrid with advanced print options

プレビューダイアログを表示し指定したヘッダとフッターでグリッドを印刷しますc1FlexGrid1PrintGrid(C1FlexGrid PrintGridFlagsFitToPageWidth | PrintGridFlagsShowPreviewDialog C1FlexGridtt + StringFormat(DateTimeNowToString() d) ttPage 0 of 1)

C

プレビューダイアログを表示し指定したヘッダとフッターでグリッドを印刷しますc1FlexGrid1PrintGrid(C1FlexGrid PrintGridFlagsFitToPageWidth Or PrintGridFlagsShowPreviewDialog C1FlexGrid amp vbTab amp vbTab amp StringFormat(DateNowToString() d) vbTab amp vbTab amp Page 0 of 1)

VBNET

FlexGrid for WinForms

198 Copyright copy GrapeCity Inc All rights reserved

Customize Print Preview DialogYou can customize the print preview dialog by using PrintPreviewDialog property of the GridPrinter class Theproperty can be accessed through PrintParameter property of the C1FlexGrid class The code below uses thePrintPreviewDialog property to display a maximized preview dialog with a custom caption

Below code demonstrates how to customize the print preview dialog of the WinForms FlexGrid

グリッドのPrintDocumentオブジェクトを取得しますSystemDrawingPrintingPrintDocument pd = c1FlexGrid1PrintParametersPrintDocument

ページを設定します(横向き15 左マージン)pdDefaultPageSettingsLandscape = truepdDefaultPageSettingsMarginsLeft = 150

ヘッダとフッタのフォントを設定しますc1FlexGrid1PrintParametersHeaderFont = new Font(Arial Black 14 FontStyleBold)c1FlexGrid1PrintParametersFooterFont = new Font(Arial Narrow 8 FontStyleItalic)

C

グリッドのPrintDocumentオブジェクトを取得しますDim pd As DrawingPrintingPrintDocument = c1FlexGrid1PrintParametersPrintDocument

ページを設定します(横向き15 左マージン)pdDefaultPageSettingsLandscape = TruepdDefaultPageSettingsMarginsLeft = 150

ヘッダとフッタのフォントを設定しますc1FlexGrid1PrintParametersHeaderFont = New Font(Arial Black 14 FontStyleBold)c1FlexGrid1PrintParametersFooterFont = New Font(Arial Narrow 8 FontStyleItalic)

VBNET

Form dlg = c1FlexGrid1PrintParametersPrintPreviewDialog as Form dlgText = Order Details dlgStartPosition = FormStartPositionCenterParent dlgWindowState = FormWindowStateMaximized c1FlexGrid1PrintGrid(Orders PrintGridFlagsShowPreviewDialog)

C

Dim dlg As Form = TryCast(c1FlexGrid1PrintParametersPrintPreviewDialog Form) dlgText = Order Details dlgStartPosition = FormStartPositionCenterParent dlgWindowState = FormWindowStateMaximized c1FlexGrid1PrintGrid(Orders PrintGridFlagsShowPreviewDialog)

VBNET

FlexGrid for WinForms

199 Copyright copy GrapeCity Inc All rights reserved

外観とスタイル設定

FlexGrid provides built-in visual styles as well as various design time and run time options so that you can style the grid and its elements as per the needsand appearance of your application The grid also provides style editors to let you customize appearance of your grid without writing a single line of codeFor more information about these editors and design time styling see Editors

This section discusses the built-in options provided by FlexGrid as well as various other ways to customize the appearance of grid and its elements

Topic Snapshot Content

Built-in Options Discusses about the available visual styles and built-in collection of styles

Visual StylesStyles Collection

Custom Styles Discusses how to create and apply the custom styles

Approach 1 Style an ObjectApproach 2 Create Re-usable Style

Customize Grid Discusses about customization at grid level

Set Alternate RowSet Background Image

Customize Border Discusses about customization of cell borders at row column or grid level

Customize Grid BorderCustomize RowColumn BorderCustomize Cell Border

Customize Text Discusses about various aspects of styling the grid text

Change FontSet MarginSet Vertical TextWrap TextDisplay Trimmed TextAlign TextApply Text Effect

Custom Glyphs Discusses about applying custom glyphs in the grid

組み込みオプション

Visual StylesFlexGrid provides six built-in visual styles so that you can easily customize the appearance of FlexGrid based on any ofthe Microsoft Office 2007 and 2010 themes These visual styles can be accessed through VisualStyle property ofthe C1FlexGrid class Apart from MS Office based visual styles you can also set this property to Custom and SystemWhen set to Custom the grid does not apply any visual styles and uses the grid properties for rendering When theproperty is set to System the grid renders its appearance based on current system settings

FlexGrid for WinForms

200 Copyright copy GrapeCity Inc All rights reserved

The property can be set using designer as well as through code To set the property at design time click smart tag toopen the C1FlexGrid Tasks menu and select a visual style from the VisualStyle combobox To apply visual style in theWinForms FlexGrid through code use the code below

Styles CollectionFlexGrid provides built-in collection of styles for predefined cell types and states such as normal cells fixed cellsfocused cells and so on You can use these built-in styles at design time as well as through code In design view youcan access these styles through the C1FlexGrid Style Editor which can be opened by clicking Styles option in Tasksmenu This collection of styles is represented by the CellStyleCollection class which can be accessed through Stylesproperty of the C1FlexGrid class Each built-in style is an object of the CellStyle class and holds various propertiessuch as BackColor DataType and Format

Following code shows how to use the styles from Styles collection of the WinForms FlexGrid

視覚スタイルをOffice2010Blueスキームに設定しますc1FlexGrid1VisualStyle = VisualStyleOffice2010Blue

C

視覚スタイルをOffice2010Blueスキームに設定しますc1FlexGrid1VisualStyle = VisualStyleOffice2010Blue

VBNET

組み込みセルスタイルNormalのプロパティを設定しますc1FlexGrid1Styles[Normal]BackColor = ColorAzurec1FlexGrid1Styles[Normal]ForeColor = ColorBlueViolet

固定セルの背景色を設定しますc1FlexGrid1Styles[Fixed]BackColor = ColorAqua

C

FlexGrid for WinForms

201 Copyright copy GrapeCity Inc All rights reserved

You can also add your own custom styles to Styles collection by using the Add method For more information abouthow to create and apply custom styles to grid cells see Custom Styles

組み込みセルスタイルNormalのプロパティを設定しますc1FlexGrid1Styles(Normal)BackColor = ColorAzurec1FlexGrid1Styles(Normal)ForeColor = ColorBlueViolet

固定セルの背景色を設定しますc1FlexGrid1Styles(Fixed)BackColor = ColorAqua

VBNET

カスタムのスタイル

Approach 1 Style an ObjectTo style a specific row column or a cell range of the WinForms FlexGrid you can use StyleNew property of the rowcolumn or cell range object

This approach is useful for styling a particular object when style is not expected to be reused To reuse a particularstyle you must create a style using the CellStyle object as discussed in the section below

Approach 2 Create Re-usable StyleIn this approach you can create a custom style as an object of CellStyle class and add it to the Styles collection usingthe Add method Then define its properties and apply it to a row column or cell range whenever required Asmentioned above this approach is very useful when you need to repeatedly use a particular style

Use the code below to create re-usable custom styles for your WinForms FlexGrid

特定の行にカスタムスタイルを適用しますc1FlexGrid1Rows[1]StyleNewBackColor = ColorAzurec1FlexGrid1Rows[1]StyleNewForeColor = ColorBlueViolet

C

特定の行にカスタムスタイルを適用しますc1FlexGrid1Rows(1)StyleNewBackColor = ColorAzurec1FlexGrid1Rows(1)StyleNewForeColor = ColorBlueViolet

VBNET

新しいスタイルを作成しスタイルコレクションに追加しますCellStyle cs = thisc1FlexGrid1StylesAdd(Custom) 新しいカスタムスタイルのプロパティを定義しますcsBackColor = ColorAzurecsForeColor = ColorBlueViolet

行にカスタムスタイルを適用しますc1FlexGrid1Rows[1]Style = cs

C

VBNET

FlexGrid for WinForms

202 Copyright copy GrapeCity Inc All rights reserved

新しいスタイルを作成しスタイルコレクションに追加しますDim cs As CellStyle = Mec1FlexGrid1StylesAdd(Custom)

新しいカスタムスタイルのプロパティを定義しますcsBackColor = ColorAzurecsForeColor = ColorBlueViolet

行にカスタムスタイルを適用しますc1FlexGrid1Rows(1)Style = cs

グリッドのカスタマイズ

FlexGrid also lets you customize overall look of the grid not to just increase its aesthetic value but also increases itsreadability You can add the alternate rows which make the grid more readable Also you can set image for instance awatermark or a company logo in background of the grid

Set Alternate RowTo set the alternate row color and styles in the grid you can use the built-in style Alternate either at design time orat runtime To apply style at design time you need to access the FlexGrid Style Editor and set properties for Alternatestyle

To apply alternate row style in the WinForms FlexGrid through code you need to use the CellStyle item Alternate ofthe CellStyleCollection class and set various properties for setting the alternate style

代替行の前色を設定します c1FlexGrid1Styles[Alternate]ForeColor = ColorWhite

代替行の背景色を設定します c1FlexGrid1Styles[Alternate]BackColor = ColorCadetBlue

C

FlexGrid for WinForms

203 Copyright copy GrapeCity Inc All rights reserved

Set Background Image in GridTo set the background image on a grid you can use the BackgroundImage property and assign the path of the imagefile to it Another property called BackgroundImageLayout property lets you choose whether and how to renderimage on the grid

Use the code below to set the background image on the WinForms FlexGrid

代替行の前色を設定しますc1FlexGrid1Styles(Alternate)ForeColor = ColorWhite

代替行の背景色を設定しますc1FlexGrid1Styles(Alternate)BackColor = ColorCadetBlue

VBNET

背景画像をグリッドに設定しますc1FlexGrid1BackgroundImage = ImageFromFile(CIMG-20190524-WA0037png)c1FlexGrid1BackgroundImageLayout = ImageLayoutStretch

C

背景画像をグリッドに設定しますc1FlexGrid1BackgroundImage = ImageFromFile(CIMG-20190524-WA0037png)c1FlexGrid1BackgroundImageLayout = ImageLayoutStretch

VBNET

境界線のカスタマイズ

The FlexGrid control lets you customize the border of grid row column and even cells by changing its style colordirection and so on

FlexGrid for WinForms

204 Copyright copy GrapeCity Inc All rights reserved

Customize Grid BorderTo customize border of the grid control you can use the BorderStyle property which accepts valuesfrom BorderStyleEnum provided by the C1WinFlexGridUtilBaseControls namespace

Following code shows how to customize border of the WinForms FlexGrid control

Customize RowColumn BorderTo customize the border style of a particular row or column you must access the Border item of CellStyle classusing StyleNew property and set its properties such as border style direction and color The grid controlprovides BorderStyleEnum as well as BorderDirEnum to set the border style and direction respectively

Use the below code to change border of rows or columns of the WinForms FlexGrid

Customize Cell BorderTo customize border of every cell in the grid you can access the built-in style Normal and set its border propertiesSimilarly you can change the style of specific types of cells such fixed or frozen by accessing their correspondingstyles from Styles collection

Below code lets you customize the border of normal cells of the WinForms FlexGrid

グリッドの境界線を3次元の境界線に変更しますc1FlexGrid1BorderStyle = C1WinC1FlexGridUtilBaseControlsBorderStyleEnumFixed3D

C

グリッドの境界線を3次元の境界線に変更しますc1FlexGrid1BorderStyle = C1WinC1FlexGridUtilBaseControlsBorderStyleEnumFixed3D

VBNET

最初の列の境界線スタイルを設定しますc1FlexGrid1Cols[1]StyleNewBorderStyle = BorderStyleEnumGroovec1FlexGrid1Cols[1]StyleNewBorderColor = ColorRedc1FlexGrid1Cols[1]StyleNewBorderDirection = BorderDirEnumVertical

最初の行の境界線スタイルを設定しますc1FlexGrid1Rows[1]StyleNewBorderStyle = BorderStyleEnumRaisedc1FlexGrid1Rows[1]StyleNewBorderColor = ColorBlue

C

最初の列の境界線スタイルを設定しますc1FlexGrid1Cols(1)StyleNewBorderStyle = BorderStyleEnumGroovec1FlexGrid1Cols(1)StyleNewBorderColor = ColorRedc1FlexGrid1Cols(1)StyleNewBorderDirection = BorderDirEnumVertical

最初の行の境界線スタイルを設定しますc1FlexGrid1Rows(1)StyleNewBorderStyle = BorderStyleEnumRaisedc1FlexGrid1Rows(1)StyleNewBorderColor = ColorBlue

VBNET

FlexGrid for WinForms

205 Copyright copy GrapeCity Inc All rights reserved

すべてのグリッドセルの境界線スタイルを設定しますc1FlexGrid1StylesNormalBorderStyle = BorderStyleEnumDouble

C

すべてのグリッドセルの境界線スタイルを設定しますc1FlexGrid1StylesNormalBorderStyle = BorderStyleEnumDouble

VBNET

テキストのカスタマイズ

FlexGrid lets you customize text in various ways such as changing its font margin orientation alignment effects and soon This topic caters to various aspects of text styling by taking a particular row object However if you wish to use anexisting built-in style or want to create your own custom style to re-use it see the corresponding topics

Change FontTo change font of text in a particular row or column object you can use Font property of its CellStyle Following codeshows how to change font of the WinForms FlexGrid row

カスタムスタイルを特定の行に適用しますc1FlexGrid1Rows[1]StyleNewFont = new Font(verdana 10 FontStyleUnderline)c1FlexGrid1Rows[0]StyleNewFont = new Font(verdana 10 FontStyleBold)

C

カスタムスタイルを特定の行に適用しますc1FlexGrid1Rows(1)StyleNewFont = new Font(verdana 10 FontStyleUnderline)c1FlexGrid1Rows(0)StyleNewFont = new Font(verdana 10 FontStyleBold)

VBNET

FlexGrid for WinForms

206 Copyright copy GrapeCity Inc All rights reserved

However if you want to change font of the whole grid you can set Font property of the C1FlexGrid class Followingcode shows how to change font of the entire WinForms FlexGrid

Set MarginTo set margin on text of a particular row or column you can set Margins property of the CellStyle Use the code belowto change margins in WinForms FlexGrid row

Set Vertical TextTo change the orientation and display a text as vertical text you can set TextDirection property of CellStyle of theobject Also to display the vertical text properly you may have to adjust height of the target cells depending upon thetext length Below code lets you set vertical text in the WinForms FlexGrid row

Wrap TextTo wrap a text which is longer than the available cell width you can set the WordWrap property of its CellStyle to trueFollowing code demonstrates how to apply text wrap in the WinForms FlexGrid row

グリッドの内容全体のフォントを変更しますc1FlexGrid1Font = new Font(verdana 10 FontStyleItalic)

C

グリッドの内容全体のフォントを変更しますc1FlexGrid1Font = New Font(verdana 10 FontStyleItalic)

VBNET

右側のマージンを設定しますc1FlexGrid1Rows[1]StyleNewMarginsRight = 10

C

右側のマージンを設定しますc1FlexGrid1Rows(1)StyleNewMarginsRight = 10

VBNET

行の内容のテキスト方向を設定しますc1FlexGrid1Rows[1]StyleNewTextDirection = TextDirectionEnumDown 行の高さを設定して垂直方向のテキストを表示しますc1FlexGrid1Rows[1]Height = 60

C

行の内容のテキスト方向を設定しますc1FlexGrid1Rows(1)StyleNewTextDirection = TextDirectionEnumDown

行の高さを設定して垂直方向のテキストを表示しますc1FlexGrid1Rows(1)Height = 60

VBNET

C

FlexGrid for WinForms

207 Copyright copy GrapeCity Inc All rights reserved

Display Trimmed TextTo display trimmed text when text is longer than the cell width set Trimming property of the style which takes its valuesfrom StringTrimming enumeration Use the code below to trim the long text to display ellipsis character in theWinForms FlexGrid row

Align TextYou can set the text alignment or position of the text with respect to cell by using the TextAlign property The propertyaccepts values from the TextAlignEnum enumeration

Use the code below to apply text alignment on the WinForms FlexGrid row

Apply Text EffectTo set various effects on the text you can use the TextEffect property which accepts its values from TextEffectEnumenumeration

Apply text on the WinForms FlexGrid row using the following code

セルの幅に応じて特定の行のテキストを折り返しますc1FlexGrid1Rows[1]StyleNewWordWrap = true

セルの幅に応じて特定の行のテキストを折り返しますc1FlexGrid1Rows(1)StyleNewWordWrap = True

VBNET

長いテキストをトリミングして最後に省略記号を表示しますc1FlexGrid1Rows[1]StyleNewTrimming = StringTrimmingEllipsisCharacter

C

長いテキストをトリミングして最後に省略記号を表示しますc1FlexGrid1Rows(1)StyleNewTrimming = StringTrimmingEllipsisCharacter

VBNET

テキストの配置を設定しますc1FlexGrid1Rows[1]StyleNewTextAlign = TextAlignEnumLeftCenter

C

テキストの配置を設定しますc1FlexGrid1Rows(1)StyleNewTextAlign = TextAlignEnumLeftCenter

VBNET

上げ表示するテキストを設定しますc1FlexGrid1Rows[1]StyleNewTextEffect = TextEffectEnumRaised

C

上げ表示するテキストを設定します c1FlexGrid1Rows(1)StyleNewTextAlign = TextAlignEnumLeftCenter

VBNET

FlexGrid for WinForms

208 Copyright copy GrapeCity Inc All rights reserved

カスタムのグリフ

FlexGrid lets you change the default glyph images used in the grid to indicate various actions such as column filteringand sorting This behavior of grid is exposed through GridGlyphs class which is a collection of images used by the gridto represent filtered state sorting order checkbox states and so on These images can be accessed through Glyphsproperty of the C1FlexGrid class which accepts values from GlyphEnum enumeration

Change the default glyphs used for filter editor and filtered column in the WinForms FlexGrid to a custom image usingthe code below

Note that setting this property to null restores the default glyph In order to hide a glyph you can set the Glyphproperty to a blank image

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilterEditor] = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilteredColumn] = ImageFromFile(filterico)

C

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilterEditor) = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilteredColumn) = ImageFromFile(filterico)

VBNET

FlexGrid for WinForms

209 Copyright copy GrapeCity Inc All rights reserved

永続的な状態

Grid persistence refers to saving the current state of the grid for later use and then restoring it back when needed Forinstance the user may apply grouping sorting filtering or some styling to the grid which he wants to use after fewmore operations or on opening the application again This behavior can be achieved by persisting the grids state

There are two steps to implement persistence of the grid state First we have to serialize the grid state and then werestore it In this topic we discuss how to persist the filtered sorted and grouped state of the FlexGrid control

You can implement persisting grid states by using XMLWriter and XMLReader class of the SystemXML namespace Tosave the grid state you can use the WriteStartElement method to write the specified start tag andWriteAttributeString method to write the filter sort and group attributes Finally call WriteEndElement method toclose the WriteStartElement method and save the state in the form of stream string or a file

Use the code below to serialize the state of WinForms FlexGrid to an XML file for later use

フィルタグループ並べ替えの定義をファイルに書き込みますprivate void WriteStateToXML(string filePath) using (XmlWriter writer = XmlWriterCreate(filePath)) writerWriteStartElement(FlexGrid) writerWriteStartElement(Definition ) writerWriteAttributeString(Filter flexGridFilterDefinition) writerWriteAttributeString(Sort flexGridSortDefinition) writerWriteAttributeString(Group flexGridGroupDefinition) writerWriteEndElement() writerWriteEndElement() writerFlush()

C

フィルタグループ並べ替えの定義をファイルに書き込みますPrivate Sub WriteStateToXML(ByVal filePath As String)

VBNET

FlexGrid for WinForms

210 Copyright copy GrapeCity Inc All rights reserved

To load the saved state back into the grid you can use the GetAttribute method of the object to read the filter sortand group attributes Then assign them to the FilterDefinition SortDefinition or GroupDefinition properties of theFlexGrid respectively

Use the code below to load saved state of the WinForms FlexGrid

Using writer = XmlWriterCreate(filePath) writerWriteStartElement(FlexGrid) writerWriteStartElement(Definition ) writerWriteAttributeString(Filter flexGridFilterDefinition) writerWriteAttributeString(Sort flexGridSortDefinition) writerWriteAttributeString(Group flexGridGroupDefinition) writerWriteEndElement() writerWriteEndElement() writerFlush() End UsingEnd Sub

保存したファイルからフィルタ並べ替えグループの定義を読み取りFlexGridに適用しますprivate void ReadStateXML(string filePath)

using (XmlReader reader = XmlReaderCreate(filePath)) readerReadToFollowing(Definition) flexGridSortDefinition = readerGetAttribute(Sort) flexGridFilterDefinition = readerGetAttribute(Filter) flexGridGroupDefinition = readerGetAttribute(Group) readerClose()

C

保存したファイルからフィルタ並べ替えグループの定義を読み取りFlexGridに適用しますPrivate Sub ReadStateXML(ByVal filePath As String) Using reader = XmlReaderCreate(filePath) readerReadToFollowing(Definition) flexGridSortDefinition = readerGetAttribute(Sort) flexGridFilterDefinition = readerGetAttribute(Filter) flexGridGroupDefinition = readerGetAttribute(Group) readerClose() End Using

VBNET

FlexGrid for WinForms

211 Copyright copy GrapeCity Inc All rights reserved

NET 5 リファレンス

FlexGrid for WinForms

212 Copyright copy GrapeCity Inc All rights reserved

NET 452 リファレンス

FlexGrid for WinForms

213 Copyright copy GrapeCity Inc All rights reserved

  • 目次
  • FlexGrid for WinForms
  • 主な特長
  • 機能比較
    • FlexGrid の比較
    • WinFormsグリッドの比較
      • クイックスタート
      • 設計時サポート
        • タスクメニュー
        • エディタ
          • データ
            • 非連結モード
            • 連結モード
              • 連結モードでの操作
                    • 基本操作
                    • ユーザー操作
                    • エディタ
                      • チェックボックス
                      • 数値
                      • 日付
                      • コンボボックス
                      • マスク
                      • マップリスト
                      • セルボタン
                        • 検証
                        • データ注釈
                        • スパークライン
                        • ヘッダとフッタ
                        • サイズ変更
                            • 基本操作
                            • ユーザー操作
                            • ヘッダ
                            • 行の詳細
                            • サイズ変更
                              • セル
                                • 基本操作
                                • セルの書式設定
                                  • グリッド
                                    • 基本操作
                                    • キーボードによる移動
                                    • パフォーマンスの向上
                                      • スクロールバー
                                      • 選択
                                      • 編集
                                        • 編集モード
                                        • 編集の無効化
                                          • 並べ替え
                                            • 並べ替えの操作
                                            • 並べ替えのインジケータ
                                              • フィルタ
                                                • フィルタの操作
                                                  • フィルタの種類
                                                    • フィルタUI
                                                      • 検索
                                                      • マージ
                                                        • 自動マージ
                                                        • はみ出して表示されるセルの処理
                                                        • カスタムのマージ
                                                          • グループ
                                                          • 集計
                                                          • ツリーグリッド
                                                            • ノードの操作
                                                            • データの操作
                                                            • ツリーグリッドのカスタマイズ
                                                              • クリップボード
                                                              • 保存ロードと印刷
                                                                • 保存
                                                                • ロード
                                                                • 印刷
                                                                  • 外観とスタイル設定
                                                                    • 組み込みオプション
                                                                    • カスタムのスタイル
                                                                    • グリッドのカスタマイズ
                                                                    • 境界線のカスタマイズ
                                                                    • テキストのカスタマイズ
                                                                    • カスタムのグリフ
                                                                      • 永続的な状態
                                                                      • NET 5 リファレンス
                                                                      • NET 452 リファレンス
Page 6: FlexGrid for WinForms

主な特長

Code-free Development

Why write code when a click is enough With rich design-time options beginning from binding to styling whichare accessible through the tasks menu and various editors FlexGrid lets you do a lot even without writing a single lineof code

Advanced Cell Editing

Choose from a variety of built-in editors or just create one for yourself FlexGrid offers various built-in cell editors sothat you can choose from simple text editing drop-down lists combo lists cell buttons masks and so on Not justthis with an option to create your own custom cell editors you can change your cells to accept or display almostany type of data

Work in Bound Mode or Unbound Mode

Bound grid or unbound populate the data seamlessly FlexGrid lets you bind the grid with any of the NET datasources such as ADONET and DataObjects for NET You can also work in unbound mode and let FlexGrid manage thedata itself

Present Hierarchical Data

View data the way that is best for you and your users When FlexGrid is bound to a hierarchical data source eachmaster record can be expanded or collapsed to show or hide the details in child grids which may contain moredetails The result is a data tree similar to the type of grid presented by Microsoft Access when displayinghierarchical data When bound the control detects subordinate data sources and creates additional instances of itselfto display child tables

Summarize Data and Show Aggregates

Get a quick outline of your grid data by summarizing it FlexGrid allows you to summarize data by adding a subtotalrow and display aggregates such as sum average count and so on for the specified column

Make it a Tree

Easily display your hierarchical data by converting your grid into a tree FlexGrid lets you represent your bound orunbound hierarchical data in Tree Grid which is similar to a TreeView control and gives a clean yet accessible structureto the data

Built-in Data Filtering

Let your users filter the data by value by condition or just give them both the options to choose from FlexGridprovides advanced built-in filtering with column filter value filter and condition filter already in place Still does notwork for you Create your own custom filter using rich FlexGrid API

Grouping

Group programmatically or at run-time With FlexGrid both are possible FlexGrid lets you group either through codeand even give your users an option to group at run-time using the FlexGridGroupPanel control or through contextmenu

Instant Search

Search the entire grid in one go and locate entries among millions of records instantly FlexGridprovides FlexGridSearchPanel control which lets the user type in the search box filters the records that match thetyped text and also highlights the search results

Merge Cells

Give your grid a tidy look by merging the cells with the same values FlexGrid lets you merge the contiguous cells withthe same values the way you want With free and restricted auto-merge options the grid can intelligently decidewhich cells to merge

Save and Load Multiple Formats

Back up the grid data or load it back in a jiffy FlexGrid lets you save the grid in your favorite format be it a text fileexcel file or XML You can even load content from these formats Not just this you can also load grid data from a

FlexGrid for WinForms

5 Copyright copy GrapeCity Inc All rights reserved

database using DataReader objects

Show Sparklines

Perk up your grid with the tiny charts FlexGrid allows you to add sparklines to grid columns so that you can easilydisplay trends and fluctuations in a single cell and make your grid data more useful and attractive at the same time

Perform Clipboard Operations

Move your text easily with Ctrl+C and Ctrl+V FlexGrid lets you perform clipboard operations on the grid data andheaders using your favorite keys

Assign Field Names to Columns

No need to remember the index of columns just call them by name FlexGrid automatically assigns column keysto field names when the grid is data-bound or you may assign them through code You can refer to a column using aColIndex(ColKey) syntax later which will retrieve the column you want even if your user has moved it to a differentposition on the grid

Use Data Annotations

Hint the user with data annotations FlexGrid lets you add data annotations in the form of metadata tags to theclasses and other objects to display messages and tips for the users

UI Automation and Support

Enable accessible and rich client applications through UI Automation (UIA) FlexGrid control supports UI Automationusing frameworks such as TestStackWhite You can enable applications such as screen readers coded UI testing toexamine user-interface elements and even simulated user interaction through code

Note UI Automation works only for the 452 version of C1FlexGrid and NET framework 47 or above applicationtarget frameworks

Add Special Drawing Effects

Make your grid look different and attractive with special drawing effects FlexGrid lets you paint special drawingeffects such as lines bitmaps and icons in the grid cells Additionally you can even scale images and addtransparency to them

Display Images in Cells

Need to display images in columns not an issue at all With FlexGrid you can display images along with data You caneven bind grid columns to image lists an easy and efficient way to display graphical information from data sources

Integrated Printing

Print the grid with a single statement FlexGrid gives you control over paper orientation margins header and footertext as well as the dialog boxes to set up the printer or see a preview You can even implement advanced printingoptions such as adding page breaks or custom elements to each page by using printing events

Styling

Use the visual styles or create your own custom styling use the designer or write your own code FlexGrid gives youenormous options to customize the appearance of the grid to match your requirements You can customize everyelement of the FlexGrid starting from headers and icons to borders and subtotal rows

FlexGrid for WinForms

6 Copyright copy GrapeCity Inc All rights reserved

機能比較

This section compares the features of various FlexGrids available across different platforms as well as shows acomparison with MS DataGridView

Topic Content

ComparingFlexGrids

Lists the difference between ActiveX version(VSFlexGrid control) and NET version of the FlexGridcontrol making it easy to migrate your grid from AciveX to NET

VSFlexGrid (ActiveX) and C1FlexGrid (NET)

ComparingWinForms Grids

Shows comparison between features of grids available in ComponentOne WinForms Edition andMS DataGridView

FlexGrid or True DBGridComparing ComponentOne Grids with MS DataGridView

FlexGrid の比較

VSFlexGrid (ActiveX) and C1FlexGrid (NET)ComponentOne provides ActiveX as well as NET version of the FlexGrid control While the ActiveX version is known asVSFlexGrid the NET version is shipped in the name of C1FlexGrid Being a NET version C1FlexGrid came laterinto the picture and instead of porting from the already existing VSFlexGrid we decided to create a brand new gridcontrol written from the ground up in C with the same design principles but with a new object model that is moremodern clean and powerful than the one in the ActiveX control

This section caters to original users of the VSFlexGrid control who want to migrate their applications from ActiveX tothe NET version that is the C1FlexGrid control To facilitate the hassle-free migration and a smooth learning curvethe NET version provides the C1FlexGridClassic control that derives from the C1FlexGrid class and provides an objectmodel that is virtually identical to the VSFlexGrid control The C1FlexGridClassic control is available in the form of aproduct sample Classic so that you may know exactly how to use the new object model This sample can also beused as a reference for creating the custom grid controls based on the C1FlexGrid class

Note The Classic sample is located at DocumentsComponentOne SamplesWinFormsv452C1FlexGridCS onyour system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

For users creating new applications we recommend using the new C1FlexGrid control However for the users who areporting their existing applications from ActiveX to NET we recommend using the C1FlexGridClassic control tominimize the programming effort Following table highlights some of the key differences between VSFlexGrid andC1FlexGrid

VSFlexGrid (ActiveX) C1FlexGrid (NET)

RowsCols1 Rows and Cols properties are used to

get or set the number of rows andcolumns

2 VSFlexGrid uses the TextMatrixproperty to represent the rows andcolumns

1 In C1FlexGrid Rows and Cols propertiesreturn the rows and column collectionsThe collections have readwriteproperties that return the number ofelements and fixed elements in eachcollection

FlexGrid for WinForms

7 Copyright copy GrapeCity Inc All rights reserved

For instance in ActiveX you would write

Dim r c c = 1

For r = c1FlexGrid1FixedRows To

c1FlexGrid1Rows - 1

DebugPrint

c1FlexGrid1TextMatrix(rc)

Next

2 C1FlexGrid uses indexers to representrows and columns

For instance in NET you would write

Dim r c c = 1

For r = c1FlexGrid1RowsFixed To

c1FlexGrid1RowsCount - 1

DebugPrint(c1FlexGrid1(r c))

Next

CellCell range The Cell property is one of the mostpowerful elements of the VSFlexGrid objectmodel It allows you to get or set anyproperty of any cell or cell range with asingle command Using a single propertymeans using variants and this prevents thecompiler from catching many subtleproblems in case you make mistakes whilecoding

For instance in ActiveX you would write

flexCell(flexcpPicture 5 5

10 10)

= theImage

In C1FlexGrid CellRange object has replacedthe Cell property to expose type-safeproperties and methods for accessing cellrange So if variable theImage contained astring instead of an image you get a compilererror and not a runtime error Also you getcommand-completion when writing the codebecause the types for each property are known

For instance in NET you would write

Dim rg As CellRange

rg =

c1FlexGrid1GetCellRange(551010)

rgImage = theImage

Typed Columns In the ActiveX version the ColDataTypeproperty allows you to set the type of datathat each column contains This informationis used mainly for sorting columns thatcontain dates or numbers

In the NET version Cols[i]DataType propertydetermines the type of data the column holdsBy default the DataType property for allcolumns is set to object that is you can storeany type of data in any column You can set thedata type to specific types however the gridtries to coerce any data stored in the grid tothe proper type

For instance in NET you would write

c1FlexGrid1Cols(2)DataType =

GetType(Integer)

Sets the value to 12

c1FlexGrid1(1 2) = 12

Can not convert hello string to

integer

Fires the GridError event

Retains the original value

c1FlexGrid1(2 2) = hello

Styles In VSFlexGrid you can customize theappearance of individual cells or cell rangesusing the Cell property

For instance in ActiveX you would write

Set the backcolor of second row

c1FlexGrid1Cell(flexcpBackColor

In C1FlexGrid cell appearance can becustomized using the CellStyle object

For instance in NET you would write

Create a cell style

Dim redStyle As CellStyle =

c1FlexGrid1Styles

FlexGrid for WinForms

8 Copyright copy GrapeCity Inc All rights reserved

2 0 2

c1FlexGrid1Cols-1) = vbRed

Demerit

To change the appearance of all red cellsyou need to clear all styles and start again oryou need to scan for red cells and thenchange their appearance

Add(Red)

redStyleBackColor = ColorRed

Set the backcolor of second row

c1FlexGrid1Rows(2)Style =

redStyle

Merit

The main advantage of this approach is that thenew style is an object that can be changed orassigned to new ranges For instance tochange the fore-color and text font of red cellsyou would write

c1FlexGrid1Styles(Red)ForeColor

= ColorWhite

c1FlexGrid1Styles(Red)Font =

new Font(Arial 9)

The VSFlexGrid control had many propertiesthat affected the way the grid was displayed(eg BackColor BackColorAlternateBackColorBkg BackColorFixedBackColorFrozen BackColorSel and so on)

The C1FlexGrid control replaces all theseproperties with a collection of CellStyle objectsso you can write something likeStylesFixedBackColor orStylesHighlightForeColor This makes theobject model simpler more consistent andmore powerful You can change the built-instyles or define your own and assign them torows columns or arbitrary cell ranges

WinFormsグリッドの比較

FlexGrid or True DBGridComponentOne offers two grid components in WinForms Edition FlexGrid and True DBGrid While both of these are robust and easy-to-usegrids allowing you to browse edit add delete and manipulate tabular data they still have their own strengths and capabilities

Both ComponentOne WinForms Edition grids can be used in bound as well as unbound mode but C1FlexGrid allows you to work more easilyin unbound mode With C1FlexGrid you can customize trees and make use of its cell merging capabilities FlexGrid is also apt for deriving acustomized grid

If you are planning to develop or migrate to NET 5 or higher it is recommended to use C1FlexGrid While we will continue to supportC1TrueDBGrid in NET 5 it no longer receives new enhancements and features like C1FlexGrid

Comparing ComponentOne Grids with MS DataGridViewThis section gives you a quick comparison between the two ComponentOne WinForms Edition grids and the standard MS DataGridViewavailable for WinForms platform For easy navigation we have broadly divided these features into different categories Click on thecorresponding category in the right hand pane or scroll down to know more about availability of a particular feature

Data Binding

Features FlexGrid TrueDBGrid MS DataGridView

Binding Data Sources

Binding Data Sources with hierarchical datarelations

With custom code

Unbound data storage and manipulations

Data Presentation

FlexGrid for WinForms

9 Copyright copy GrapeCity Inc All rights reserved

Features FlexGrid TrueDBGrid MS DataGridView

Hierarchical Styles With custom code

TreeView-like Styles

MultiLine Data View

Grouping

Built-in Drag And Drop

Horizontal and Vertical Interactive Splits

Child grids within master grid support

Drop-Down Objects Support

Drop-Down Multicolumn Object support

Drop-Down Multicolumn Bindable and SortableObject support

Data Exchange

Features FlexGrid TrueDBGrid MS DataGridView

Export Data (Delimited Text XLS and XLSX)

Export Data in other formats (PDF HTML RTFJPG and other)

Load data from Excel files

Enhanced Printing data from grid and PrintPreview support

Cell Manipulations

Features FlexGrid TrueDBGrid MS DataGridView

In-Cell Objects

Enhanced Cell Editing with Custom Editors

Merging Cells and Rows

Customize Cells Merging

Drag And Drop Columns and rows

Automatic Cell Sizing

Fixed Non-scrolling Columns

Excel-style Cell Selection

Customize each Cell Rendering

Zooming Cells

Run-Time CellTips

Data Manipulations with Cell Ranges

Layout and Styling

Features FlexGrid TrueDBGrid MS DataGridView

Visual Styles Support

Dynamic Support of 38 Decoration Themes

Office 2007 and 2010 Styling

Alternating Row Colors

Customizable Cell Border Style

FlexGrid for WinForms

10 Copyright copy GrapeCity Inc All rights reserved

Add Special Drawing Effects

Data-Sensitive Display

Input and Navigation

Features FlexGrid TrueDBGrid MS DataGridView

Input Masking

Simplify Data Input

Automatic Data Translation

Spell Checking support

Customizable Keyboard Navigation and keysbehavior

Right-To-Left navigation

Touch Support

Clipboard support

Rich Scrolling Capabilities

Data Manipulations

Features FlexGrid TrueDBGrid MS DataGridView

Sorting

Multi-column Sorting

Built-in Data Filtering

Extended and Conditional Filtering

Customizable filter form

Additional Filter Bar row

Multi-language Filtering

AutoSearch

Range Aggregates

Localization

Features FlexGrid TrueDBGrid MS DataGridView

Right-To-Left support

Net localization support

Regional settings support

Other Features

Features FlexGrid TrueDBGrid MS DataGridView

Optimize performance for displaying largeamount of data in bound and unbound mode

Just-In-Time Data Loading

Server-side Data Virtualization withC1DataSource

Automatic Lookup Columns with C1DataSource

Design-time extended support

Assembly size 1508 K 2108 K Part of

FlexGrid for WinForms

11 Copyright copy GrapeCity Inc All rights reserved

SystemWindowsForms

FlexGrid for WinForms

12 Copyright copy GrapeCity Inc All rights reserved

クイックスタート

This quick start will guide you through the steps of creating a simple grid application using the FlexGrid control Follow thesteps below to get started

FlexGrid for WinForms

13 Copyright copy GrapeCity Inc All rights reserved

This section demonstrates how to create a FlexGrid application in NET 452 by binding it to an externaldatasource You can also create a class to supply data to the grid as shown in the NET 5 tab Similarly you can usebelow steps to bind FlexGrid to a datasource in NET 5 However note that some design-time steps may vary in caseof NET 5

Set Up the Application1 Create a new Windows Forms app(NET Framework)2 Configure your project and set the Framework property3 Drag and drop the FlexGrid control from the Visual Studio toolbox onto the form

Observe An empty grid is added to the form at design time

Bind FlexGrid to a Data SourceThere are two ways to bind data with the FlexGrid control either choose to bind at design time or through code atrun time

Binding at Design Time

1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Click the Choose Data Source drop down button and select Add Project Data Source option to open the

Data Source Configuration Wizard3 On Choose a Data Source Type page select Database and click Next4 On Choose a Database Model page select Dataset and click Next5 On Choose Your Data Connection page click New Connection to open the Add Connection dialog6 Against the DataSource field click Change button to open the Change Data Source dialog7 Select Microsoft Access Database File and click OK to return to the Add Connection dialog8 Against the Database file name field click Browse and navigate to the database file Provide the User name

and Password if required to connect to the database file This example uses C1NWindmdb file located atthe following location by defaultDocumentsComponentOne SamplesCommon

9 Click Test Connection to make sure that you have successfully connected to the database or server and clickOK

NET 452

FlexGrid for WinForms

14 Copyright copy GrapeCity Inc All rights reserved

10 Click OK again to close the Add Connection dialog box11 Click Next 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 Choose the appropriate option as per your requirement12 Save the connection string in the application configuration file by checking the Yes save the connection as

box and entering a name13 Click Next to switch to the Choose Your Database Objects page14 Choose a table say Products from the Tables node and click Finish15 The above steps add a dataset and connection string to your project Also Visual Studio automatically creates

the following code to fill the datasetC

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて

移動または削除できます

thisproductsTableAdapterFill(thisc1NWindDataSetProducts)

VBNET

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移

動または削除できます

MeProductsTableAdapterFill(Mec1NWindDataSetProducts)

Binding at Run Time

To bind the grid through code first we need to create a database connection string Then use an object of dataadapter (in this case OleDbDataAdapter) to create a query to fetch products from the data table and fill it in thedata table which is assigned to the DataSource property of C1FlexGrid class

C

グリッドをデータソースに連結します

string conn = GetConnectionString()OleDbDataAdapter da = new OleDbDataAdapter(select from products conn)DataTable dt = new DataTable(Products)daFill(dt)c1FlexGrid1DataSource = dt

VBNET

グリッドをデータソースに連結します

Dim conn As String = GetConnectionString()Dim da As OleDbDataAdapter = New OleDbDataAdapter(select from products conn)Dim dt As DataTable = New DataTable(Products)daFill(dt)c1FlexGrid1DataSource = dt

Note that the above sample code uses a custom method named GetConnectionString to create a connection stringwith database

C

static string GetConnectionString() string path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) + ComponentOne SamplesCommon string conn = provider=microsoftjetoledb40data source=0c1nwindmdb return stringFormat(conn path)

VBNET

Private Shared Function GetConnectionString() As String Dim path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) amp

FlexGrid for WinForms

15 Copyright copy GrapeCity Inc All rights reserved

ComponentOne SamplesCommon Dim conn = provider=microsoftjetoledb40data source=0c1nwindmdb Return StringFormat(conn path)End Function

Configure the FlexGrid controlThis section walks you through the design-time and run-time steps to configure the grid with some basic settingsThese settings and features are explained in detail in the topics below

Configuring Grid at Design Time

Click smart tag to open the C1FlexGrid Tasks MenuClick the Styles option to open C1FlexGrid Styles EditorSelect Fixed from Built-in Styles pane customize some settings such as Backcolor Font and ForeColor andclick OKTo fit the grid to the form click the Dock in Parent Container optionFor customizing a column click the column (say Unit Price column) to open C1FlexGrid Column TasksMenuClick the ellipsis alongside Format field to open the Format String dialogSelect Currency as Format Type and click OK

Configuring Grid at Run Time

Add following code to configure the grid and its columns at run time

C

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = new Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols[6]Format = c

VBNET

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = New Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols(6)Format = c

FlexGrid for WinForms

16 Copyright copy GrapeCity Inc All rights reserved

This section demonstrates how to create a FlexGrid application in NET 5 by populating its data from a custom classYou can also use an external datasource to supply data to the grid as shown in NET 452 tab However note thatsome design-time steps given in the aforementioned tab may vary in case of NET 5 Similarly you can use belowsteps to bind FlexGrid to an internal datasource in NET 452

Set Up the Application1 Create a new Windows Forms app(NET Framework)2 Configure your project and set the Framework property3 Initialize the FlexGrid control and add it to the form

C

コントロールを初期化します

C1FlexGrid flexGrid = new C1FlexGrid() フォームにコントロールを追加します

thisControlsAdd(flexGrid)

VBNET

コントロールを初期化します

Dim flexGrid As C1FlexGrid = New C1FlexGrid() フォームにコントロールを追加します

MeControlsAdd(flexGrid)

Bind FlexGrid to a Data Source1 Create a custom class Product to be used as a data source

C

カスタムクラスProductを作成します

public class Product static Random _rnd = new Random()

NET 5

FlexGrid for WinForms

17 Copyright copy GrapeCity Inc All rights reserved

static string[] _names = Macko|Surfair|Pocohey|StudebySplit(|) static string[] _lines = Computers|Washers|Stoves|CarsSplit(|) static string[] _colors = Red|Green|Blue|WhiteSplit(|) public Product() Name = _names[_rndNext() _namesLength] Line = _lines[_rndNext() _linesLength] Color = _colors[_rndNext() _colorsLength] Price = 30 + _rndNextDouble() 1000 Cost = 3 + _rndNextDouble() 300 Discontinued = _rndNextDouble() lt 2 Introduced = DateTimeTodayAddDays(_rndNext(-600 0)) public string Name get set public string Color get set public string Line get set public double Price get set public double Cost get set public DateTime Introduced get set public bool Discontinued get set

VBNET

カスタムクラスProductを作成します

Public Class Product Private Shared _rnd As Random = New Random() Private Shared _names As String() = Macko|Surfair|Pocohey|StudebySplit(|c) Private Shared _lines As String() = Computers|Washers|Stoves|CarsSplit(|c) Private Shared _colors As String() = Red|Green|Blue|WhiteSplit(|c)

Public Sub New() Name = _names(_rnd[Next]() Mod _namesLength) Line = _lines(_rnd[Next]() Mod _linesLength) Color = _colors(_rnd[Next]() Mod _colorsLength) Price = 30 + _rndNextDouble() 1000 Cost = 3 + _rndNextDouble() 300 Discontinued = _rndNextDouble() lt 2 Introduced = DateTodayAddDays(_rnd[Next](-600 0)) End Sub

Public Property Name As String Public Property Color As String Public Property Line As String Public Property Price As Double Public Property Cost As Double Public Property Introduced As Date Public Property Discontinued As BooleanEnd Class

2 Initialize a list of type ProductC

Productがクラス型であるProduct型のリストを初期化します

ListltProductgt _products = new ListltProductgt()

FlexGrid for WinForms

18 Copyright copy GrapeCity Inc All rights reserved

VBNET

Productがクラス型であるProduct型のリストを初期化します

Dim _products As List(Of Product) = New List(Of Product)()

3 Initialize a For loop and add products to the list

C

forループを初期化し製品をリストに追加します

for (int i = 0 i lt100 i++) _productsAdd(new Product())

VBNET

forループを初期化し製品をリストに追加します

For i As Integer = 0 To 100 - 1 _productsAdd(New Product())Next

4 Bind FlexGrid to the created data sourceC

FlexGridにデータを連結します flexGridDataSource = _products

VBNET

FlexGridにデータを連結します flexGridDataSource = _products

Configure the FlexGrid controlAdd following code to configure the grid and its columns at run time

C

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = new Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols[6]Format = c

VBNET

c1FlexGrid1StylesFixedForeColor = ColorBluec1FlexGrid1StylesFixedFont = New Font(Microsoft Sans serif 9 FontStyleBold)c1FlexGrid1Dock = DockStyleFillc1FlexGrid1Cols(6)Format = c

FlexGrid for WinForms

19 Copyright copy GrapeCity Inc All rights reserved

設計時サポート

FlexGrid for WinForms comes with various design time options to make your programming tasks a lot easier In addition to smart tag context menu andproperty grid FlexGrid provides tasks menus and editors as well While C1FlexGrid Tasks menu lets you work on the entire grid in design time the ColumnTasks menu provides options to set some common properties for each column of the grid At the same time various editors such as C1FlexGrid ColumnEditor and C1FlexGrid Style Editor provide detailed properties to customize the columns and styles

This section discusses about various design-time options available in the FlexGrid control

Topic Snapshot Content

Tasks Menus Discusses about the C1FlexGrid Tasks menu the Column Tasks menu and their options

C1FlexGrid Tasks MenuC1FlexGrid Column Tasks Menu

Editors Discusses about the various editors and how to access them

C1FlexGrid Column EditorC1FlexGrid Style EditorCaption Style EditorColumn Style Editor

タスクメニュー

C1FlexGrid Tasks MenuC1FlexGrid Tasks menu provides you an easy access to the commonly used properties of FlexGrid It also providesoptions to open various editors such as C1FlexGrid Column Editor C1FlexGrid Style Editor

To access the C1FlexGrid Tasks menu click the smart tag ( ) in the upper right corner of the grid Following tableexplains various options available through the C1FlexGrid Tasks menu

Option Description

ChooseDataSource

The dropdown opens the list of available data sourcesand gives you Add Project Data Source option to openData Source Configuration Wizard

For more information on how to add a new data sourceto the project see Bound Mode

EnableAddingRows

The checkbox toggles the AllowAddNew propertywhich allows users to add new row to the grid at runtime When checked ON it displays a template row withstar at the bottom of the grid to enter the new record

EnableDeletingRows

The checkbox toggles the AllowDelete property whichallows users to delete the selected rows by pressing theDelete key

EnableEditing

The checkbox toggles the AllowEditing property whichallows users to edit the grid

Enable Column Reordering The checkbox sets the AllowDragging property toColumns which allows users to re-order the columns by draggingthe column headers

Enable Column Filtering The checkbox toggles the FlexGridAllowFiltering property to

FlexGrid for WinForms

20 Copyright copy GrapeCity Inc All rights reserved

enable or disable the filtering on grid columns

VisualStyle The dropdown lets you choose the built-in visual styles availablein the grid By default the value is set to Custom

Designer The option opens C1FlexGrid Column Editor which allows you toset the properties of each column of the grid

Styles The option opens C1FlexGrid Style Editor which allows youto customize the various pre-defined styles or create the newstyles at design time

Display Hidden Columns The checkbox lets you display or hide grid columns in the designview Note that this option is NOT associated with the run-timevisibility of columns Hence even if this checkbox is checked ONcolumns with Visible property set to False still remain hiddenwhen the application is run

Column Tasks The option switches the task menu to C1FlexGrid Column Tasksmenu which provides options to set the properties for theselected column

About C1FlexGrid The option displays a dialog box displaying the information suchas version of the FlexGrid control

Dock in Parent Container This option sets the Dock property of the grid to Fill which resizesthe grid to occupy the whole form space Clicking the option alsoswitches the text and provides option to Undock in ParentContainer which restores the grid to its original size

C1FlexGrid Column Tasks MenuC1FlexGrid Column Tasks menu provides you an easy access to the commonly used properties of grid columns Italso provides options to open editors named Caption Style and Column Style

To access the C1FlexGrid Column Tasks menu double-click header of the column to be configured at design-timeAnother way to open C1FlexGrid Column Tasks menu is to click on the smart tag ( ) in the upper right corner of thegrid and then navigate to the Column Tasks option Following table explains various options available through theC1FlexGrid Column Tasks menu

FlexGrid for WinForms

21 Copyright copy GrapeCity Inc All rights reserved

Option Description

ColumnCaption

The field allows you to specify the value of Captionproperty which sets text in header cell of the column

DataField

The dropdown opens a list of available fields in the datasource to choose from and sets value of Name property ofthe column

DataType

The dropdown opens a list of available data types and letsyou set the data type of the selected column This fieldcorresponds to the DataType property of the column

EditMask

The field lets you specify value of EditMask property whichsets mask for the selected column The ellipsis button onthe right side of the field opens the Input Mask dialog boxwhere you can select from the list of pre-defined masks

FormatString

The field lets you specify the value of Format propertywhich sets format string to display data value from source

ComboList

The field lets you specify the list of multiple values fromwhich user can choose The ellipsis button on the right sideof the field lets you open the Combo List dialog box whereyou can specify the value options

Allow Sorting The checkbox toggles the AllowSorting property to enable ordisable sorting in the column By default sorting is enabled for allcolumns

Allow Editing The checkbox toggles the AllowEditing property to make thecolumn read-only or editable By default editing is enabled for allcolumns

Allow Resizing The checkbox toggles the AllowResizing property which allows usersto adjust the size of column at run time By default resizing isenabled for all columns

Allow Dragging The checkbox toggles the AllowDragging property to enable ordisable re-ordering of the column at run time By default dragging isenabled for all columns

Allow Merging The checkbox toggles the AllowMerging property to enable ordisable merging two adjacent column cells having same values Bydefault merging is disabled for all columns

Allow Filtering The dropdown lets you specify the value of ColumnAllowFilteringproperty and choose the type of filter for each column The availableoptions are Default ByValue ByCondition Custom or None

Visible The checkbox lets you set the visibility of the column in the grid atrun time by toggling value of its Visible property

FlexGrid for WinForms

22 Copyright copy GrapeCity Inc All rights reserved

Caption Style The option opens the Caption Style editor which gives you options tostyle the text alignment background and border for the header cellof column

Column Style The option opens the Column Style editor which gives you options tostyle the text alignment background and border for the column text

C1FlexGrid Tasks The option switches the task menu to C1FlexGrid Tasks menu whichprovides options to set the properties for the entire grid

Dock in Parent Container The option sets the Dock property of the grid to Fill which resizes thegrid to occupy the whole form Clicking the option also switches thetext and provides option to Undock in Parent Container whichrestores the grid to its original size by setting the Dock property toNone

エディタ

Apart from the tasks menu FlexGrid also provides various editors that help you set a number of properties related togrid its columns and their styles

C1FlexGrid Column EditorFlexGrid provides the C1FlexGrid Column Editor making it easy to work with columns at design-time instead ofwriting code The editor lets you set various properties related to columns such as Caption DataTypeAllowFiltering and AllowMerging through its property pane on left hand side Toolbar on the top of this editorgives you options such as reloading data from the data source adding removing and resizing columns You can evenstyle the column text using the options given in this toolbar For further customization of column text you can usethe Column Style editor to access more specific properties

FlexGrid for WinForms

23 Copyright copy GrapeCity Inc All rights reserved

There are three ways in which you can access the C1FlexGrid Column Editor at design time

Smart Tag Click the smart tag ( ) in the upper right corner of the grid and select Designer from theC1FlexGrid Tasks menuProperty Window Select the grid go to the Properties window and click the ellipsis button (hellip) next to theCols propertyContext Menu Right-click the grid and select Designer from the context menu

C1FlexGrid Style EditorFlexGrid provides the C1FlexGrid Style editor which lets you style the grid at design time by customizing the built-instyles and creating the new ones The editor offers a list of styles for specific types of cell on left hand side and aproperty window on right hand side to customize these styles The list of styles is divided into two sections thedefault Built-in Styles and Custom Styles Towards the bottom there are Add and Remove buttons to add anddelete the custom styles and a Clear button to revert the editor to default settings The AutoFormat button in theend opens a secondary dialog C1FlexGrid Auto Format which lists the pre-defined set of styles and also shows apreview in the Preview pane

FlexGrid for WinForms

24 Copyright copy GrapeCity Inc All rights reserved

There are three ways in which you can access the C1FlexGrid Style Editor at design-time

Smart Tag Click the smart tag ( ) in the upper right corner of the grid and select Styles from theC1FlexGrid Tasks menuProperty Window Select the grid go to the Properties window and click the ellipsis button (hellip) next to theStyles propertyContext Menu Right-click the grid and select Styles from the context menu

Caption Style EditorFlexGrid provides the Caption Style editor which allows you to set styling related properties of the column header celland its text The editor comprises of four tabs Text Alignment Border and Background for customizing variousaspects of the header cells

To access the Caption Style editor click smart tag ( ) click the C1FlexGrid Column Tasks option on the task menu toopen column tasks and then go to Caption Style option

FlexGrid for WinForms

25 Copyright copy GrapeCity Inc All rights reserved

Column Style EditorSimilar to Caption Style editor FlexGrid provides another editor the Column Style editor for styling the column textThe editor has got the same options as that of Caption Style editor The only difference is that Caption Style editorcustomizes the column header text while this editor works on the general text in the column cells

To access the Column Style editor click smart tag ( ) click the C1FlexGrid Column Tasks option on the task menu toopen column tasks and then go to Column Style option

FlexGrid for WinForms

26 Copyright copy GrapeCity Inc All rights reserved

データ

This section discusses about various ways to populate data in the FlexGrid control

Topic Snapshot Content

Unbound Mode Discusses how to populate data in the unbound grid

Bound Mode Discusses ways of populating data in the grid through data binding and various operations on bound grid

Binding at design timeBinding at run time using DataSource propertyBinding at run time using SetDataBinding methodOperations in Bound Mode

非連結モード

As the name suggests in unbound mode grid is not bound to any data source and data is stored in the control itselfIn this case you need to provide data by adding rows and columns either at design time or programmatically throughrow and column collections You can also create an empty grid to let user enter the data

An unbound grid is not a very common scenario as grid does not store the data and hence user needs to manage itmanually However unbound grids suits better to some business scenarios like creation and maintenance of recordsFor instance you can use the grid in unbound mode for recording the date-wise sales data or to maintain the dailyinventory changes Below example demonstrates a grid with data populated through code

In C1FlexGrid you can add empty rows or columns by setting the Count property of row or column objects Also youcan use the Add method of these collections to add the empty rows and columns to a grid To set data in the cellsyou can either use the familiar index notation(Item property) or the SetData method For more information on settingdata in the cells see Storing and Retrieving Data

Use the code below to populate data in unbound FlexGrid for WinForms

連結されていない列を追加しますColumn col = _flexColsAdd()colName = colCaption = Unbound_flex[1 Unbound] = 123

C

連結されていない列を追加しますDim col As Column = C1FlexGrid1ColsAdd()colName = UnboundcolCaption = Unbound

VBNET

FlexGrid for WinForms

27 Copyright copy GrapeCity Inc All rights reserved

連結モード

Bound mode as the name suggests refers to a state where grid fetches its data from an underlying data source Databinding also allows multiple data consumers to be connected to a data provider in the synchronized manner

FlexGrid supports data binding to most of the commonly used data sources such as ObservableCollection IListltTgtListltTgt Array BindingSource ADONET objects such as DataSet DataTable etc

There are three ways of binding FlexGrid to a data source

Binding at design timeBinding at run time using DataSource propertyBinding at run time using SetDataBinding method

Binding at Design Time1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Click the Choose Data Source drop down button and select Add Project Data Source option to open the

Data Source Configuration Wizard3 On Choose a Data Source Type page select Database and click Next4 On Choose a Database Model page select Dataset and click Next5 On Choose Your Data Connection page click New Connection to open the Add Connection dialog6 Against the DataSource field click Change button to open the Change Data Source dialog7 Select Microsoft Access Database File and click OK to return to the Add Connection dialog8 Against the Database file name field click Browse and navigate to the database file Provide the User name

and Password if required to connect to the database file This example uses C1NWindmdb file located at thefollowing location by defaultDocumentsComponentOne SamplesCommon

FlexGrid for WinForms

28 Copyright copy GrapeCity Inc All rights reserved

9 Click Test Connection to make sure that you have successfully connected to the database or server and clickOK

10 Click OK again to close the Add Connection dialog box11 Click Next 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 Choose the appropriate option as per your requirement12 Save the connection string in the application configuration file by checking the Yes save the connection as

box and entering a name13 Click Next to switch to the Choose Your Database Objects page14 Choose a table say Products from the Tables node and click Finish15 The above steps add a dataset and connection string to your project Also Visual Studio automatically creates

the following code to fill the dataset

Binding at Run Time Using DataSource PropertyFlexGrid provides the DataSource property to bind the FlexGrid control to a data source at run time You need toassign a data source object to the DataSource property of FlexGrid If the data source object contains more than onetable you can set the DataMember property to table name to specify the target table

Following code uses DataSource property to bind data to the WinForms FlexGrid

Note that the above sample code uses a custom method named GetData to supply data You can set up the datasource as per your requirements Following code shows an example of creating data for WinForms FlexGrid

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移動または削除できます thisproductsTableAdapterFill(thisc1NWindDataSetProducts)

C

次のサンプルコードはデータを「c1NWindDataSetProducts」テーブルにロードします 必要に応じて移動または削除できます MeProductsTableAdapterFill(Mec1NWindDataSetProducts)

VBNET

c1FlexGrid1BeginUpdate()C1DataCollectionltCustomergt c1DataCollection = new C1DataCollectionltCustomergt(GetData())c1FlexGrid1DataSource = new C1DataCollectionBindingList(c1DataCollection)c1FlexGrid1EndUpdate()

C

c1FlexGrid1BeginUpdate()Dim c1CollectionView As C1DataCollectionC1DataCollection(Of Customer) = New C1DataCollectionC1DataCollection(Of Customer)(GetData())c1FlexGrid1DataSource = New C1DataCollectionBindingListC1DataCollectionBindingList(c1CollectionView)c1FlexGrid1EndUpdate()

VBNET

ObservableCollectionltCustomergt GetData() var data = new ObservableCollectionltCustomergt() for (int i = 0 i lt 25 i++)

C

FlexGrid for WinForms

29 Copyright copy GrapeCity Inc All rights reserved

Binding at Run Time Using SetDataBinding MethodFlexGrid also provides the SetDataBinding method using which you can set DataSource and DataMember propertiesboth using a single call The following code demonstrates an example of rendering a parent table and its child tablesin different grids with the help of the SetDataBinding method

Below code demonstrates how to bind data to WinForms FlexGrid using SetDataBinding method

dataAdd(new Customer()) return data

Private Function GetData() As ObservableCollection(Of Customer) Dim data = New ObservableCollection(Of Customer)()

For i = 0 To 25 - 1 dataAdd(New Customer()) Next

Return dataEnd Function

VBNET

グリッドにデータセットを連結します_flexCustomersBeginUpdate()_flexCustomersSetDataBinding(ds Customers)_flexCustomersEndUpdate()

_flexOrdersBeginUpdate()_flexOrdersSetDataBinding(ds CustomersCustomerOrders)_flexOrdersEndUpdate()

_flexOrderDetailsBeginUpdate()_flexOrderDetailsSetDataBinding(ds CustomersCustomerOrdersOrderDetails)_flexOrderDetailsEndUpdate()

C

グリッドにデータセットを連結します_flexCustomersBeginUpdate()_flexCustomersSetDataBinding(ds Customers)_flexCustomersEndUpdate() _flexOrdersBeginUpdate()_flexOrdersSetDataBinding(ds CustomersCustomerOrders)_flexOrdersEndUpdate() _flexOrderDetailsBeginUpdate()_flexOrderDetailsSetDataBinding(ds CustomersCustomerOrdersOrderDetails)_flexOrderDetailsEndUpdate()

VBNET

連結モードでの操作

Adding Unbound Column in Bound ModeIn the bound mode grid fetches the data from data source and display it as records and bound columns To add a column to

FlexGrid for WinForms

30 Copyright copy GrapeCity Inc All rights reserved

display data that does not exist in the data source you need to add unbound columns at design time or through code

Adding unbound column at design time

1 In the design view select the FlexGrid control and click smart tag to open the C1FlexGrid Tasks menu2 Bind the grid control with a data source For detailed steps about how to bind FlexGrid to a data source see Bound

Mode3 Click the Designer option to open the C1FlexGrid Column Editor4 In the right hand side pane select an existing column from the grid preview5 Click Insert Column options in the toolbar to add a column before or after the selection

Adding unbound column through code

FlexGrid provides Add Insert and InsertRange method of the ColumnCollection class to add an unbound column to the gridWhile Add method adds a column at the end the Insert method lets you specify the position where you want to add a newcolumn Similarly you can add multiple columns at a specified position by using the InsertRange method

Use the code below to add unbound column in a bound WinForms FlexGrid

連結されていない列を追加しますColumn col = _flexColsAdd()colName = colCaption = Unbound_flex[1 Unbound] = 123

C

連結されていない列を追加しますDim col As Column = C1FlexGrid1ColsAdd()colName = UnboundcolCaption = Unbound

VBNET

FlexGrid for WinForms

31 Copyright copy GrapeCity Inc All rights reserved

Set Values in Unbound ColumnTo define values in the unbound column of bound grid you need to usethe SetUnboundValue and GetUnboundValue events of the C1FlexGrid class First create a hash table to store the enteredvalues then use the SetUnboundValue event to set unbound value in the hash table using a unique key to identify therecord and use GetUnboundValue event to get the value stored in the hash table using its unique key and set unboundvalue to be displayed in the cell

Following code shows how to set values in an unbound column added to a bound WinForms FlexGrid

Displaying Data in Fixed ColumnTo set values in the fixed columns you need to set DrawMode property of the C1FlexGrid class to OwnerDraw in the formload event and then create the OwnerDrawCell event to set values in the fixed column cells In this example we are settingrow numbers in the fixed column of a bound WinForms FlexGrid

get value from hashtable using ProductID as keyvoid _flex_GetUnboundValue(object sender C1WinC1FlexGridUnboundValueEventArgs e) DataRowView drv = (DataRowView)_flexRows[eRow]DataSource eValue = _hash[drv[ProductID]]

store value in hashtable using ProductID as keyvoid _flex_SetUnboundValue(object sender C1WinC1FlexGridUnboundValueEventArgs e) DataRowView drv = (DataRowView)_flexRows[eRow]DataSource _hash[drv[ProductID]] = eValue

C

Private Sub C1FlexGrid1_GetUnboundValue(sender As Object e As C1WinC1FlexGridUnboundValueEventArgs) Handles C1FlexGrid1GetUnboundValue Dim drv As DataRowView = DirectCast(C1FlexGrid1Rows(eRow)DataSource DataRowView) eValue = _hash(drv(ProductID))End Sub

Private Sub C1FlexGrid1_SetUnboundValue(sender As Object e As C1WinC1FlexGridUnboundValueEventArgs) Handles C1FlexGrid1SetUnboundValue Dim drv As DataRowView = DirectCast(C1FlexGrid1Rows(eRow)DataSource DataRowView) _hash(drv(ProductID)) = eValueEnd Sub

VBNET

FlexGrid for WinForms

32 Copyright copy GrapeCity Inc All rights reserved

Auto-adjust Column WidthFlexGrid provides AutoResize property of the C1FlexGrid class to adjust the width of columns automatically according tothe text length You need to set the property to true before binding it to the data source to load the grid with appropriatecolumn width You can also call AutoSizeCol method to adjust the width of the specified column

Use the code below auto-adjust the column width according to the text in WinForms FlexGrid

Display Bitmap Image in FieldIn most of the scenarios grid directly fetches the images from the data source However if the grid is bound to a databasewhich stores images as OLE objects such as Microsoft Access a little bit of extra processing is required to fetch bitmapimages In such case you need to convert the image data stored as byte array to a memory stream and then usethe OwnerDrawCell event to load the image In the form load event you need to set the DrawMode property toOwnerDraw Also adjust the height of row to display the image properly

Following code demonstrates how to display bitmap image in fields of WinForms FlexGrid

private void C1FlexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if ((eRow gt= thisc1FlexGrid1RowsFixed) amp (eCol == (thisc1FlexGrid1ColsFixed - 1))) eText = eRowToString() または任意のテキスト

C

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If eRow gt= Mec1FlexGrid1RowsFixed And eCol Is Mec1FlexGrid1ColsFixed - 1 Then eText = eRowToString() または任意のテキスト End IfEnd Sub

VBNET

すべての列の幅を自動的に調整します c1FlexGrid1AutoResize = true

4列目の幅を自動調整します c1FlexGrid1AutoSizeColumns(3)

C

すべての列の幅を自動的に調整します c1FlexGrid1AutoResize = True

4列目の幅を自動調整します c1FlexGrid1AutoSizeColumns(3)

VBNET

private void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) if(eMeasuring ampamp eRowgt=c1FlexGrid1RowsFixed ampamp eCol gt=

C

FlexGrid for WinForms

33 Copyright copy GrapeCity Inc All rights reserved

Note that the above sample code uses a custom method LoadImage method to convert the images from byte array to amemory stream

c1FlexGrid1ColsFixed) 「Photo」はblob(byte [])に保存された画像です if (c1FlexGrid1Cols[eCol]Name == Picture) mdbからロードしてみてください eImage = LoadImage(c1FlexGrid1[eRow eCol] as byte[])

画像が表示された場合はテキストを入力しないでください if (eImage = null) eText = null

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) If Not eMeasuring AndAlso eRow gt= c1FlexGrid1RowsFixed AndAlso eCol gt= c1FlexGrid1ColsFixed Then

「Photo」はblob(byte [])に保存された画像です If c1FlexGrid1Cols(eCol)Name Is Picture Then mdbからロードしてみてください eImage = LoadImage(TryCast(c1FlexGrid1(eRow eCol) Byte()))

画像が表示された場合はテキストを入力しないでください If eImage IsNot Nothing Then eText = Nothing End If End IfEnd Sub

VBNET

Image LoadImage(byte[] picData) static Image LoadImage(byte[] picData) これが埋め込みオブジェクトであることを確認してください const int bmData = 78 if (picData == null || picDataLength lt bmData + 2) return null if (picData[0] = 0x15 || picData[1] = 0x1c) return null

現在点ではビットマップのみを処理します if (picData[bmData] = B || picData[bmData + 1] = M) return null

画像をロードします Image img = null try MemoryStream ms = new MemoryStream(picData bmData picDataLength - bmData) img = ImageFromStream(ms) catch

画像を返します return img

C

Private Function LoadImageMethod(ByVal picData As Byte()) As Image

VBNET

FlexGrid for WinForms

34 Copyright copy GrapeCity Inc All rights reserved

Private Shared Function LoadImage(ByVal picData As Byte()) As Image これが埋め込みオブジェクトであることを確認してください Const bmData As Integer = 78 If picData Is Nothing OrElse picDataLength lt bmData + 2 Then Return Nothing If picData(0) ltgt ampH15 OrElse picData(1) ltgt ampH1c Then Return Nothing

現在点ではビットマップのみを処理します If picData(bmData) ltgt Bc OrElse picData(bmData + 1) ltgt Mc Then Return Nothing

画像をロードします Dim img As Image = Nothing

Try Dim ms As MemoryStream = New MemoryStream(picData bmData picDataLength - bmData) img = ImageFromStream(ms) Catch End Try

画像を返します Return imgEnd Function

FlexGrid for WinForms

35 Copyright copy GrapeCity Inc All rights reserved

A grid control is a collection of rows and columns Columns generally contain a particular type of information through out while rows are used to recorddifferent types of information about a particular item

In FlexGrid the collection of columns is represented by the ColumnCollection class which can be accessed through Cols property of the C1FlexGrid class Thissection discusses the various operations that can be performed on columns

Topic Snapshot Content

BasicOperations

Discusses about how to perform basic column operations

Set Column CountAdd ColumnDelete ColumnInsert ColumnSet Data TypeSet Fixed ColumnSet Frozen Column

UserInteraction

Discusses about operations that can be performed by the end user at run time

Allow EditingAllow DraggingAllow FreezingAllow SortingAllow FilteringAllow Resizing

Editors Discusses about various built-in editors of FlexGrid and operations related to them Also discusses how to use customeditors in the FlexGrid

CheckBoxNumericDateComboBoxMaskMapped ListCell Button

Validation Discusses how to apply validation and show error information on FlexGrid cells

Sparkline Discusses about how to display Sparkline charts in FlexGrid cells

Header andFooter

Discusses about how to set column header and footer

Set Header TextMerge column headerWrap column header textStyle Column HeaderSet Column Footer

Sizing Discusses about various aspects of column sizing

Set Column WidthAuto-adjust Column WidthSet MinMax Column WidthStar Sizing

基本操作

This topic discusses various basic operations which can be performed on a column

FlexGrid for WinForms

36 Copyright copy GrapeCity Inc All rights reserved

Set Column CountWhen grid is bound to a data source the number of columns is determined by the number of fields available in thedata source However in the case of unbound mode you can set any arbitrary value in the Count property ofthe ColumnCollection class to set the number of columns to be displayed in the grid

Use the code below to set the number of columns to be added to WinForms FlexGrid in unbound mode

Add ColumnFlexGrid provides two ways to add a new column using the ColumnCollection class You can either use Add methodor increment the value of Count property provided by the class to add new columns Also note that if a new columnis added to a bound grid using these methods it is added as an unbound column only

Following are the two approaches to add column to a WinForms FlexGrid

Delete ColumnTo delete a particular column from the grid you can use Remove method of the ColumnCollection class and specifythe column you want to delete as its parameter In the unbound grid you can also reduce the number of columns bychanging the value of Count property This removes columns from the end of the column collection TheColumnCollection class also provides RemoveRange method which allows you to remove a range of columns

列数を設定します c1FlexGrid1ColsCount = 4

C

列数を設定しますc1FlexGrid1ColsCount = 4

VBNET

方法1 列コレクションのAddメソッドを使用します C1WinC1FlexGridColumn c c = c1FlexGrid1ColsAdd() cCaption = New Column

方法2 列コレクションのCountプロパティを変更します c1FlexGrid1ColsCount += 1 c1FlexGrid1Cols[c1FlexGrid1ColsCount - 1]Caption = New Column

C

方法1 列コレクションのAddメソッドを使用します Dim c As C1WinC1FlexGridColumn c = c1FlexGrid1ColsAdd() cCaption = New Column

方法2 列コレクションのCountプロパティを変更します c1FlexGrid1ColsCount += 1 c1FlexGrid1Cols(c1FlexGrid1ColsCount - 1)Caption = New Column

VBNET

FlexGrid for WinForms

37 Copyright copy GrapeCity Inc All rights reserved

Below code snippet shows all the three approaches to delete column from the WinForms FlexGrid

Insert ColumnTo insert a column in FlexGrid at a specific location you can use Insert method of the ColumnCollection class whichlets you specify the position where columns are to be inserted You can also insert multiple columns in the grid byusing the InsertRange method These methods add the unbound columns only even if the grid is a bound grid

Use any of the following approaches to insert a column in the WinForms FlexGrid at the specified location

方法1 列コレクションのRemoveメソッドを使用して2番目の列を削除します c1FlexGrid1ColsRemove(2)

方法2 Countプロパティを変更して最後の列を削除します c1FlexGrid1ColsCount -= 1

方法3 RemoveRangeメソッドを使用して2番目から始まる4つの列を削除します c1FlexGrid1ColsRemoveRange(2 4)

C

方法1 列コレクションのRemoveメソッドを使用して2番目の列を削除します c1FlexGrid1ColsRemove(2)

方法2 Countプロパティを変更して最後の列を削除します c1FlexGrid1ColsCount -= 1

方法3 RemoveRangeメソッドを使用して2番目から始まる4つの列を削除します c1FlexGrid1ColsRemoveRange(2 4)

VBNET

C1WinC1FlexGridColumn c

方法1 Insertメソッドを使用して2番目の位置に列を挿入します c = c1FlexGrid1ColsInsert(2) cCaption = Inserted Column

方法2 InsertRangeメソッドを使用して2番目の位置に3つの列を挿入します c1FlexGrid1ColsInsertRange(2 3)

C

Dim c As C1WinC1FlexGridColumn 方法1 Insertメソッドを使用して2番目の位置に列を挿入します c = c1FlexGrid1ColsInsert(2) cCaption = Inserted Column 方法2 InsertRangeメソッドを使用して2番目の位置に3つの列を挿入します c1FlexGrid1ColsInsertRange(2 3)

VBNET

FlexGrid for WinForms

38 Copyright copy GrapeCity Inc All rights reserved

Set Data TypeIn case of a bound FlexGrid data type of each bound column is automatically picked from the data source dependingon the data However in the case of unbound mode you can set the data type of columns by specifyingthe DataType property of Column class You can also set the Data Type property at design time by using theColumn Tasks menu For more information on tasks menus see Tasks Menus Note that when a particular data type isset to a FlexGrid column its cells accept the user input of keys accepted by the data type only For instance you cannot input alphabets in a Numeric type cell

Set the data type of an unbound column in WinForms FlexGrid as shown in the code below

Set Fixed ColumnFixed columns refer to the columns with non-editable cells which are always visible in the left hand side of the grideven if user scrolls the grid horizontally In FlexGrid fixed columns can be set using Fixed property ofthe ColumnCollection class This property accepts an integer value that specifies the number of columns to be fixed

Use the code below to set one column as fixed in the WinForms FlexGrid

Set Frozen ColumnFrozen columns similar to fixed columns are non-scrollable but can be edited by the user In FlexGrid frozen columnscan be set by using Frozen property provided by the ColumnCollection class

To set frozen columns in the WinForms FlexGrid use the code below

最初の列のデータ型を設定します c1FlexGrid1Cols[1]DataType = typeof(int)

C

最初の列のデータ型を設定しますc1FlexGrid1Cols(1)DataType = GetType(Integer)

VBNET

1つの列を固定列として設定しますc1FlexGrid1ColsFixed = 1

C

1つの列を固定列として設定しますc1FlexGrid1ColsFixed = 1

VBNET

最初の4列を静止として設定しますc1FlexGrid1ColsFrozen = 4

C

最初の4列を静止として設定しますc1FlexGrid1ColsFrozen = 4

VBNET

FlexGrid for WinForms

39 Copyright copy GrapeCity Inc All rights reserved

ユーザー操作

This topic discusses how you can let end users interact with the FlexGrid columns

Allow EditingBy default FlexGrid allows to edit all columns of the grid However you can choose to disable editing of a particularcolumn by setting AllowEditing property of the Column object to false You can also disable editing of the whole gridby setting the C1FlexGridAllowEditing property to false For more information on editing see Edit

Following code shows how to disable editing of WinForms FlexGrid while keeping only one column editable

Allow DraggingFlexGrid by default allows user to reorder columns by dragging a column header and dropping it to the targetposition However you can change this behavior by using the FlexGridAllowDragging propertyand ColumnAllowDragging property To disable dragging of a particular column you can set theColumnAllowDragging property of that column to false On the other hand setting the FlexGridAllowDraggingproperty to either Rows or None disables the column reordering at grid level This property accepts the valuesfrom AllowDraggingEnum You can also disable column reordering at design time by checking off the Enable ColumnReordering checkbox in the C1FlexGrid Tasks menu For more information on tasks menus see Tasks Menus

グリッド全体で編集を無効にしますc1FlexGrid1AllowEditing = false

3列目でのみ編集を有効にしますc1FlexGrid1Cols[3]AllowEditing = true

C

グリッド全体で編集を無効にしますc1FlexGrid1AllowEditing = False

3列目でのみ編集を有効にしますc1FlexGrid1Cols(3)AllowEditing = True

VBNET

FlexGrid for WinForms

40 Copyright copy GrapeCity Inc All rights reserved

Below code demonstrates how to enable dragging of columns in WinForms FlexGrid

Allow FreezingTo allow end user to freeze the columns at runtime you can use the AllowFreezing property of the C1FlexGrid classwhich accepts values from AllowFreezingEnum When this property is set to Columns or Both a lock sign appearswhen mouse is hovered over the edge of header column User can click and drag the lock sign to freeze the columns

Following code shows how to allow users to freeze the columns in WinForms FlexGrid

Allow PinningFlexGrid lets you allow your users to pin a particular column or column range at run time by using the AllowPinningproperty of the C1FlexGrid class Setting the property adds a Pin button( ) in the column header which allows usersto pin columns at run-time so they remain in view as the user scrolls the grid horizontally The property accepts itsvalues from AllowPinning enumeration which lets you set pinning for a single column or a column range Whenproperty is set to ColumnRange user can pin or unpin all the columns starting from left till the clicked column in onego

グリッド全体ですべての列のドラッグを許可します c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumColumns

特定の列のドラッグを無効にしますc1FlexGrid1Cols[3]AllowDragging = false

C

グリッド全体ですべての列のドラッグを許可します c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumColumns

特定の列のドラッグを無効にします c1FlexGrid1Cols(3)AllowDragging = False

VBNET

実行時に列のフリーズを許可します c1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumColumns

C

実行時に列のフリーズを許可しますc1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumColumns

VBNET

FlexGrid for WinForms

41 Copyright copy GrapeCity Inc All rights reserved

Use the code below to let user pin multiple columns in the WinForms FlexGrid

Allow SortingIn FlexGrid column sorting is enabled for the whole grid by default and value of AllowSorting property of theC1FlexGrid class is set to Auto In this mode user can sort a single column by clicking the column header andmultiple columns by holding the CTRL key while clicking the column headers On sorting multiple columns the gridshows sort index in the column header next to the sort direction glyph You can also choose to prevent sorting orsimply change the way the columns are sorted through AllowSortingEnum enumeration The AllowSortingEnumenumeration allows you to choose whether to auto sort columns sort single column multiple columns or columnrange or just prevent sorting

You can enable multi-column sorting in the WinForms FlexGrid using the code below When AllowSorting propertyis set to MultiColumn user may sort multiple columns by simply clicking on their headers one after the other

ユーザーが列範囲を固定できるようにしますc1FlexGrid1AllowPinning = C1WinC1FlexGridAllowPinningColumnRange

C

ユーザーが列範囲を固定できるようにしますc1FlexGrid1AllowPinning = C1WinC1FlexGridAllowPinningColumnRange

VBNET

グリッドで複数列の並べ替えを有効にしますc1FlexGrid1AllowSorting = C1WinC1FlexGridAllowSortingEnumMultiColumn

1列のみの並べ替えを無効にしますc1FlexGrid1Cols[1]AllowSorting = false

C

グリッドで複数列の並べ替えを有効にしますc1FlexGrid1AllowSorting = C1WinC1FlexGridAllowSortingEnumMultiColumn

1列のみの並べ替えを無効にしますc1FlexGrid1Cols(1)AllowSorting = False

VBNET

FlexGrid for WinForms

42 Copyright copy GrapeCity Inc All rights reserved

To disable sorting on a particular column you need to set the ColumnAllowSorting property of that column to falseFor more information on sorting see Sort

Allow FilteringFlexGrid doesnt allow filtering at runtime by default However you can enable it by settingthe C1FlexGridAllowFiltering property to true To define the type of filter you want to apply on a particularcolumn you can use the ColumnAllowFiltering property which accepts following values from the AllowFilteringenumeration

AllowFiltering Values Description

Default The grid automatically creates a filter of type ColumnFilter This filteris the combination of a value filter and a condition filter

ByValue The grid automatically creates a filter of type ValueFilter This filteroffers a checkbox list of values to choose from Values that are notchecked in the list are excluded from the filter output

ByCondition The grid automatically creates a filter of type ConditionFilter Thisfilter provides several options such as Equals is Greater thanContains Begins with etc to create conditions You can also combinetwo conditions by using the And and Or operators available in thefilter

Custom The grid does not create a filter automatically and allows you to defineyour own filter and then explicitly assign it to Filter property of theColumn class

None Filtering is disabled for the column

For more information on filtering see Filter

Following code shows how to enable filtering in the WinForms FlexGrid and how to apply filters

Allow ResizingBy default FlexGrid allows resizing of all columns of the grid To change this behavior you can use AllowResizingproperty of the C1FlexGrid class This property accepts values from the AllowResizingEnum enumeration which letsyou resize columns rows both or none The enumeration also gives you options to uniformly resize the rows columnsor both that is if you resize one of the columns or rows the grid automatically resizes rest of the columns or rows as

グリッドレベルでのフィルタリングを許可します c1FlexGrid1AllowFiltering = true

最初の列に条件フィルターを適用します c1FlexGrid1Cols[1]AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

C

グリッドレベルでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = True

最初の列に条件フィルターを適用しますc1FlexGrid1Cols(1)AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

VBNET

FlexGrid for WinForms

43 Copyright copy GrapeCity Inc All rights reserved

well FlexGrid also provides ColumnAllowResizing property which is a Boolean type property and lets you enable ordisable resizing of a particular row or column

Below code shows how to allow users to resize columns of WinForms FlexGrid

Enable Context MenuFlexGrid provides support for column context menu at run-time to facilitate quick actions related to columnoperations To enable the column context menu on right-click you need to set ColumnContextMenuEnabled propertyprovided by the C1FlexGrid class to true By default this property is set to false

The column context menu provides following options

Option Description

Sort Ascending Sorts the column in ascending order

Sort Descending Sorts the column in descending order

Group by This Groups the grid data based on column under mouse pointer

列と行のサイズを均一に変更できますc1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumBoth

最初の列のサイズ変更のみを無効にしますc1FlexGrid1Cols[1]AllowResizing = false

C

列と行のサイズを均一に変更できますc1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumBoth

最初の列のサイズ変更のみを無効にしますc1FlexGrid1Cols(1)AllowResizing = False

VBNET

FlexGrid for WinForms

44 Copyright copy GrapeCity Inc All rights reserved

Column

Ungroup Removes grouping from the grid data The option displays only when grid is in groupedstate

Hide this Column Hides the column under mouse pointer

Auto size Resizes the column according to the length of longest value

Auto size (allcolumns)

Resizes all columns according to the length of longest value in each of them

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = true

C

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = True

VBNET

Option Description

エディタ

This topic discusses various built-in editors of FlexGrid and operations related to them The topic also takes you through thesteps to apply custom editors in the FlexGrid columns

Built-in EditorsFlexGrid provides several built-in editors to enable efficient in-cell editing The grid uses TextBox control as its default editorHowever other built-in editors such as numeric date checkbox and combo box are also supported These editors areautomatically assigned generally based on the value of some specific properties such as DataType property of the column Thetable below summarizes the built-in editors provided by FlexGrid their brief description and the example codes demonstratingthem For more information about built-in editors and their customization click the corresponding hyperlink

Built-inEditor

Snapshot Description Sample Code

Checkbox Gets enabledautomatically whenDataType propertyof the Columnobject is set to

c1FlexGrid1Cols[colIndex]DataType =

typeof(Boolean)

FlexGrid for WinForms

45 Copyright copy GrapeCity Inc All rights reserved

Boolean

Numeric Gets enabledautomatically whenDataType propertyis set to a numericdata type such asInt or Decimal

c1FlexGrid1Cols[colIndex]DataType =

typeof(Int32)

Date Gets enabledautomatically if theDataType propertyof column is set toDate or DateTime

c1FlexGrid1Cols[colIndex]DataType =

typeof(DateTime)

ComboBox Gets enabled bysetting multiplevalues separated bypipe inthe ComboListproperty

c1FlexGrid1Cols[colIndex]ComboList =

Red|Green|Blue|Red|White

Mask Gets enabled whenthe EditMaskproperty of columnis set

c1FlexGrid1Cols[colIndex]EditMask =

(999) 999-9999

Mappedlist

Gets enabled whenthe DataMapproperty is set to anIDictionary objectwhich establishesmapping betweenvalues stored in thegrid and thosevisible to a user

ListDictionary customerNames = new

ListDictionary()

customerNamesAdd(AJK18F Sam

Anders)

customerNamesAdd(BBK21D Daneil)

customerNamesAdd(AEF25N Henry

Hussain)

customerNamesAdd(BZD42S Owen

Romanov)

customerNamesAdd(AKC16G Serena

Nguyen)

c1flexGrid1Cols[Name]DataMap =

customerNames

c1flexGrid1ShowButtons =

ShowButtonsEnumWithFocus

Cell Button Gets enabled whenthe ComboListproperty is set to anellipsis() whichautomaticallydisplays a cellbutton in editmode You can then

c1flexGrid1Cols[colIndex]ComboList

=

c1flexGrid1CellButtonClick +=

C1flexGrid1_CellButtonClick

FlexGrid for WinForms

46 Copyright copy GrapeCity Inc All rights reserved

capturethe CellButtonClickevent either toshow a dialog boxor to perform anyother operation

Custom EditorsFlexGrid control provides most of the commonly used editing options through the above-mentioned built-in editors However inaddition you can also use external controls as editors to meet the specialized editing needs Any control that derives from thebase Control class can be easily used as an editor This can be done at design time as well as through code In the examplebelow we are setting the C1ColorPicker control as a cell editor

At Design Time

1 Add the C1FlexGrid control and C1ColorPicker control to the form2 Select Designer option from the C1FlexGrid Tasks menu to open the C1FlexGrid Column Editor3 Select a column and switch to Properties pane on left hand side4 Navigate to the Editor property and set its value to instance of the C1ColorPicker control

At Run Time

To set an external control as editor through code create an instance of the control and assign it to the Editor property ofthe Column object

See the code below to know how to set an external control as editor in WinForms FlexGrid column

カスタムエディタとして使用するC1ColorPickerコントロールのインスタンスを作成します C1WinC1InputC1ColorPicker customeditor = new C1WinC1InputC1ColorPicker() カスタムエディタにEditorプロパティを割り当てます c1FlexGrid1Cols[1]Editor = customeditor

C

FlexGrid for WinForms

47 Copyright copy GrapeCity Inc All rights reserved

For controls which are not derived from the Control base class it is still possible to use them as editors usingIC1EmbeddedEditor interface You can even use the UITypeEditor classes as grid editors This way the FlexGrid control canuse virtually any control as a cell editor For more information about the implementation see the product sample named CustomEditors

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing WinForms Editionusing ComponentOneControlPanelexe

カスタムエディタとして使用するC1ColorPickerコントロールのインスタンスを作成します Dim customeditor As C1WinC1InputC1ColorPicker = New C1WinC1InputC1ColorPicker()

カスタムエディタにEditorプロパティを割り当てます c1FlexGrid1Cols(1)Editor = customeditor

VBNET

チェックボックス

Display Checkbox for Boolean ValuesFlexGrid by default uses the checkbox editor for representing the Boolean values That is when the DataTypeproperty of a Row or Column object is set to Bool type a checkbox appears in the cells and user can toggle the valueof an editable cell simply by clicking it

To disable this default behavior and display text value instead of a checkbox in a Bool type you can set the Formatproperty of Row or Column object to string values

Default Checkbox Checkbox with Text Checkbox with Non-Boolean Value Three-state Checkbox

Use the code below to set checkbox type editor in a WinForms FlexGrid column and configure it further

データ型をブール値に設定します(チェックボックスを自動的に表示します)c1FlexGrid1Cols[Verified]DataType = typeof(Boolean)

チェックボックスを表示する代わりに文字列値を表示しますc1flexGrid1Cols[Verified]Format = YesNo ブール列のチェックボックスの横にあるテキストを有効にしますc1flexGrid1Cols[Verified]ImageAndText = true

C

データ型をブール値に設定します(チェックボックスを自動的に表示します)c1FlexGrid1Cols(Verified)DataType = GetType(Boolean)

チェックボックスを表示する代わりに文字列値を表示しますc1flexGrid1Cols(Verified)Format = YesNo

ブール列のチェックボックスの横にあるテキストを有効にしますc1flexGrid1Cols(Verified)ImageAndText = True

VBNET

FlexGrid for WinForms

48 Copyright copy GrapeCity Inc All rights reserved

Display Checkbox for Non-Boolean ValuesIn unbound mode you can display a checkbox along with any non-boolean text as well You can use the SetCellCheckmethod to add checkbox to any kind of cells Along with row and column index this method takes valueof CheckEnum enumeration as one of its parameters to specify the state of checkbox at the time of rendering

Following code demonstrates how you can display checkbox for non-boolean values

Set Checkbox AlignmentTo set position of checkbox in the cell you need to use ImageAlign property of the Row or Column object Thisproperty accepts values from the ImageAlignEnum enumeration which lets you hide tile stretch or position the image

Align the checkbox to display in center of a WinForms FlexGrid column using the code below

Change the Checkbox ImageTo change icon image of different states of checkbox you can use the GlyphEnum which can be accessed usingthe Glyphs property For more information about changing glyphs see Custom Glyphs

You can change the images to be used for various checkbox states in WinForms FlexGrid using the code below

チェックオン状態のセル(32)に2つの状態のチェックボックスを設定します c1flexGrid1SetCellCheck(3 2 CheckEnumChecked)

C

チェックオン状態のセル(32)に2つの状態のチェックボックスを設定しますc1flexGrid1SetCellCheck(3 2 CheckEnumChecked)

VBNET

チェックボックスをセルの右中央に揃えますc1flexGrid1Cols[Verified]ImageAlign = ImageAlignEnumRightCenter

C

チェックボックスをセルの右中央に揃えますc1flexGrid1Cols(Verified)ImageAlign = ImageAlignEnumRightCenter

VBNET

カスタム画像をチェックボックスアイコンとして設定します Image imgChk = new Bitmap(ResourcesImagescheckedpng) Image imgUnchk = new Bitmap(ResourcesImagesuncheckedpng) Image imgGray = new Bitmap(ResourcesImagesnullpng) c1flexGrid1Glyphs[GlyphEnumChecked] = imgChk c1flexGrid1Glyphs[GlyphEnumUnchecked] = imgUnchk c1flexGrid1Glyphs[GlyphEnumGrayed] = imgGray

C

カスタム画像をチェックボックスアイコンとして設定します Dim imgChk As Image = New Bitmap(ResourcesImagescheckedpng) Dim imgUnchk As Image = New Bitmap(ResourcesImagesuncheckedpng)

VBNET

FlexGrid for WinForms

49 Copyright copy GrapeCity Inc All rights reserved

Use Three State CheckboxIn addition to usual two state checkbox FlexGrid lets you create three state checkbox as well The simplest way ofenabling the third state is through the CheckEnum While a Boolean checkbox togglesbetween CheckEnumChecked and CheckEnumUnchecked states the three states of a three state checkbox arerepresented by CheckEnumTSChecked CheckEnumTSUnchecked and CheckEnumTSGrayed However in thiscase by default user can not go back to null after switching to checked or unchecked state once In order to cycle acheckbox between three states you need to handle the ValidateEdit event

Use the code below to create a three state checkbox in the WinForms FlexGrid

Dim imgGray As Image = New Bitmap(ResourcesImagesnullpng) c1flexGrid1Glyphs(GlyphEnumChecked) = imgChk c1flexGrid1Glyphs(GlyphEnumUnchecked) = imgUnchk c1flexGrid1Glyphs(GlyphEnumGrayed) = imgGray

private void c1FlexGrid1_ValidateEdit(object sender ValidateEditEventArgs e) if (c1FlexGrid1Cols[eCol]Name == Done) eCancel = true if (c1FlexGrid1[eRow eCol]Equals(false)) c1FlexGrid1[eRow eCol] = true else if (c1FlexGrid1[eRow eCol]Equals(true)) c1FlexGrid1[eRow eCol] = DBNullValue else if (c1FlexGrid1[eRow eCol]Equals(DBNullValue)) c1FlexGrid1[eRow eCol] = false

C

Private Sub c1FlexGrid1_ValidateEdit(ByVal sender As Object ByVal e As ValidateEditEventArgs) If c1FlexGrid1Cols(eCol)Name Is Done Then eCancel = True

If c1FlexGrid1(eRow eCol)Equals(False) Then c1FlexGrid1(eRow eCol) = True ElseIf c1FlexGrid1(eRow eCol)Equals(True) Then c1FlexGrid1(eRow eCol) = DBNullValue ElseIf c1FlexGrid1(eRow eCol)Equals(DBNullValue) Then c1FlexGrid1(eRow eCol) = False End If End IfEnd Sub

VBNET

数値

FlexGrid by default uses the numeric editor to edit the numeric data that is when the data type is set to any of the numeric types such as Int and Decimal Thisbehavior of FlexGrid is controlled by the EditOptions property which provides various editing options through the EditFlags enumeration One of the flagsprovided is UseNumericEditor As the default value of EditOptions property is All UseNumericEditor flag is always ON and hence grid automatically enablesthe numeric editor while editing the numeric data You can access the EditOptions property at design time as well as through code

FlexGrid for WinForms

50 Copyright copy GrapeCity Inc All rights reserved

Numeric Editor Numeric Editor with Format = C0 Numeric Editor with Spin Button Numeric Editor with Calculator

At Design Time

To enable or disable the numeric editor at design time you can access the EditOptions property from the Properties window

At Run Time

At run-time you need to set the UseNumericEditor flag On in the EditOptions property Use the code below to set EditOptions property in the WinFormsFlexGrid

Format Numeric CellTo format the data in a numeric cell FlexGrid provides the Format property of Column as well as Row object In case of the formats that support decimal valuessuch as numeric currency and exponential FlexGrid displays values up to two decimal places by default However you can specify the number of decimals todisplay by appending the value of Format property with that number For instance in order to display values up to three decimal places in a Number type cellyou specify value of Format property as N3 or n3

Note This property doesnt have any effect on the stored value but only on how value is displayed at the run time You can access the formatted valueof a cell using GetDataDisplay(Int32 Int32) method of the C1FlexGrid class

You can set the Format property at design time as well as through code Following table lists the commonly used formats for numeric cells

Format Value Description

Number N or n Specifies the formatting for simple numeric values

Currency C or c Specifies the formatting for monetary values

Exponential or Scientific E or e Specifies the formatting for values using scientific notations

Percentage P or p Specifies the formatting for percentage values

Custom User-defined Takes the value of format string from user

A custom string might require handling in the code

At Design Time

1 In design view click on the FlexGrid smart tag to open the C1FlexGrid Tasks menu2 Click the Column Tasks option and navigate to Format String property3 Click ellipsis button to open the Format String dialog

すべてのフラグをオンに設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsAll

UseNumericEditorフラグのみを設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsUseNumericEditor

C

すべてのフラグをオンに設定しますc1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsAll

UseNumericEditorフラグのみを設定します c1FlexGrid1EditOptions = C1WinC1FlexGridEditFlagsUseNumericEditor

VBNET

FlexGrid for WinForms

51 Copyright copy GrapeCity Inc All rights reserved

4 Select the required format from the list box on left say Currency5 Set the format specific properties on the right hand side of the dialog Decimal places in this case

At Run Time

To specify the format of a particular numeric type column set the Format property to any of the above mentioned values In this example we have set theformat of column 3 as currency without decimals

Following code shows how to set the format of a WinForms FlexGrid column

Input using Spin ButtonTo create a numeric editor which uses a spin button for input you need to assign instance of an external control such as NumericUpDown to the Editorproperty

Use the code below to create a numeric editor with spin button in the WinForms FlexGrid

Input using CalculatorTo allow user to give input using a calculator in a numeric editor you can use the C1NumericEdit control of C1Input library as an editor So just add thereference to C1WinC1Input and assign an instance of C1NumericEdit control to the Editor property For more information about using an external controlas editor see Custom Editors

To create a numeric editor with calculator use the code below

小数点なしの通貨形式を設定します c1FlexGrid1Cols[3]Format = C0

C

小数点なしの通貨形式を設定しますc1FlexGrid1Cols(3)Format = C0

VBNET

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols[2]Editor = new NumericUpDown()

C

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols(2)Editor = New NumericUpDown()

VBNET

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols[2]Editor = new C1NumericEdit()ShowUpDownButtons=false

C

NumericUpDownコントロールを2番目の列のエディタとして割り当てますc1flexGrid1Cols(2)Editor = New C1NumericEdit() With ShowUpDownButtons = False

VBNET

日付

FlexGrid by default uses the Date editor for all the Date and DateTime type of data The Date editor consists of adropdown which opens a calendar when clicked and user can select the desired date by navigating through it Usercan also change the date month or year by simply selecting the corresponding part in the editor and pressing the upand down arrow keys

FlexGrid for WinForms

52 Copyright copy GrapeCity Inc All rights reserved

Default Date Editor Date Editor Without Calendar Date Editor with Spin Button

Use the code below to create a Date editor in a WinForms FlexGrid column

Input without Displaying CalendarAs mentioned earlier in FlexGrid a DateTime type cell automatically displays a dropdown calendar to receive theinput from user However in order to get a date input from user without displaying a calendar you can set a maskusing the EditMask property and then validate the input value using the ValidateEdit event

Following code demonstrates how to create a Date editor without calendar in WinForms FlexGrid

For more information about cell masks and validation see topics Mask and Validation respectively Another way ofhiding the calendar is to get user input using the spin buttons

Input using Spin ButtonBelow code shows how to create Date editor with spin button

To display spin buttons in a Date editor use the SetupEditor event to convert the editor into DateTimePicker and setits ShowUpDown property to true

Set the data type property to DateTime c1FlexGrid1Cols[1]DataType = typeof(DateTime)

C

Set the data type property to DateTimec1FlexGrid1Cols(1)DataType = GetType(Date)

VBNET

Set a mask on column c1flexGrid1Cols[3]EditMask = 00000000

C

Set a mask on columnc1flexGrid1Cols(3)EditMask = 00000000

VBNET

private void C1flexGrid1_SetupEditor(object sender RowColEventArgs e)

C

FlexGrid for WinForms

53 Copyright copy GrapeCity Inc All rights reserved

Set Date FormatTo set the format in a Date type column you need to set the Format property of the Column object

Following table lists the pre-defined formats

Format Value Example

Short Date d 11192003

Long Date D Friday November 19 2003

Short Time t 1215 AM

Long Time T 121530 AM

You can also create a custom format using the various custom format specifiers supported in the Net framework Fordetails see Custom date and time format strings on Microsoft website

Use the following code to create a custom date format in WinForms FlexGrid column

if (c1flexGrid1Cols[eCol]Name == DOB) Cast FlexGrids current cell editor var dateEditor = c1flexGrid1Editor as DateTimePicker

Show UpDown button (replacing the drop-down button for calendar) dateEditorShowUpDown = true

Private Sub C1flexGrid1_SetupEditor(ByVal sender As Object ByVal e As RowColEventArgs) If c1flexGrid1Cols(eCol)Name Is DOB Then Cast FlexGrids current cell editor Dim dateEditor = TryCast(c1flexGrid1Editor DateTimePicker)

Show UpDown button (replacing the drop-down button for calendar) dateEditorShowUpDown = True End IfEnd Sub

VBNET

Set a pre-defined format c1FlexGrid1Cols[DOB]Format = d Set a custom format c1FlexGrid1Cols[OrderDate]Format = ddMMyyyy

C

Set a pre-defined format c1FlexGrid1Cols(DOB)Format = d

Set a custom format c1FlexGrid1Cols(OrderDate)Format = ddMMyyyy

VBNET

FlexGrid for WinForms

54 Copyright copy GrapeCity Inc All rights reserved

Display Country-specific Date FormatAlthough abovementioned formats are the most commonly used date formats but there are cultures which preferusing their specific calendar and date formats in some cases such as Japan You can display those specific calendarsand date formats by using OwnerDrawCell event of the C1FlexGrid class and the SystemGlobalization namespaceThe namespace provides various classes to define culture related information including calendars and date formatsFor instance to display Japanese calendar and Japanese date format you can leveragethe SystemGlobalizationJapaneseCalendar class Similarly you can also display other calendars such as GregorianHebrew Hijri and Korean

Set the country specific date format in WinForms FlexGrid using the code below

Set MinMax DateTo set a range of valid values you can use the DateTimePicker control as editor and set its MinDate and MaxDate

c1flexGrid1Cols[DOB]Format = ddMMyyyy c1flexGrid1DrawMode = DrawModeEnumOwnerDraw c1flexGrid1OwnerDrawCell += C1flexGrid1_OwnerDrawCell private void C1flexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if (c1flexGrid1Cols[eCol]DataType == typeof(DateTime) ampamp eRow gt= c1flexGrid1RowsFixed) eText = DateTimeParse(eText)ToString(yyyy年MM月dd日(dddd) c)

C

C1FlexGrid1Cols(DOB)Format = ddMMyyyy C1FlexGrid1DrawMode = DrawModeEnumOwnerDraw

AddHandler C1FlexGrid1OwnerDrawCell AddressOf C1flexGrid1_OwnerDrawCell

Private Sub C1flexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If C1FlexGrid1Cols(eCol)DataType = GetType(DateTime) AndAlso eRow gt= C1FlexGrid1RowsFixed Then eText = DateTimeParse(eText)ToString(yyyy年MM月dd日(dddd) c) End If End Sub

VBNET

FlexGrid for WinForms

55 Copyright copy GrapeCity Inc All rights reserved

property

Use the code below to set a range of valid dates in WinForms FlexGrid

DateTimePicker dateTimePicker = new DateTimePicker() dateTimePickerFormat = DateTimePickerFormatShort

Sets Max and Min dates dateTimePickerMinDate = new DateTime(2015 05 01) dateTimePickerMaxDate = DateTimeToday

Assigns DateTimePicker control as editor for FirstOrderDate(date) column c1flexGrid1Cols[FirstOrderDate]Editor = dateTimePicker

C

Dim dateTimePicker As DateTimePicker = New DateTimePicker() dateTimePickerFormat = DateTimePickerFormat[Short]

Sets Max and Min dates dateTimePickerMinDate = New DateTime(2015 05 01) dateTimePickerMaxDate = DateToday

Assigns DateTimePicker control as editor for FirstOrderDate(date) column c1flexGrid1Cols(FirstOrderDate)Editor = dateTimePicker

VBNET

コンボボックス

ComboBox cell is a common way of providing the user with a well-defined list of possible values in the form of a drop-down list FlexGrid providesthis multi-option editor in various forms such as dropdown list dropdown combo ellipsis button or a textbox with ellipsis button

Default ComboBox Multi-column ComboBox ComboBox with custom BackColor ComboBox with Images

Display Dropdown List or ComboIn FlexGrid you can create a dropdown list by creating a string containing all the choices separated by pipe characters (for exampleTrue|False|Dont know) and assign it to the ComboList property of Row or Column object This causes the grid to display a drop-down buttonnext to the cell The user can click the dropdown button (or press F2) to display the list of choices available for that cell

Another common situation is where cells have a list of common values but users should be allowed to type a custom value as well This can beaccomplished with drop-down combos a combination of text box and drop-down list In FlexGrid you can create combos by starting the choicelist with a pipe character (for example |True|False|Dont know) and then assign it to the ComboList property

Following code shows how to create a dropdown list or combo editor in the WinForms FlexGrid

FlexGrid for WinForms

56 Copyright copy GrapeCity Inc All rights reserved

The ComboList property can also be set using the Combo List dialog at design time To access the Combo List dialog

1 Open the Column Tasks menu for column for which editor is to be set2 Go to the Combo List option and click the ellipsis button on the right hand side of the field3 Combo List dialog opens where you can specify the option values each in a new line4 You can also choose whether you want to display these values as a Dropdown List or Dropdown Combo Note that it also lets you create

cell button using Ellipsis Button or Textbox amp Ellipsis Button option

Display Multi-column ComboBoxIn FlexGrid you can also display multiple columns in a ComboBox using the MultiColumnDictionary class This class implementsthe IC1MultiColumnDictionary interface and has multiple overloads These overloads let you specify the data source object the key columncolumns that are to be displayed in multiple columns and the column to be displayed when ComboBox is closed

Display a multi-column combobox in a WinForms FlexGrid column using the code below

Note that the above code uses the data source object dt to supply data to the grid You can set up the data source as per your requirements

ドロップダウンリストとしてCustomerIDを割り当てますc1flexGrid1Cols[CustomerID]ComboList = AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

ドロップダウンコンボボックスとしてCustomerIDを割り当てパイプ文字|でリストを開始します c1flexGrid1Cols[CustomerID]ComboList = |AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

C

ドロップダウンリストとしてCustomerIDを割り当てますc1flexGrid1Cols(CustomerID)ComboList = AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

ドロップダウンコンボボックスとしてCustomerIDを割り当てパイプ文字|でリストを開始します c1flexGrid1Cols(CustomerID)ComboList = |AJK18F|BBK21D|AEF25N|BZD42S|AKC16G

VBNET

string[] columnRange = new string[] City Country c1FlexGrid1Cols[City]DataMap = new MultiColumnDictionary(dt City columnRange 0)

C

Dim columnRange = New String() City Countryc1FlexGrid1Cols(City)DataMap = New MultiColumnDictionary(dt City columnRange 0)

VBNET

DataTable dt = new DataTable() dtColumnsAdd(CustomerID typeof(int)) dtColumnsAdd(ContactName typeof(string)) dtColumnsAdd(Designation typeof(string)) dtColumnsAdd(City typeof(string)) dtColumnsAdd(Country typeof(object))

サンプルデータ

C

FlexGrid for WinForms

57 Copyright copy GrapeCity Inc All rights reserved

Set Mapped Data in the ComboBoxTo set a ComboBox having display values different from the actual values you need to use the C1ComboBox as editor and leverageits ItemsDisplayMember and ItemsValueMember properties For instance the example below uses country names as display values while actualvalue is the dialing code of the corresponding country

Following code shows how to set the mapped data in combobox column of the WinForms FlexGrid

dtRowsAdd(1 Maria Anders Sales Representative Madrid Spain ) dtRowsAdd(2 Ana Trujillo Sales Associate Monterrey Mexico ) dtRowsAdd(3 Antonio Moreno Owner Dublin Ireland) dtRowsAdd(4 Thomas Hardy Sales Representative Bristol UK) dtRowsAdd(5 Patricio Simpson Marketing Manager Munich Germany) dtRowsAdd(6 Paolo Accorti Sales Representative Barcelona Spain) dtRowsAdd(7 Martine Ranceacute Owner Puebla Mexico) dtRowsAdd(8 Elizabeth Brown Marketing Manager London UK) dtRowsAdd(9 Jaime Yorres Order Administrator Vienna Austria) dtRowsAdd(10 Yvonne Moncada Marketing Manager Mexico Mexico) dtRowsAdd(11 Helen Bennett OwnerMarketing Cork Ireland) dtRowsAdd(12 Sergio Gutieacuterrezy Order Administrator Sao Paulo Brazil)

c1FlexGrid1DataSource = dt

Dim dt As DataTable = New DataTable()dtColumnsAdd(CustomerID GetType(Integer))dtColumnsAdd(ContactName GetType(String))dtColumnsAdd(Designation GetType(String))dtColumnsAdd(Country GetType(Object))dtColumnsAdd(City GetType(String))

サンプルデータdtRowsAdd(1 Maria Anders Sales Representative Spain Madrid)dtRowsAdd(2 Ana Trujillo Sales Associate Mexico Monterrey)dtRowsAdd(3 Antonio Moreno Owner Ireland Dublin)dtRowsAdd(4 Thomas Hardy Sales Representative UK Bristol)dtRowsAdd(5 Patricio Simpson Marketing Manager Germany Munich)dtRowsAdd(6 Paolo Accorti Sales Representative Spain Barcelona)dtRowsAdd(7 Martine Ranceacute Owner Mexico Puebla)dtRowsAdd(8 Elizabeth Brown Marketing Manager UK London)dtRowsAdd(9 Jaime Yorres Order Administrator Austria Vienna)dtRowsAdd(10 Yvonne Moncada Marketing Manager Mexico Mexico)dtRowsAdd(11 Helen Bennett OwnerMarketing Ireland Cork)dtRowsAdd(12 Sergio Gutieacuterrezy Order Administrator Brazil Sao Paulo)c1FlexGrid1DataSource = dt

VBNET

private void Form1_Load(object sender EventArgs e) 顧客データを取得します Customers = GetCustomers()

FlexGridにデータを入力します c1FlexGrid1DataSource = Customers

国とその国コードのコレクションを作成します ObservableCollectionltCountrygt countries = new ObservableCollectionltCountrygt() countriesAdd(new Country(1 USA)) countriesAdd(new Country(91 India)) countriesAdd(new Country(7 Russia))

C

FlexGrid for WinForms

58 Copyright copy GrapeCity Inc All rights reserved

Set ComboBox DimensionsTo set the height and width of combo box dropdown you need to assign an instance of ComboBox as an editor and then setthe DropDownHeight and DropDownWidth property of that instance

countriesAdd(new Country(54 Argentina)) countriesAdd(new Country(81 Japan)) countriesAdd(new Country(380 Ukraine)) countriesAdd(new Country(98 Iran)) countriesAdd(new Country(45 Denmark)) countriesAdd(new Country(84 Vietnam)) countriesAdd(new Country(49 Germany)) BindingSource countryBS = new BindingSource() countryBSDataSource = countries

C1Comboboxコントロールをインスタンス化して設定します C1ComboBox countryCodeCombo = new C1ComboBox() countryCodeComboItemsDataSource = countryBS

region Mapped Data using C1Combobox

国コードと国名をマッピングするためにプロパティを設定します countryCodeComboItemsDisplayMember = CountryName countryCodeComboItemsValueMember = CountryCode countryCodeComboTextDetached = true countryCodeComboTranslateValue = true

C1ComboboxをDiallingCode列のエディタとして設定します c1FlexGrid1Cols[DiallingCode]Editor = countryCodeCombo endregion

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) 顧客データを取得します Customers = GetCustomers()

FlexGridにデータを入力します c1FlexGrid1DataSource = Customers

国とその国コードのコレクションを作成します Dim countries As ObservableCollection(Of Country) = New ObservableCollection(Of Country)() countriesAdd(New Country(1 USA)) countriesAdd(New Country(91 India)) countriesAdd(New Country(7 Russia)) countriesAdd(New Country(54 Argentina)) countriesAdd(New Country(81 Japan)) countriesAdd(New Country(380 Ukraine)) countriesAdd(New Country(98 Iran)) countriesAdd(New Country(45 Denmark)) countriesAdd(New Country(84 Vietnam)) countriesAdd(New Country(49 Germany)) Dim countryBS As BindingSource = New BindingSource() countryBSDataSource = countries

C1Comboboxコントロールをインスタンス化して設定します Dim countryCodeCombo As C1ComboBox = New C1ComboBox() countryCodeComboItemsDataSource = countryBS

国コードと国名をマッピングするためにプロパティを設定します countryCodeComboItemsDisplayMember = CountryName countryCodeComboItemsValueMember = CountryCode countryCodeComboTextDetached = True countryCodeComboTranslateValue = True

C1ComboboxをDiallingCode列のエディタとして設定します c1FlexGrid1Cols(DiallingCode)Editor = countryCodeComboEnd Sub

VBNET

FlexGrid for WinForms

59 Copyright copy GrapeCity Inc All rights reserved

Use the code below to specify the height and width of the combobox to be displayed in the WinForms FlexGrid

Change Background Color or Font ColorTo change the background color or font color of the ComboBox list create an instance of ComboBox to assign it as editor Then set the BackColorand ForeColor property of that instance

Customize combobox in the WinForms FlexGrid by using the code below

Display Image in the ListTo display images in the ComboBox list you need to use the C1ComboBox as an editor and leverage its ItemsImageList property This property isof type ImageList class that acts as a container for the images which are stored in its Images collection First access the images stored in theproject resources through the ResourceManagerGetResourceSet method and create a collection of mapping between images and itscorresponding names The collection acts as a data source for ComboBox Now create an instance of the ImageList class add images to itsImages collection from data source and assign that instance of ImageList class to the ItemsImageList property to render images in the ComboBoxlist

Following code shows how to display images in the combobox lists of WinForms FlexGrid

ComboBox cb = (ComboBox)c1flexGrid1Editor cbDropDownWidth = 250 cbDropDownHeight = 200

C

Dim cb As ComboBox = CType(c1flexGrid1Editor ComboBox) cbDropDownWidth = 250 cbDropDownHeight = 200

VBNET

ComboBox comboBox = new ComboBox() comboBoxBackColor = ColorBlack comboBoxForeColor = ColorWhite

C

Dim comboBox As ComboBox = New ComboBox() comboBoxBackColor = ColorBlack comboBoxForeColor = ColorWhite

VBNET

コンボボックスに画像を入力します var itemsSource = new ListltFlaggt() ImageList imgFlag = new ImageList() imgFlagImagesClear() var rsrSet = ResourcesResourceManagerGetResourceSet(CultureInfoCurrentCulture true true)

foreach(DictionaryEntry entry in rsrSet) var img = entryValue as Image itemsSourceAdd(new Flag(entryKeyToString() img)) itemsSourceSort(new CompareFlag())

foreach (Flag entry in itemsSource) imgFlagImagesAdd(entryCountryName entryCountryFlag)

countryComboItemsImageList = imgFlag

C

FlexGrid for WinForms

60 Copyright copy GrapeCity Inc All rights reserved

Set Number of Displayed ItemsTo set the number of items to be displayed in a combo box you can use ComboBoxMaxDropDownItems property

Use the code below to limit the number of items to be displayed in combobox list of the WinForms FlexGrid

Sort the ComboBox ListTo sort the items in the ComboBox dropdown list you can use the C1ComboBox as editor and call the Sort method to sort the dropdown itemsgetting displayed in the ComboBox

To display sorted items in comboboxlist of the WinForms FlexGrid use the code below

countryComboItemMode = ComboItemModeHtmlPattern countryComboHtmlPattern = ltdiv ltdiv style=padding0pxgtltimg src=CountryName style=padding-right14pxgtCountryNameltdivgt

コンボボックスに画像を入力します Dim itemsSource = New List(Of Flag)()Dim imgFlag As ImageList = New ImageList()imgFlagImagesClear()Dim rsrSet = ResourcesResourceManagerGetResourceSet(CultureInfoCurrentCulture True True)

For Each entry As DictionaryEntry In rsrSet Dim img = TryCast(entryValue Image) itemsSourceAdd(New Flag(entryKeyToString() img))Next

itemsSourceSort(New CompareFlag())

For Each entry In itemsSource imgFlagImagesAdd(entryCountryName entryCountryFlag)Next

countryComboItemsImageList = imgFlagcountryComboItemMode = ComboItemModeHtmlPatterncountryComboHtmlPattern = ltdiv ltdiv style=padding0pxgtltimg src=CountryName style=padding-right14pxgtCountryNameltdivgt

VBNET

コンボボックスのドロップダウンに表示する国の数を設定します countryComboMaxDropDownItems = 10

C

コンボボックスのドロップダウンに表示する国の数を設定しますcountryComboMaxDropDownItems = 10

VBNET

C1ComboBox countryCombo = new C1ComboBox() countryComboDropDownStyle = DropDownStyleDropDownList Listltstringgt countries = new Listltstringgt USA Canada India Russia Japan Germany countriesSort() countryComboItemsDataSource = countries

C1ComboboxをCountry列のエディタとして設定します c1FlexGrid1Cols[Country]Editor = countryCombo

C

FlexGrid for WinForms

61 Copyright copy GrapeCity Inc All rights reserved

Get the Selected IndexTo get the selected index or value of the selected item you can use the SelectedIndex property or SelectedItem property of the ComboBoxEditorclass The example below uses the ComboCloseUp event to show a message box displaying the selected index and the selected item

Use the code below to fetch the index and value of selected item in combobox list of the WinForms FlexGrid

Dim countryCombo As C1ComboBox = New C1ComboBox() countryComboDropDownStyle = DropDownStyleDropDownList Dim countries As List(Of String) = New List(Of String) From USA Canada India Russia Japan Germany countriesSort() countryComboItemsDataSource = countries

C1ComboboxをCountry列のエディタとして設定します c1FlexGrid1Cols(Country)Editor = countryCombo

VBNET

private void C1FlexGrid1_ComboCloseUp(object sender C1WinC1FlexGridRowColEventArgs e) MessageBoxShow(Selected Index + c1FlexGrid1ComboBoxEditorSelectedIndex + n + Selected Item + c1FlexGrid1ComboBoxEditorSelectedItem)

C

Private Sub C1FlexGrid1_ComboCloseUp(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) MessageBoxShow(Selected Index amp c1FlexGrid1ComboBoxEditorSelectedIndex amp vbLf amp Selected Item + c1FlexGrid1ComboBoxEditorSelectedItem)End Sub

VBNET

マスク

Mask editor refers to pre-defined templates for getting input from users which also automatically validates the userinput as it is typed Mask strings have two types of characters literal characters and template characters While literalcharacters are the ones which become part of the input the template characters serve as placeholders for charactersbelonging to specific categories (for example digits or alphabets) For example the code below assigns a (999) 999-9999 editing mask to the first column which holds phone numbers Here special characters such as braces (()) andhyphen (-) are the literals and the digit 9 is a placeholder that stands for any digit

FlexGrid for WinForms

62 Copyright copy GrapeCity Inc All rights reserved

The FlexGrid control supports masked editing through the EditMask property which can be used with regular textfields and with drop-down combo fields To apply different masks within the same column you can trap the BeforEditevent and set the EditMask property to appropriate value

You can also set the EditMask property at design time using the Input Mask dialog You can access the dialog byclicking the ellipsis button against Edit Mask field in Column Tasks menu It also means that the Edit Mask field isspecific to the column selected at that time

Note that when the EditMask property is set to a non-empty string the grid uses the masked editor even if thecolumn contains DateTime values Usually grid uses the built-in Date editor to edit DateTime type cells

電話番号の編集マスクを設定します c1FlexGrid1Cols(1)EditMask = (999) 999-9999

C

電話番号の編集マスクを設定します c1FlexGrid1Cols(1)EditMask = (999) 999-9999

VBNET

マップリスト

Mapped lists refer to the mapping of data stored in the grid to the values visible to the user Such mapping is oftenused to display user-friendly values when actual data stored in the grid is either encoded or difficult to understand bythe user For instance in an employee record table it would be more convenient for administrative executive to seenames of the employees while database stores the employee IDs

FlexGrid for WinForms

63 Copyright copy GrapeCity Inc All rights reserved

Display Data MappingIn FlexGrid data mapping can be achieved by using the DataMap property This property contains reference to anIDictionary object that establishes mapping between database values and values to be displayed in the gridHashTable ListDictionary and SortedList are some examples of IDictionary objects which provide valid data maps

Following code demonstrates how to display the data mapped list in the WinForms FlexGrid

There is a difference in how HashTable ListDictionary and SortedList classes order the items So when these tables areused with editable columns the order of items rendering in the mapped list also differs depending upon the keys andclass used to create the list

Note that the keys in the data map must be of the same type as the cells being edited For example if a columncontains short integers (Int16) then any data maps associated with the column should have short integer keys

Display Image MappingTo display image mapping in a FlexGrid column you need to set the ImageMap property of Row or Column object toan IDictionary object that establishes mapping between images and the corresponding text values For example if acolumn contains country names you can use this property to display the corresponding flags You can controlwhether to show only images or images with text by using the ImageAndText property of the object

Create an image mapping in the WinForms FlexGrid using the code below

データマップを作成しますListDictionary customerNames = new ListDictionary()customerNamesAdd(AJK18F Sam Anders)customerNamesAdd(BBK21D Daneil)customerNamesAdd(AEF25N Henry Hussain)customerNamesAdd(BZD42S Owen Romanov)customerNamesAdd(AKC16G Serena Nguyen)

データマップをflexgrid列に割り当てますc1flexGrid1Cols[Name]DataMap = customerNames

C

データマップを作成しますDim customerNames As ListDictionary = New ListDictionary()customerNamesAdd(AJK18F Sam Anders)customerNamesAdd(BBK21D Daneil)customerNamesAdd(AEF25N Henry Hussain)customerNamesAdd(BZD42S Owen Romanov)customerNamesAdd(AKC16G Serena Nguyen)

データマップをflexgrid列に割り当てますc1flexGrid1Cols(Name)DataMap = customerNames

VBNET

Hashtable ht = new Hashtable() foreach (Row row in c1flexGrid1Rows) htAdd(row[CustomerID] LoadImage(row[Photo] as byte[])) ImageMapをPhoto列に割り当てます c1flexGrid1Cols[Photo]ImageMap = ht

C

FlexGrid for WinForms

64 Copyright copy GrapeCity Inc All rights reserved

アスペクト比を維持しながら画像をセルに合わせます c1flexGrid1Cols[Photo]ImageAlign = ImageAlignEnumScale c1flexGrid1Cols[Photo]Width = 80

Dim ht As Hashtable = New Hashtable()

For Each row As Row In c1flexGrid1Rows htAdd(row(CustomerID) LoadImage(TryCast(row(Photo) Byte()))) Next

ImageMapをPhoto列に割り当てます c1flexGrid1Cols(Photo)ImageMap = ht

アスペクト比を維持しながら画像をセルに合わせます c1flexGrid1Cols(Photo)ImageAlign = ImageAlignEnumScale c1flexGrid1Cols(Photo)Width = 80

VBNET

セルボタン

Cell button editor refers to a cell with an ellipsis button This editor comes to use when you need to get an operationdone or open a dialog on a button click Such dialogs generally contain multiple different options or settings for a userto choose from

Default Cell Button Cell Button with Text Cell Button with Custom Image

Display Cell ButtonIn FlexGrid you can display a cell button by setting the ComboList property to an ellipsis character You can alsouse a pipe character before ellipsis button to display an ellipsis with text box to let user enter his inputThe CellButtonClick event is fired when user clicks the cell button You can capture this event to implement thedesired operation or display a dialog of your choice

By default the cell button gets displayed when cell enters the edit mode However you can set the ShowButtonsproperty to Always to display the cell button even in non-edit mode

Use the code below to display cell button in a WinForms FlexGrid column

Mark列のComboListプロパティを設定してセルボタンを表示するようにします c1flexGrid1Cols[Mark]ComboList = セルボタンを常に表示できるようにします c1flexGrid1Cols[Mark]ShowButtons = ShowButtonsEnumAlways

エンドユーザーがセルボタンをクリックしたときに処理します c1flexGrid1CellButtonClick += C1flexGrid1_CellButtonClick

C

Mark列のComboListプロパティを設定してセルボタンを表示するようにしますc1flexGrid1Cols(Mark)ComboList =

VBNET

FlexGrid for WinForms

65 Copyright copy GrapeCity Inc All rights reserved

The ComboList property can also be set using the Combo List dialog at design time To access the Combo List dialog

1 Open the Column Tasks menu for column for which editor is to be set2 Go to the Combo List option and click the ellipsis button on the right hand side of the field3 Combo List dialog opens where you can specify the option values each in a new line4 You can also choose whether you want to display these values as an Ellipsis Button or Textbox amp Ellipsis

Button Note that it also gives you options to create Dropdown List and Dropdown Combo

The example below demonstrates change in back color and fore color of the current row on click of the cell buttonSimilarly you can perform the desired operation in the CellButtonClick event

セルボタンを常に表示できるようにしますc1flexGrid1Cols(Mark)ShowButtons = ShowButtonsEnumAlways

エンドユーザーがセルボタンをクリックしたときに処理しますc1flexGrid1CellButtonClick += C1flexGrid1_CellButtonClick

private void C1flexGrid1_CellButtonClick(object sender RowColEventArgs e) 次のコードは色を変更して現在の行をマークします if (c1flexGrid1Rows[eRow]StyleDisplayBackColor == ColorFromName(Window)) c1flexGrid1Rows[eRow]StyleNewBackColor = ColorGreen c1flexGrid1Rows[eRow]StyleNewForeColor = ColorWhite c1flexGrid1Rows[eRow]StyleNewBackColor = ColorFromName(Window) c1flexGrid1Rows[eRow]StyleNewForeColor = ColorFromName(WindowText)

C

FlexGrid for WinForms

66 Copyright copy GrapeCity Inc All rights reserved

Change Image of Cell ButtonBy default cell button displays an ellipsis However you can change the image of cell button usingthe CellButtonImage property

Set the image of cell button in the WinForms FlexGrid as shown in the code below

Private Sub C1flexGrid1_CellButtonClick(ByVal sender As Object ByVal e As RowColEventArgs) 次のコードは色を変更して現在の行をマークします If c1flexGrid1Rows(eRow)StyleDisplayBackColor Is ColorFromName(Window) Then c1flexGrid1Rows(eRow)StyleNewBackColor = ColorGreen c1flexGrid1Rows(eRow)StyleNewForeColor = ColorWhite End If

If True Then c1flexGrid1Rows(eRow)StyleNewBackColor = ColorFromName(Window) c1flexGrid1Rows(eRow)StyleNewForeColor = ColorFromName(WindowText) End IfEnd Sub

VBNET

CellButtonImageプロパティを設定してセルボタンの画像を定義しますImage imgCellBtn = new Bitmap(ResourcesImagesbuttonpng)c1flexGrid1CellButtonImage = imgCellBtn

C

CellButtonImageプロパティを設定してセルボタンの画像を定義しますDim imgCellBtn As Image = New Bitmap(ResourcesImagesbuttonpng)c1flexGrid1CellButtonImage = imgCellBtn

VBNET

検証

Data validation lets you control the data that a user can enter into a column cell There are various ways in which adata can be validated such as restricting invalid input keys showing the error or warning information or revert thevalue to original on getting an invalid input from the user

FlexGrid for WinForms

67 Copyright copy GrapeCity Inc All rights reserved

To implement validations such as specifying the range of acceptable values or defining the minimum string length ofinput FlexGrid provides EditorValidation property of the Column class The property is oftype ValidationRuleCollection class which consists of pre-defined rules for implementing enhanced data validation inFlexGrid columns For instance the sample code below demonstrates StringLength and Required validation rulesapplied to the Customer column using the EditorValidation property

Refer the code below to know how to add validation rules in WinForms FlexGrid columns

private void SetupGridColumns() var customerNameColumn = _flexCols[CustomerName] customerNameColumnCaption = Customer customerNameColumnEditorValidationAdd(new RequiredRule()) customerNameColumnEditorValidationAdd(new StringLengthRule() MinimumLength = 2 ) var customerIDColumn = _flexCols[CustomerID] customerIDColumnVisible = false var frequencyColumn = _flexCols[Frequency] frequencyColumnFormat = 0 frequencyColumnAllowEditing = false var ageColumn = _flexCols[Age] ageColumnEditorValidationAdd(new RequiredRule()) ageColumnEditorValidationAdd(new RangeRule() Minimum = 10 Maximum = 90 )

C

FlexGrid for WinForms

68 Copyright copy GrapeCity Inc All rights reserved

Another way of applying validation is by capturing the ValidateEdit event and checking the value of EditorTextproperty If value obtained is invalid set the Cancel parameter to true to keep the grid in editing mode until userenters a valid value Such validation can be used in scenarios such as setting the range of valid values validating thecurrent cell value based on another cell value For example the below sample code validates input into a currencycolumn to ensure that values entered are between 1000 and 10000

Use ValidateEdit event to check for valid values during edit mode of the WinForms FlexGrid cell as shown in the codebelow

Private Sub SetupGridColumns() Dim customerNameColumn = _flexCols(CustomerName) customerNameColumnCaption = Customer customerNameColumnEditorValidationAdd(New RequiredRule()) customerNameColumnEditorValidationAdd(New StringLengthRule() With MinimumLength = 2 ) Dim customerIDColumn = _flexCols(CustomerID) customerIDColumnVisible = False Dim frequencyColumn = _flexCols(Frequency) frequencyColumnFormat = 0 frequencyColumnAllowEditing = False Dim ageColumn = _flexCols(Age) ageColumnEditorValidationAdd(New RequiredRule()) ageColumnEditorValidationAdd(New RangeRule() With Minimum = 10 Maximum = 90 )End Sub

VBNET

private void _flex_ValidateEdit( object sender ValidateEditEventArgs e) 金額を検証します if (_flexCols[eCol]DataType == typeof(Decimal)) try Decimal dec = DecimalParse(_flexEditorText) if ( dec lt 1000 || dec gt 10000 ) MessageBoxShow(Value must be between 1000 and 10000) eCancel = true catch MessageBoxShow(Value not recognized as a Currency) eCancel = true

C

Private Sub _flex_ValidateEdit(ByVal sender As Object ByVal e As ValidateEditEventArgs)

VBNET

FlexGrid for WinForms

69 Copyright copy GrapeCity Inc All rights reserved

金額を検証します If _flexCols(eCol)DataType Is GetType(Decimal) Then

Try Dim dec As Decimal = DecimalParse(_flexEditorText)

If dec lt 1000 OrElse dec gt 10000 Then MessageBoxShow(Value must be between 1000 and 10000) eCancel = True End If

Catch MessageBoxShow(Value not recognized as a Currency) eCancel = True End Try End IfEnd Sub

データ注釈

Data annotation means adding meaningful metadata tags to the classes and other objects making it easier to bridgethe gap between models and views by performing data validation and displaying appropriate messages to the endusers For example you may use data annotations to specify how items should be formatted what their captionsshould be whether they should be editable or not

FlexGrid supports multiple data annotation attributes used for customizing data classes displaying data from sourceand setting validation rules To use the attributes in your project you need to add a reference to theSystemComponentModelDataAnnotations assembly and then add the attributes to your data objects in the code

Note The C1FlexGrid supports the annotations defined in NET 4SystemComponentModelDataAnnotations should be version 4000 or higher

Listed below are some of the major annotation attributes that are supported in FlexGrid control Cilck herefor complete list of DataAnnotation attributes

FlexGrid for WinForms

70 Copyright copy GrapeCity Inc All rights reserved

Attribute Name Functionality in FlexGrid

Association Specifies that an entity member represents a data relationship such as a foreignkey relationship

Display Provides a general-purpose attribute that lets you specify localizable strings fortypes and members of entity partial classes

DisplayFormat Specifies how data fields are displayed and formatted by ASPNET Dynamic Data

DisplayColumn Specifies the column that is displayed in the referred table as a foreign-keycolumn

Editable Indicates whether a data field is editable

Key Denotes one or more properties that uniquely identify an entity

Validation

RequiredAttributeStringLengthAttributeRangeAttributeRegularExpressionAttributeMinLengthAttributeMetaDataAttributeMaxLengthAttributeEmailAddressAttributeCompareAttributeDataTypeAttribute

The data annotation validation attributes are used as validation rules in FlexGridoperations

The following code example shows how data annotation feature works in WinForms FlexGrid control

自動生成されたCustomerName列ヘッダに「Customer」と表示されます この列には少なくとも2つの記号の長さが最小の空でない文字列も必要です[Display(Name = Customer)][Required][StringLength(intMaxValue MinimumLength = 2)]

public string CustomerName get set 自動生成されたCustomerID列は非表示になります[Display(AutoGenerateField = false)]public int CustomerID get set

自動生成された「Frequency」列にはパーセンテージで書式設定された値が表示されます また編集を許可しません[DisplayFormat(DataFormatString = 0)][Editable(false)]public double Frequency get set

自動生成された「Age」列は事前定義された範囲の値を許可します[Required][Range(10 90)]public int Age get set サンプルデータを作成しますpublic static BindingListltDatagt GetSampleData(int cnt) var list = new BindingListltDatagt() var rnd = new Random()

C

FlexGrid for WinForms

71 Copyright copy GrapeCity Inc All rights reserved

for (int i = 0 i lt cnt i++) var item = new Data() itemCustomerName = _firstNames[rndNext(0 _firstNamesLength)] + + _lastNames[rndNext(0 _lastNamesLength)] itemCustomerID = i itemFrequency = rndNextDouble() itemAge = rndNext(10 91) listAdd(item) return list

自動生成されたCustomerName列ヘッダに「Customer」と表示されます この列には少なくとも2つの記号の長さが最小の空でない文字列も必要です ltDisplay(Name=Customer)gt ltRequiredgt ltStringLength(IntegerMaxValue MinimumLength=2)gt Public Property CustomerName As String 自動生成されたCustomerID列は非表示になります ltDisplay(AutoGenerateField=False)gt Public Property CustomerID As Integer 自動生成された「Frequency」列にはパーセンテージで書式設定された値が表示されます また編集を許可しません ltDisplayFormat(DataFormatString=0)gt ltEditable(False)gt Public Property Frequency As Double 自動生成された「Age」列は事前定義された範囲の値を許可します ltRequiredgt ltRange(10 90)gt Public Property Age As Integer

サンプルデータを作成します Public Shared Function GetSampleData(ByVal cnt As Integer) As BindingList(Of Data) Dim list = New BindingList(Of Data)() Dim rnd = New Random()

For i As Integer = 0 To cnt - 1 Dim item = New Data() itemCustomerName = _firstNames(rnd[Next](0 _firstNamesLength)) amp + _lastNames(rnd[Next](0 _lastNamesLength)) itemCustomerID = i itemFrequency = rndNextDouble() itemAge = rnd[Next](10 91) listAdd(item) Next

Return list End Function

VBNET

スパークライン

Sparklines are the miniature charts visually representing a series of values to show trends such as periodic fluctuationsor to highlight maximum or minimum values of the data series In grids sparklines are specially useful as they easily fitin a single cell and can help identify the data patterns at a glance

FlexGrid for WinForms

72 Copyright copy GrapeCity Inc All rights reserved

FlexGrid for WinForms lets you display sparklines in columns by setting ShowSparkline property of the Column classto true You can also set the type of sparkline using SparklineType property of the Sparkline class FlexGrid supportsthree types of sparklines which are

Line Similar to line chart line sparkline indicates change in values over a period of time with the help of a lineColumn Similar to column charts column sparkline uses vertical columns to demonstrate pattern acrossdifferent categoriesWinLoss Similar to column sparkline winloss sparkline uses vertical columns to represent values However itdoes not indicate the magnitude and is generally used to indicate the binary data

To display the data markers on sparkline you can set the ShowMarkers property to true The Sparkline class alsoprovides properties to highlight the first last highest lowest or negative data points by displaying them in differentformat You can even style the sparklines using the Styles property

Below code shows how to add sparkline to the WinForms FlexGrid columns

WinLossSparklineを表示するようにプロパティを設定します c1FlexGrid1Cols[2]ShowSparkline = true c1FlexGrid1Cols[2]SparklineSparklineType = SparklineTypeWinLoss c1FlexGrid1Cols[2]SparklineStylesSeriesColor = ColorGreen c1FlexGrid1Cols[2]SparklineShowNegative = true

C

WinLossSparklineを表示するようにプロパティを設定します c1FlexGrid1Cols(2)ShowSparkline = True c1FlexGrid1Cols(2)SparklineSparklineType = SparklineTypeWinLoss c1FlexGrid1Cols(2)SparklineStylesSeriesColor = ColorGreen c1FlexGrid1Cols(2)SparklineShowNegative = True

VBNET

ヘッダとフッタ

Column header refers to the fixed rows on the top of the grid which contains a caption string sort glyph etc

In FlexGrid by default the top row with zero index is allocated for the column header However you can span the header to other rows aswell by specifying them as fixed To set more than one rows as fixed you need to set the Fixed property of RowCollection class to an integergreater than 1

FlexGrid for WinForms

73 Copyright copy GrapeCity Inc All rights reserved

Set Header TextFlexGrid when in bound mode reads the field names from the data source and renders them as column header text However youcan explicitly set Caption property of the Row class to overwrite field name string from the data source In case of unbound grid as well theCaption property specifies the header text Note that this property sets the value of cells in the default header row at zero index To setvalue in the other fixed row cells you need to use the usual value allocation ways of FlexGrid For more information on how to set cellvalues see Set Value in Cell

Specify the header rows and set the header text in WinForms FlexGrid using the code below

Merge Column HeaderFlexGrid provides the AllowMerging property for Row object which specifies whether it is allowed to merge cells in a particular row (in thiscase the header row) or not Once you have allowed merging in the header row set either AllowMerging or AllowMergingFixed propertyof C1FlexGrid class to FixedOnly Availability of these two properties in the FlexGrid control offers you more flexibility to implement multiplelogics related to merging For more information on merging cells see Merge

Use the code below to merge column headers in the WinForms FlexGrid

Wrap Column Header Text

2つの行を列ヘッダ行として設定しますc1FlexGrid1RowsFixed = 2 最初の列のヘッダとサブヘッダを設定しますc1FlexGrid1Cols [1] Caption = Column Header 1c1FlexGrid1 [11] = Column Sub-header 1

C

2つの行を列ヘッダー行として設定します c1FlexGrid1RowsFixed = 2

最初の列のヘッダとサブヘッダを設定します c1FlexGrid1Cols(1)Caption = Column Header 1 c1FlexGrid1(1 1) = Column Sub-header 1

VBNET

ヘッダ行でのマージを許可しますc1FlexGrid1Rows[0]AllowMerging = true

グリッドのAllowMergingまたはAllowMergingFixedプロパティを設定して固定行のみを結合します c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

ヘッダ行でのマージを許可しますc1FlexGrid1Rows(0)AllowMerging = True

グリッドのAllowMergingまたはAllowMergingFixedプロパティを設定して固定行のみを結合します c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

FlexGrid for WinForms

74 Copyright copy GrapeCity Inc All rights reserved

To wrap the text in column header access the CellStyle item Fixed of the CellStyleCollection class and set its WordWrap property totrue Note that to view the wrapped text properly you need to adjust the row height or just call the AutoSizeRow() method to automaticallyresize the row according to the text length

Use the code below to wrap header text of the WinForms FlexGrid columns

Style Column HeaderTo style the column header you can access the CellStyle item Fixed of the CellStyleCollection class and set various styling relatedproperties for same such as Font ForeColor and TextEffect

Customize column header of the WinForms FlexGrid using the code below

Set Column FooterColumn Footer refers to the last row of the grid which displays additional information about the whole column Most common use ofcolumn footer is to show the summary of column data

In FlexGrid you can create the column footer by using Footers property of the C1FlexGrid class FlexGrid lets you choose whether toscroll the footer along with rows or keep it fixed at the bottom of the grid by using Fixed property of the Footers class This class alsoprovides the Descriptions property which accesses the FooterDescription collection to set the additional information such as Caption Todisplay aggregate result in the column footer through various aggregate functions you must access the AggregateDefinition collection

列のキャプションを設定しますc1FlexGrid1Cols[3]Caption = Large Text for Column Header Text Wrapping

行の高さを設定しますc1FlexGrid1Rows[0]Height = 50

固定の行と列のワードラップを設定しますc1FlexGrid1Styles[Fixed]WordWrap = true

C

列のキャプションを設定しますc1FlexGrid1Cols(3)Caption = Large Text for Column Header Text Wrapping

行の高さを設定しますc1FlexGrid1Rows(0)Height = 50

固定の行と列のワードラップを設定しますc1FlexGrid1Styles(Fixed)WordWrap = True

VBNET

ヘッダテキストのフォントを設定しますc1FlexGrid1Styles[Fixed]Font = new Font(Tahoma 10 FontStyleBold) ヘッダテキストの前色を設定しますc1FlexGrid1Styles[Fixed]ForeColor = ColorAqua ヘッダーテキストの背景色を設定しますc1FlexGrid1Styles[Fixed]BackColor = ColorBlue

ヘッダテキストにテキスト効果を適用しますc1FlexGrid1Styles[Fixed]TextEffect = C1WinC1FlexGridTextEffectEnumRaised

C

ヘッダテキストのフォントを設定します c1FlexGrid1Styles(Fixed)Font = New Font(Tahoma 10 FontStyleBold)

ヘッダテキストの前色を設定します c1FlexGrid1Styles(Fixed)ForeColor = ColorAqua

ヘッダーテキストの背景色を設定します c1FlexGrid1Styles(Fixed)BackColor = ColorBlue

ヘッダテキストにテキスト効果を適用します c1FlexGrid1Styles(Fixed)TextEffect = C1WinC1FlexGridTextEffectEnumRaised

VBNET

FlexGrid for WinForms

75 Copyright copy GrapeCity Inc All rights reserved

using Aggregates property of the FooterDescription class Aggregate functions can be specified using the Aggregate property whichaccepts values from AggregateEnum enumeration

Following code shows how to add a column footer in the WinForms FlexGrid

列にフッタを追加しますc1FlexGrid1FootersDescriptionsAdd(new C1WinC1FlexGridFooterDescription() Caption = Total ) フッタに集計を適用しますc1FlexGrid1FootersDescriptions[0]AggregatesAdd(new C1WinC1FlexGridAggregateDefinition() Column = 4 Aggregate = C1WinC1FlexGridAggregateEnumSum )

C

列にフッタを追加しますc1FlexGrid1FootersDescriptionsAdd(New C1WinC1FlexGridFooterDescription() With Caption = Total )

フッタに集計を適用しますc1FlexGrid1FootersDescriptions(0)AggregatesAdd(New C1WinC1FlexGridAggregateDefinition() With Column = 4 Aggregate = C1WinC1FlexGridAggregateEnumSum )

VBNET

サイズ変更

Set Column WidthFlexGrid provides the DefaultSize property of ColumnCollection class to set the column width across the grid You canalso specify the width of a particular column by setting the Width property of the Column class Default value ofWidth property is -1 which indicates that the column is taking width specified by the DefaultSize property The Widthproperty is also available at design time through the C1FlexGrid Column Editor For more information on columneditor see Editors

Use the code below to set the default width of a column of the WinForms FlexGrid

Auto-adjust Column WidthTo adjust the column width according to the text length FlexGrid provides the AutoSizeCol() and AutoSizeCols()methods While AutoSizeCol() method automatically adjusts width of the specified column the AutoSizeCols()method is used for cell ranges

Following code shows how you can auto adjust the column widths according to the text length in the WinFormsFlexGrid

すべての列のデフォルト幅を設定しますc1FlexGrid1ColsDefaultSize = 110最初の列の幅を設定しますc1FlexGrid1Cols [1] Width = 30

C

すべての列のデフォルト幅を設定します c1FlexGrid1ColsDefaultSize = 110最初の列の幅を設定します c1FlexGrid1Cols(1)Width = 30

VBNET

FlexGrid for WinForms

76 Copyright copy GrapeCity Inc All rights reserved

Set MinMax Column WidthFlexGrid allows you to set bounds to the column width by using the MinSize and MaxSize propertiesof ColumnCollection This feature is especially useful in scenarios such as when AllowResizing property is set to trueor while using the AutoSizeCol or AutoSizeCols method

Specify the bounds of column width in the WinForms FlexGrid using the code below

Star SizingStar sizing refers to proportional sizing of grid columns to occupy the available space so that layout of grid remainssame even on resizing For instance consider a grid with 5 columns whose star sizes are specified as 3 2 and In this case first fourth and fifth column always take the same width and grid allocates thrice the width of firstcolumn to the second and twice the width to third column

テキストの長さに応じて最初の列の幅を自動調整しますc1FlexGrid1AutoSizeCol(1) 列の幅を1番目から4番目まで自動調整しますc1FlexGrid1AutoSizeCols(1 4 2)

すべての列の幅を自動調整します c1FlexGrid1AutoSizeCols()

C

テキストの長さに応じて最初の列の幅を自動調整しますc1FlexGrid1AutoSizeCol(1)

列の幅を1番目から4番目まで自動調整しますc1FlexGrid1AutoSizeCols(1 4 2)

すべての列の幅を自動調整します c1FlexGrid1AutoSizeCols()

VBNET

列コレクションの最小幅を設定します c1FlexGrid1ColsMinSize = 20 列コレクションの最大幅を設定します c1FlexGrid1ColsMaxSize = 60

C

列コレクションの最小幅を設定します c1FlexGrid1ColsMinSize = 20

列コレクションの最大幅を設定します c1FlexGrid1ColsMaxSize = 60

VBNET

FlexGrid for WinForms

77 Copyright copy GrapeCity Inc All rights reserved

FlexGrid provides the StarWidth property of Column class to specify the star sizes of columns To restrict the widthsfrom getting too narrow or too wide you can set the MinWidth and MaxWidth properties These properties are alsoavailable through the C1FlexGrid Column Editor For more information on column editor see Editors

Set star sizing or proportional sizing in the WinForms FlexGrid columns using the code below

列のスターサイズを設定しますc1FlexGrid1Cols[1]StarWidth = c1FlexGrid1Cols[2]StarWidth = 3c1FlexGrid1Cols[3]StarWidth = 2c1FlexGrid1Cols[4]StarWidth = c1FlexGrid1Cols[5]StarWidth =

列が狭くなりすぎないようにMinWidthプロパティを設定しますc1FlexGrid1Cols[1]MinWidth = 50

C

列のスターサイズを設定しますc1FlexGrid1Cols(1)StarWidth = c1FlexGrid1Cols(2)StarWidth = 3c1FlexGrid1Cols(3)StarWidth = 2c1FlexGrid1Cols(4)StarWidth = c1FlexGrid1Cols(5)StarWidth =

列が狭くなりすぎないようにMinWidthプロパティを設定しますc1FlexGrid1Cols(1)MinWidth = 50

VBNET

FlexGrid for WinForms

78 Copyright copy GrapeCity Inc All rights reserved

A grid control is a collection of rows and columns Columns generally contain a particular type of information through out while rows are used to recorddifferent types of information about a particular item

In FlexGrid the collection of rows is represented by the RowCollection class which can be accessed through Rows property of the C1FlexGrid class Thissection discusses the various operations that can be performed on rows

Topic Snapshot Content

Basic Operations Discusses about how to perform basic row operations

Set Row CountAdd RowDelete RowInsert RowSet Data TypeSet Fixed RowSet Frozen Row

User Interaction Discusses about operations that can be performed by the end-user at run time

Allow AddingAllow DeletingAllow DraggingAllow FreezingAllow Resizing

Header Discusses about how to set row header and perform other related operations

Set Header TextMerge Row HeaderWrap Row Header TextStyle Row Header

Row Detail Discusses how to display additional information using row detail feature

In-form EditingHierarchical ViewCustom Row Details

Sizing Discusses about various aspects of row sizing

Set Row HeightAuto-adjust Row HeightSet MinMax Row Height

基本操作

This topic discusses various basic operations which can be performed on a row

Set Row CountWhen grid is bound to a data source the number of rows is determined by the number of records available in thedata source However in the case of unbound mode you can set any integer value in Count property ofthe RowCollection class to set the number of rows to be displayed in the grid

Use the code below to set row count in the WinForms FlexGrid

Set row count c1FlexGrid1RowsCount = 15

C

VBNET

FlexGrid for WinForms

79 Copyright copy GrapeCity Inc All rights reserved

Add RowFlexGrid provides various ways to add a new row at runtime You can either use Add method of the RowCollectionclass or AddItem method of the C1FlexGrid class to add a new record In the unbound mode you can also incrementthe value of Count property to add new rows Note that all these ways add rows towards the end of the grid To inserta row at a specific location see Insert Row Also note that an exception is thrown if a new row is added to a boundgrid using Count property

Add a row to WinForms FlexGrid using any of these approaches shown in the code below

Delete RowTo delete a particular row from the grid you can use Remove method of the RowCollection class and specify the rowyou want to delete as its parameter The RowCollection class also provides RemoveRange method which allows you

Set row countc1FlexGrid1RowsCount = 15

Approach1 Use the RowCollectionAdd method to add row C1WinC1FlexGridRow r r = c1FlexGrid1RowsAdd() Set data r[1] = New Row 2

Approach2 Use AddItem method to add row and set data c1FlexGrid1AddItem( + t + New Row 1) Approach3 Use the RowCollectionCount property to add row c1FlexGrid1RowsCount += 1 Set data c1FlexGrid1[c1FlexGrid1RowsCount - 1 1] = New Row 3

C

Approach1 Use the RowCollectionAdd method to add row Dim r As C1WinC1FlexGridRow r = c1FlexGrid1RowsAdd()

Set data r(1) = New Row 2

Approach2 Use AddItem method to add row and set data c1FlexGrid1AddItem( amp vbTab amp New Row 1)

Approach3 Use the RowCollectionCount property to add row c1FlexGrid1RowsCount += 1

Set data c1FlexGrid1(c1FlexGrid1RowsCount - 1 1) = New Row 3

VBNET

FlexGrid for WinForms

80 Copyright copy GrapeCity Inc All rights reserved

to remove a range of rows using a single call Similarly you can also use RemoveItem method of the C1FlexGridclass to remove a specific row In the unbound grid you can reduce the number of rows by changing the value ofCount property

Following code gives different approaches to delete row from the WinForms FlexGrid

Insert RowTo insert a row in FlexGrid at a specific location you can use Insert method of the RowCollection class which lets youspecify the position where rows are to be inserted You can also insert multiple rows in the grid by usingthe InsertRange method

Below code demonstrates how to insert a row at a particular position in the WinForms FlexGrid

Approach1 Remove second row using RowCollectionRemove methodc1FlexGrid1RowsRemove(2)

Approach1 Remove second row using the RemoveItem methodc1FlexGrid1RemoveItem(2)

Approach3 Remove 3 rows starting from second using the RemoveRange methodc1FlexGrid1RowsRemoveRange(2 3) Approach4 Remove last row using the RowCollectionCount property c1FlexGrid1RowsCount -= 1

C

Approach1 Remove second row using RowCollectionRemove method c1FlexGrid1RowsRemove(2)

Approach1 Remove second row using the RemoveItem method c1FlexGrid1RemoveItem(2)

Approach3 Remove 3 rows starting from second using the RemoveRange method c1FlexGrid1RowsRemoveRange(2 3)

Approach4 Remove last row using the RowCollectionCount property c1FlexGrid1RowsCount -= 1

VBNET

C1WinC1FlexGridRow r Approach1 Use the Insert method to insert row at second position r = c1FlexGrid1RowsInsert(2) r[1] = Inserted row Approach2

C

FlexGrid for WinForms

81 Copyright copy GrapeCity Inc All rights reserved

Set Data TypeIn case of a bound FlexGrid data type of each bound column is automatically picked from the data source dependingon the data However in the case of unbound mode you can set the data type of rows or columns by specifyingthe DataType property of Row or Column class respectively Note that when data type is set for both rows andcolumns column settings take preference over row settings

Use the code below to set data type of a WinForms FlexGrid row

Set Fixed RowFixed rows refer to the rows with non-editable cells which are always visible on top of the grid even when user scrollsdown the grid In FlexGrid fixed rows can be set using Fixed property of the RowCollection class This propertyaccepts an integer value that specifies the number of rows to be fixed

Set fixed rows in the WinForms FlexGrid using the code below

Set Frozen RowFrozen rows similar to fixed rows are non-scrollable but can be edited by the user In FlexGrid frozen rows can be set

Use the InsertRange method to add three rows at second position c1FlexGrid1RowsInsertRange(2 3)

Dim r As C1WinC1FlexGridRow Approach1 Use the Insert method to insert row at second position r = c1FlexGrid1RowsInsert(2) r(1) = Inserted row

Approach2 Use the InsertRange method to add three rows at second position c1FlexGrid1RowsInsertRange(2 3)

VBNET

C1WinC1FlexGridRow r r = c1FlexGrid1RowsAdd() rDataType = typeof(int)

C

Dim r As C1WinC1FlexGridRow r = c1FlexGrid1RowsAdd() rDataType = GetType(int)

VBNET

Set three rows as fixed c1FlexGrid1RowsFixed = 3

C

Set three rows as fixedc1FlexGrid1RowsFixed = 3

VBNET

FlexGrid for WinForms

82 Copyright copy GrapeCity Inc All rights reserved

by using Frozen property provided by the RowCollection class

Use the code below to set frozen rows in the WinForms FlexGrid

Set first two rows as frozen c1FlexGrid1RowsFrozen = 2

C

Set first two rows as frozen c1FlexGrid1RowsFrozen = 2

VBNET

ユーザー操作

This topic discusses how you can let end-users interact with the FlexGrid rows

Allow AddingBy default FlexGrid does not allow end-user to add new row to the grid To provide an option to add rows at runtimeyou can set AllowAddNew property of the C1FlexGrid class to true FlexGrid also provides a design-time optionEnable Adding Rows in C1FlexGrid Tasks menu to allow adding new row by the end-user For more information ontask menus see Tasks Menus Moreover you can also set watermark text to be displayed in the new row templatethrough NewRowWatermark property

Use the code below to allow users to add rows in WinForms FlexGrid at run-time

Allow user to add rows c1FlexGrid1AllowAddNew = true Set watermark in the template new row c1FlexGrid1NewRowWatermark = Add new row

C

Allow user to add rows c1FlexGrid1AllowAddNew = True

Set watermark in the template new row

VBNET

FlexGrid for WinForms

83 Copyright copy GrapeCity Inc All rights reserved

Allow DeletingFlexGrid by default does not allow end-user to delete rows from the grid However if your application requires youcan let the end-user delete the selected rows through Delete key by setting AllowDelete property to true You canalso enable row deletion by checking ON the Enable Deleting Rows checkbox on the C1FlexGrid Tasks menu

Following code shows how to allow users to delete rows from WinForms FlexGrid at run-time

Allow DraggingFlexGrid by default does not allow user to rearrange rows by dragging However you can change this behavior inunbound grid by using the FlexGridAllowDragging property and RowAllowDragging property To enable dragging ofgrid rows you can set the FlexGridAllowDragging property to either Rows or Both This property accepts the valuesfrom AllowDraggingEnum You can also disable dragging of a particular row by setting the RowAllowDraggingproperty to false

Note As moving a row is not allowed in bound mode the bound grid throws an exception on dragging arow To implement dragging in bound mode see the blog Drag and Drop Rows in C1Flexgrid

Let users drag the rows in an unbound WinForms FlexGrid at run-time by using the code below

Allow FreezingTo allow end user to freeze the rows at runtime you can use AllowFreezing property of the C1FlexGrid class whichaccepts values from AllowFreezingEnum When this property is set to Rows or Both a lock sign appears when mouseis hovered over the edge of header row End-user can click and drag the lock sign to freeze the rows

Use the code below to allow your users to freeze the WinForms FlexGrid rows at run-time

c1FlexGrid1NewRowWatermark = Add new row

Allow user to delete rowsc1FlexGrid1AllowDelete = true

C

Allow user to delete rowsc1FlexGrid1AllowDelete = True

VBNET

Allow dragging of all rows across the grid c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumRows Disable dragging of a particular row c1FlexGrid1Rows[3]AllowDragging = false

C

Allow dragging of all rows across the grid c1FlexGrid1AllowDragging = C1WinC1FlexGridAllowDraggingEnumRows

Disable dragging of a particular row c1FlexGrid1Rows(3)AllowDragging = False

VBNET

FlexGrid for WinForms

84 Copyright copy GrapeCity Inc All rights reserved

Allow ResizingBy default FlexGrid does not give option to resize the rows To change this behavior you can use AllowResizingproperty of the C1FlexGrid class This property accepts values from the AllowResizingEnum enumerationwhich enables end-user to change size of columns rows or both The enumeration also gives you options touniformly resize the rows columns or both that is if you resize one of the columns or rows the grid automaticallyresizes rest of the columns or rows as well FlexGrid also provides RowAllowResizing property which is Boolean typeand lets you enable or disable resizing of a particular row

Following code shows how to allow users to resize the WinForms FlexGrid rows at run-time

Allow freezing of rows at runtimec1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumRows

C

Allow freezing of rows at runtimec1FlexGrid1AllowFreezing = C1WinC1FlexGridAllowFreezingEnumRows

VBNET

Allow user to resize rows c1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumRows Stop user from resizing second row c1FlexGrid1Rows[2]AllowResizing = false

C

Allow user to resize rows c1FlexGrid1AllowResizing = C1WinC1FlexGridAllowResizingEnumRows

Stop user from resizing second row c1FlexGrid1Rows(2)AllowResizing = False

VBNET

ヘッダ

Row header refers to the fixed rows on the left hand side of the grid which may or may not contain the caption string

In FlexGrid by default the left most column with zero index is allocated for the row header However you can span theheader to other columns as well by specifying them as fixed To set more than one column as fixed you need toset the Fixed property of ColumnCollection class to an integer greater than 1

FlexGrid for WinForms

85 Copyright copy GrapeCity Inc All rights reserved

Set Header TextTo set the row header text you can set Caption property of the Row class Note that this property sets the value of cellsin the default header column at zero index To set value in the other fixed column cells you need to use the usual valueallocation ways of FlexGrid For more information on how to set cell values see Set Value in Cell

Specify the header column and set the header text in WinForms FlexGrid using the code below

Merge Row HeaderFlexGrid provides AllowMerging property of the Column class which specifies whether it is allowed to merge cells in aparticular column (in this case the header column) or not Once you have allowed merging in the header columnset either AllowMerging or AllowMergingFixed property of the C1FlexGrid class to FixedOnly Availability of these twoproperties in the FlexGrid control offers you more flexibility to implement multiple logics related to merging For moreinformation on merging cells see Merge

Set header for first rowc1FlexGrid1Rows[1]Caption = Row 1

Set header for all rowsfor (int i = c1FlexGrid1RowsFixed i lt c1FlexGrid1RowsCount i++) c1FlexGrid1[i 0] = Row + iToString()

Set column widthc1FlexGrid1Cols[0]Width = 85

C

Set header for first row c1FlexGrid1Rows(1)Caption = Row 1

Set header for all rows For i As Integer = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 c1FlexGrid1(i 0) = Row amp iToString() Next

Set column width c1FlexGrid1Cols(0)Width = 85

VBNET

FlexGrid for WinForms

86 Copyright copy GrapeCity Inc All rights reserved

Use the code below to merge row headers in the WinForms FlexGrid

Wrap Row Header TextTo wrap the text in row header access the CellStyle item Fixed of the CellStyleCollection class and set its WordWrapproperty to true Note that to view the wrapped text properly you need to adjust height of FlexGrid rows or just callthe AutoSizeRow() method to automatically resize the rows according to the length of text

Use the code below to wrap header text of the WinForms FlexGrid rows

Style Row HeaderTo style the row header you can access the CellStyle item Fixed of the CellStyleCollection class and set variousstyling related properties for same such as Font ForeColor and TextEffect

Allow merging on the header columnc1FlexGrid1Cols[0]AllowMerging = true

Set AllowMerging or AllowMergingFixed property of the grid to merge fixed rowcolumns only c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

Allow merging on the header columnc1FlexGrid1Cols(0)AllowMerging = True

Set AllowMerging or AllowMergingFixed property of the grid to merge fixed rowcolumns only c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnlyc1FlexGrid1AllowMergingFixed = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

Set row captionc1FlexGrid1Rows[3]Caption = Large text to display text wrapping and mergingc1FlexGrid1Rows[4]Caption = Large text to display text wrapping and merging Set row heightc1FlexGrid1Rows[3]Height = 35c1FlexGrid1Rows[4]Height = 35

Set word wrapping for fixed rows and columnsc1FlexGrid1Styles[Fixed]WordWrap = true

C

Set row captionc1FlexGrid1Rows(3)Caption = Large text to display text wrapping and mergingc1FlexGrid1Rows(4)Caption = Large text to display text wrapping and merging

Set row heightc1FlexGrid1Rows(3)Height = 35c1FlexGrid1Rows(4)Height = 35

Set word wrapping for fixed rows and columnsc1FlexGrid1Styles(Fixed)WordWrap = True

VBNET

FlexGrid for WinForms

87 Copyright copy GrapeCity Inc All rights reserved

Customize row header of the WinForms FlexGrid using the code below

Set font of the header textc1FlexGrid1Styles[Fixed]Font = new Font(Tahoma 10 FontStyleBold) Set forecolor of the header textc1FlexGrid1Styles[Fixed]ForeColor = ColorPaleVioletRed Set backcolor of the header textc1FlexGrid1Styles[Fixed]BackColor = ColorLemonChiffon Apply text effect on the header textc1FlexGrid1Styles[Fixed]TextEffect = C1WinC1FlexGridTextEffectEnumInset

C

Set font of the header text c1FlexGrid1Styles(Fixed)Font = New Font(Tahoma 10 FontStyleBold)

Set forecolor of the header text c1FlexGrid1Styles(Fixed)ForeColor = ColorPaleVioletRed

Set backcolor of the header text c1FlexGrid1Styles(Fixed)BackColor = ColorLemonChiffon

Apply text effect on the header text c1FlexGrid1Styles(Fixed)TextEffect = C1WinC1FlexGridTextEffectEnumInset

VBNET

行の詳細

Row detail is a feature to provide additional information related to a row or record in the form of another expandablelayer In such case row which is the first layer contains the basic information while the second layer contains the detailedinformation This feature is specially useful when the additional information is too large to be displayed in the availablescreen space or it is not consistent for every record

FlexGrid for WinForms

88 Copyright copy GrapeCity Inc All rights reserved

FlexGrid provides the row detail feature using IC1FlexGridRowDetail interface which is implemented by the detail controls tobe hosted on detail row In addition FlexGrid also provides a separate assembly C1WinC1FlexGridRowDetails452dllto provide template user controls InputPanel and FlexGrid ready to be used in detail row You can add details section toany row in FlexGrid which enables you to group data in a template which is visible optionally This allows users to viewadditional data related to a row by simply selecting the row The grid also provides built-in expand or collapse buttons tocontrol the visibility of data within the expandable row

Some common use case scenarios of row detail feature are

1 In-form editing where an InputPanel control is hosted to get input from the user to fill information in a record2 Hierarchical grid which contains a master grid and a detail grid to show additional information about the record3 Custom row details where any control can be used to create row detail template

Detailed implementation of these scenarios is given in their respective sections below

In-form EditingFlexGrid supports in-form editing by hosting InputPanel control in detail row The InputPanel control contains data fieldswhere user can enter or edit the values like a form Once user finishes editing fields those values get reflected in theselected row

FlexGrid for WinForms

89 Copyright copy GrapeCity Inc All rights reserved

In FlexGrid you can implement in-form editing by adding reference to C1WinC1FlexGridRowDetails452dll and usingthe C1InputPanelRowDetail class which already implements the IC1FlexGridRowDetail interface The instance of this classis then assigned to RowDetailProvider property of the C1FlexGrid class which adds the InputPanel control to detail rowand enables the in-form editing

Hierarchical ViewHierarchical view refers to master-detail model where top level grid is the master grid and nested grid is the detail gridwhich displays additional information about expanded row of the master grid For instance example below demonstratesthe master-detail structure using Customer and Order tables respectively with CustomerID as common data element todefine a relation

flexGridRowDetailProvider = (g r) =gt new C1InputPanelRowDetail()flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected

C

flexGridRowDetailProvider = Function(g r) New C1InputPanelRowDetail()flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected

VBNET

FlexGrid for WinForms

90 Copyright copy GrapeCity Inc All rights reserved

In FlexGrid you can implement hierarchical grid by adding reference to C1WinC1FlexGridRowDetails452dll and usingthe C1FlexGridRowDetail class which already implements the IC1FlexGridRowDetail interface The instance of this class isthen assigned to RowDetailProvider property of the C1FlexGrid class to nest another grid in the detail row which enablesthe hierarchical grid interface

private void FlexGrid_Load(object sender EventArgs e) string conn = UtilGetConnectionString() var ds = new DataSet() string[] tables = Customers OrdersSplit() foreach (string tableName in tables) UtilFillTable(ds tableName conn) Defining relation between master and detail grid dsRelationsAdd(Customers_Orders dsTables[Customers]Columns[CustomerID] dsTables[Orders]Columns[CustomerID]) flexGridDataSource = ds flexGridDataMember = Customers flexGridRowDetailProvider = (g r) =gt new C1FlexGridRowDetail() flexGridAreRowDetailsFrozen = false

C

Private Sub FlexGrid_Load(ByVal sender As Object ByVal e As EventArgs) Dim conn As String = UtilGetConnectionString() Dim ds = New DataSet() Dim tables As String() = Customers OrdersSplit(c)

For Each tableName As String In tables UtilFillTable(ds tableName conn) Next Defining relation between master and detail grid dsRelationsAdd(Customers_Orders dsTables(Customers)Columns(CustomerID) dsTables(Orders)Columns(CustomerID))

VBNET

FlexGrid for WinForms

91 Copyright copy GrapeCity Inc All rights reserved

Custom Row DetailsIn addition to the InputPanel and FlexGrid control you can also host a custom control in the detail row of a grid Forinstance in the example below a text label control is attached to the row to enlist the additional information withoutaffecting the dimensions of the grid

To implement the custom row details in FlexGrid you need to create a user control which implementsthe IC1FlexGridRowDetail interface For instance here we have created a class named CustomRowDetail which representsthe text label control to be hosted in the detail row You then need to assign an object of this class to RowDetailProviderproperty of the C1FlexGrid class to enable the custom control to display additional information in the detail row

flexGridDataSource = ds flexGridDataMember = Customers flexGridRowDetailProvider = Function(g r) New C1FlexGridRowDetail() flexGridAreRowDetailsFrozen = False End Sub

private void CustomSample_Load(object sender EventArgs e) flexGridDataSource = DemoDataSource(Employees) flexGridRowDetailProvider = (g r) =gt new CustomRowDetail() flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected flexGridCols[Notes]Visible = false

Custom row detail class which shows label with notes about employee public class CustomRowDetail C1Label IC1FlexGridRowDetail Used to setup control before showing the FlexGrid detail control void IC1FlexGridRowDetailSetup(C1FlexGrid parentGrid int rowIndex) var bs = new BindingSource(parentGridDataSource parentGridDataMember) bsPosition = parentGridRows[rowIndex]DataIndex DataField = Notes DataSource = bs

C

FlexGrid for WinForms

92 Copyright copy GrapeCity Inc All rights reserved

Used to update size of the FlexGrid detail control void IC1FlexGridRowDetailUpdateSize(C1FlexGrid parentGrid int rowIndex Size proposedSize) var srSz = parentGridScrollableRectangleSize var sz = TextRendererMeasureText(Text Font srSz TextFormatFlagsWordBreak) szWidth = MathMax(szWidth srSzWidth) Size = sz

Private Sub CustomSample_Load(ByVal sender As Object ByVal e As EventArgs) flexGridDataSource = DemoDataSource(Employees) flexGridRowDetailProvider = Function(g r) New CustomRowDetail() flexGridRowDetailsVisibilityMode = RowDetailsVisibilityModeVisibleWhenSelected flexGridCols(Notes)Visible = False End Sub

Custom row detail class which shows label with notes about employee Public Class CustomRowDetail Inherits C1Label Implements IC1FlexGridRowDetail

Used to setup control before showing the FlexGrid detail control Private Sub Setup(ByVal parentGrid As C1FlexGrid ByVal rowIndex As Integer) Dim bs = New BindingSource(parentGridDataSource parentGridDataMember) bsPosition = parentGridRows(rowIndex)DataIndex DataField = Notes DataSource = bs End Sub

Used to update size of the FlexGrid detail control Private Sub UpdateSize(ByVal parentGrid As C1FlexGrid ByVal rowIndex As Integer ByVal proposedSize As Size) Dim srSz = parentGridScrollableRectangleSize Dim sz = TextRendererMeasureText(Text Font srSz TextFormatFlagsWordBreak) szWidth = MathMax(szWidth srSzWidth) Size = sz End Sub End Class

VBNET

サイズ変更

Set Row HeightFlexGrid provides DefaultSize property of the RowCollection class to set row height across the grid You can alsospecify the height of a particular row by setting Height property of the Row class Default value of the Heightproperty is -1 which indicates that the row is taking height specified by the DefaultSize property

Use the code below to set the default height of a row of the WinForms FlexGrid

Set the default size of all rowsc1FlexGrid1RowsDefaultSize = 50

C

FlexGrid for WinForms

93 Copyright copy GrapeCity Inc All rights reserved

Auto-adjust Row HeightTo adjust the row height according to text length and word wrapping options FlexGrid provides the AutoSizeRow()and AutoSizeRows() methods While AutoSizeRow() method automatically adjusts height of the specified row theAutoSizeRows() method is used for cell ranges

Following code shows how you can auto adjust the row height according to the text length in the WinForms FlexGrid

Set MinMax Row HeightFlexGrid allows you to set bounds to the row height by using the MinSize and MaxSize propertiesof the RowCollection class This feature is especially useful in scenarios such as when AllowResizing property is set totrue or while using the AutoSizeRow() or AutoSizeRows() method

Specify the bounds of row height in the WinForms FlexGrid using the code below

Set the height of a particular rowc1FlexGrid1Rows[1]Height = 55

Set the default size of all rowsc1FlexGrid1RowsDefaultSize = 50

Set the height of a particular rowc1FlexGrid1Rows(1)Height = 55

VBNET

Adjust the height of fourth row automaticallyc1FlexGrid1AutoSizeRow(4) Adjust the height of all rows automatically c1FlexGrid1AutoSizeRows() Adjust the height of cell range automaticallyc1FlexGrid1AutoSizeRows(2 4 5 6 10 C1WinC1FlexGridAutoSizeFlagsNone)

C

Adjust the height of fourth row automatically c1FlexGrid1AutoSizeRow(4)

Adjust the height of all rows automatically c1FlexGrid1AutoSizeRows()

Adjust the height of cell range automatically c1FlexGrid1AutoSizeRows(2 4 5 6 10 C1WinC1FlexGridAutoSizeFlagsNone)

VBNET

Set the maximum height of rowc1FlexGrid1RowsMaxSize = 50 Set the minimum height of rowc1FlexGrid1RowsMinSize = 20

C

FlexGrid for WinForms

94 Copyright copy GrapeCity Inc All rights reserved

Set the maximum height of rowc1FlexGrid1RowsMaxSize = 50

Set the minimum height of row c1FlexGrid1RowsMinSize = 20

VBNET

FlexGrid for WinForms

95 Copyright copy GrapeCity Inc All rights reserved

セル

Cell is the smallest unit of a grid Although in most common scenarios we prefer working on row or column levelthere are some operations which are required to be carried out on the cell level Getting setting or removing data arefew to name

Topic Snapshot Content

Basic Operations Discusses how to perform basic operations related to a cell

Set Value in CellSet Values in Cell RangeClear Value from Cell (Range)Set Image in CellDisplay Tooltip in CellRetrieve Cell Values

Cell Format Discusses how to format cell or cell data in various scenarios

Cell ContentCell AppearanceConditional FormattingOwner Drawn Cell

基本操作

Set Value in CellFlexGrid provides two ways to set values in cell You can either use Item property (indexer) or SetData method of the C1FlexGrid class

Use the code below to set a value in the WinForms FlexGrid cell

Set Values in Cell RangeTo set values in a cell range you can either use Data property of the CellRange class or SetData method of the C1FlexGrid class

Following code shows how to set values in a cell range in WinForms FlexGrid

インデックスを使用してデータを設定しますc1FlexGrid1[2 3] = 2nd col 3rd row SetDataメソッドを使用してデータを設定しますc1FlexGrid1SetData(2 4 2nd col 4th row)

C

インデックスを使用してデータを設定します c1FlexGrid1(2 3) = 2nd col 3rd row

SetDataメソッドを使用してデータを設定します c1FlexGrid1SetData(2 4 2nd col 4th row)

VBNET

セル範囲を取得しますC1WinC1FlexGridCellRange cr = c1FlexGrid1GetCellRange(2 3 5 6) 方法1dataプロパティを使用してセル範囲にデータを設定しますcrData = Cell Range

C

FlexGrid for WinForms

96 Copyright copy GrapeCity Inc All rights reserved

Clear Value from Cell (Range)There are two ways by which contents of cell or cell range can be cleared You can either chose to do it programmatically by setting thecontent of cell to an empty string using indexer or SetData method Or you can set the AutoClipboard property to true so that user candelete the values by pressing the Delete key

Below code demonstrates how to allow keyboard operations so that user can clear values from WinForms FlexGrid cells

Set Image in CellTo set image in a cell you can use SetCellImage method of the C1FlexGrid class You can also set an image in a cell range by using Imageproperty of the CellRange class By default text and image both are displayed in the cell However you can choose to display only image bysetting the ImageAndText property to false

Use the code below to set image in a WinForms FlexGrid cell

方法2SetDataメソッドを使用してセル範囲にデータを設定します c1FlexGrid1SetData(cr Cell Range)

セル範囲を取得します Dim cr As C1WinC1FlexGridCellRange = c1FlexGrid1GetCellRange(2 3 5 6)

方法1dataプロパティを使用してセル範囲にデータを設定します crData = Cell Range

方法2SetDataメソッドを使用してセル範囲にデータを設定します c1FlexGrid1SetData(cr Cell Range)

VBNET

ユーザーがDeleteキーを押してセルの内容をクリアするなどのキーボード操作を実行できるようにしますc1FlexGrid1AutoClipboard = true

コードを介して特定のセルのデータをクリアしますc1FlexGrid1SetData(3 4 )

C

ユーザーがDeleteキーを押してセルの内容をクリアするなどのキーボード操作を実行できるようにします c1FlexGrid1AutoClipboard = True

コードを介して特定のセルのデータをクリアします c1FlexGrid1SetData(3 4 )

VBNET

セル(36)に画像を設定しますc1FlexGrid1SetCellImage(3 6 ImageFromFile(masterpng))

C

FlexGrid for WinForms

97 Copyright copy GrapeCity Inc All rights reserved

Display Tooltip in CellTo display partially hidden content of cells as tooltip FlexGrid provides ShowCellLabels property of the C1FlexGrid class You can also showadditional information in the form of a tooltip by using the MouseEnterCell and MouseLeaveCell event

Below code shows how to display a tooltip on a WinForms FlexGrid cell

セル範囲(126)から(146)に画像を設定しますC1WinC1FlexGridCellRange crcr = c1FlexGrid1GetCellRange(12 6 14 6)crImage = ImageFromFile(amexjpg)

テキストなしで画像を表示しますc1FlexGrid1Rows[3]ImageAndText = false

セル(36)に画像を設定します c1FlexGrid1SetCellImage(3 6 ImageFromFile(masterpng))

セル範囲(126)から(146)に画像を設定します Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1GetCellRange(12 6 14 6) crImage = ImageFromFile(amexjpg)

テキストなしで画像を表示します c1FlexGrid1Rows(3)ImageAndText = False

VBNET

private void Form1_Load(object sender EventArgs e) このコードはデータを「c1NWindDataSetEmployees」テーブルにロードします 必要に応じて移動または削除できます thisemployeesTableAdapterFill(thisc1NWindDataSetEmployees) for (int i = c1FlexGrid1RowsFixed i lt c1FlexGrid1RowsCount i++) c1FlexGrid1Rows[i]UserData = Employee + c1FlexGrid1[i 2] + + c1FlexGrid1[i 3] private void C1FlexGrid1_MouseEnterCell(object sender C1WinC1FlexGridRowColEventArgs e) if (eRow gt= c1FlexGrid1RowsFixed) string tip tip = c1FlexGrid1Rows[eRow]UserDataToString() ツールチップを表示します toolTip1SetToolTip(c1FlexGrid1 tip)

private void C1FlexGrid1_MouseLeaveCell(object sender C1WinC1FlexGridRowColEventArgs e) ツールチップを非表示にします toolTip1SetToolTip(c1FlexGrid1 )

C

FlexGrid for WinForms

98 Copyright copy GrapeCity Inc All rights reserved

Retrieve Cell ValuesThere are numerous ways using which you can fetch the value of FlexGrid cells depending on your requirement Below tablediscusses several scenarios such as fetching the raw data or formatted data from a single cell or a cell range

Requirement MethodProperty Usage

Get the raw data Item property (indexer) ExampleCode

var data = c1FlexGrid1[1 1] SystemDiagnosticsDebugWriteLine($Cell data data)

GetData() method ExampleCode

var data1 = c1FlexGrid1GetData(1 1) SystemDiagnosticsDebugWriteLine($Cell data data1)

Get the formatted data GetDataDisplay() method ExampleCode

var data2 = c1FlexGrid1GetDataDisplay(1 1) SystemDiagnosticsDebugWriteLine($Display data data2)

Get values of a cell range Clip property ExampleCode

var data3 = c1FlexGrid1Clip SystemDiagnosticsDebugWriteLine($Clip data data3)

GetCellRange method ExampleCode

var data4 = c1FlexGrid1GetCellRange(1 1) SystemDiagnosticsDebugWriteLine($Cell Range data data4Clip)

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) このコードはデータを「c1NWindDataSetEmployees」テーブルにロードします 必要に応じて移動または削除できます MeemployeesTableAdapterFill(Mec1NWindDataSetEmployees)

For i As Integer = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 c1FlexGrid1Rows(i)UserData = Employee amp c1FlexGrid1(i 2) amp + c1FlexGrid1(i 3) Next End Sub

Private Sub C1FlexGrid1_MouseEnterCell(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) If eRow gt= c1FlexGrid1RowsFixed Then Dim tip As String tip = c1FlexGrid1Rows(eRow)UserDataToString() ツールチップを表示します toolTip1SetToolTip(c1FlexGrid1 tip) End If End Sub

Private Sub C1FlexGrid1_MouseLeaveCell(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) ツールチップを非表示にします toolTip1SetToolTip(c1FlexGrid1 ) End Sub

VBNET

FlexGrid for WinForms

99 Copyright copy GrapeCity Inc All rights reserved

セルの書式設定

Cell ContentTo control how content of the cells is formatted and displayed set the Format property of Row or Column object toformat string similar to the ones that are used with StringFormat property in the NET framework For instance thesample code below formats the third column as Date and fourth column as Currency

FlexGrid also provides design time option to set the Format property through the Format String dialog You canaccess the Format String dialog by clicking Ellipsis button against the Format String field in Column Tasks menu Oryou can also use the Format property in C1FlexGrid Column Editor

短い日付形式を設定しますc1FlexGrid1Cols[3]Format = D 通貨形式を設定しますc1FlexGrid1Cols[4]Format = c

C

短い日付形式を設定しますc1FlexGrid1Cols(3)Format = D

通貨形式を設定しますc1FlexGrid1Cols(4)Format = c

VBNET

FlexGrid for WinForms

100 Copyright copy GrapeCity Inc All rights reserved

Note that Format String dialog is specific to column and changes the Format property of the selected column only

Cell AppearanceFlexGrid provides CellStyle objects to handle the appearance aspects of cells such as alignment font colors bordersand so on The grid has Styles property that holds the collection of styles used to format the grid This collection hassome built-in members that define the appearance of grid elements such as fixed and scrollable cells selection focuscell and so on You can change these styles to modify the appearance of grid

Although changing the built-in styles is the simplest way to change appearance of the grid you can also create yourown custom styles and assign them to cells rows or columns

Use the code below to change appearance of the WinForms FlexGrid cells

組み込みのスタイルをカスタマイズしますCellStyle cs = c1FlexGrid1StylesFocus

C

FlexGrid for WinForms

101 Copyright copy GrapeCity Inc All rights reserved

Conditional FormattingTo format a cell according to its content you need to create a new style and apply it to the cells satisfying a particularcondition using SetCellStyle() method For instance to highlight the values greater than a specified value you canformat the cells containing them using different style

Following code shows how to apply conditional formatting on WinForms FlexGrid cells

csFont = new Font(c1FlexGrid1Font FontStyleBold)csForeColor = ColorGreencsBackColor = ColorRed

カスタムスタイルを作成します CellStyle cs1 = c1FlexGrid1StylesAdd(NewStyle)cs1BackColor = ColorAquacs1ForeColor = ColorBlue

カスタムスタイルを割り当てますc1FlexGrid1Cols[3]Style = cs1

Dim cs As CellStyle = c1FlexGrid1StylesFocus csFont = New Font(c1FlexGrid1Font FontStyleBold) csForeColor = ColorGreen csBackColor = ColorRed

Dim cs1 As CellStyle = c1FlexGrid1StylesAdd(NewStyle) cs1BackColor = ColorAqua cs1ForeColor = ColorBlue

c1FlexGrid1Cols(3)Style = cs1

VBNET

CellStyle cs 大きな値のカスタムスタイルを作成しますcs = c1FlexGrid1StylesAdd(LargeValue)csFont = new Font(Font FontStyleItalic)

C

FlexGrid for WinForms

102 Copyright copy GrapeCity Inc All rights reserved

Owner Drawn CellThe above sections explain how you can customize FlexGrid cells to change the appearance of grid using CellStyleobjects However for further customization of grid cells such as rendering gradient background custom graphics etcyou can use DrawMode property and OwnerDrawCell event of the C1FlexGrid class

The DrawMode property determines whether or not the OwnerDrawCell event is fired The event allows you tooverride every visual aspect of the cell You can change the text and image to be displayed in the cell by setting theeText and eImage parameters in the event handler You can also change the style that is used to display the cell bysetting the eStyle property

Note that you should not modify properties of the Style parameter as it might affect other cells Instead assign a newCellStyle object to the Style parameter For example instead of setting eStyleForeColor = ColorRed assign a wholenew style to the parameter using eStyle = c1FlexGrid1Styles[RedStyle]

You can also use your own drawing code to draw into the cell and even combine your custom code with calls to theeDrawCell method For example you can paint the cell background using GDI calls and then call eDrawCell todisplay the cell borders and content

In the example below WinForms FlexGrid uses a gradient brush to paint the background of the selected cell rangeFirst the sample code sets the DrawMode property to OwnerDraw and then declares a LinearGradientBrushobject

csBackColor = ColorGold

for (int row = 1 row lt c1FlexGrid1RowsCount row++)if (ConvertToDouble(c1FlexGrid1[row 4]) gt 80000)c1FlexGrid1SetCellStyle(row 4 cs)

Dim cs As CellStyle

cs = c1FlexGrid1StylesAdd(LargeValue) csFont = New Font(Font FontStyleItalic) csBackColor = ColorGold

For row As Integer = 1 To c1FlexGrid1RowsCount - 1

If ConvertToDouble(c1FlexGrid1(row 4)) gt 80000 Then c1FlexGrid1SetCellStyle(row 4 cs) End If Next

VBNET

SystemDrawingDrawing2DLinearGradientBrush m_GradientBrushprivate void Form1_Load(object sender EventArgs e)

C

FlexGrid for WinForms

103 Copyright copy GrapeCity Inc All rights reserved

所有者描画セルで使用するブラシ m_GradientBrush = new SystemDrawingDrawing2DLinearGradientBrush(ClientRectangle ColorSteelBlue ColorWhite 45)

グラデーションを追加するにはowner-drawを使用します c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw

private void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) グラデーションブラシを使用して選択したセルの背景を描画します if (c1FlexGrid1SelectionContains(eRow eCol)) 背景を描きますeGraphicsFillRectangle(m_GradientBrush eBounds)

グリッドにコンテンツを描画させますeDrawCell(C1WinC1FlexGridDrawCellFlagsContent)

このセルの描画は完了ですeHandled = true

Private m_GradientBrush As DrawingDrawing2DLinearGradientBrush

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) 所有者描画セルで使用するブラシ m_GradientBrush = New DrawingDrawing2DLinearGradientBrush(ClientRectangle ColorSteelBlue ColorWhite 45)

グラデーションを追加するにはowner-drawを使用します c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDrawEnd Sub

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) グラデーションブラシを使用して選択したセルの背景を描画します If c1FlexGrid1SelectionContains(eRow eCol) Then 背景を描きます eGraphicsFillRectangle(m_GradientBrush eBounds)

グリッドにコンテンツを描画させます eDrawCell(C1WinC1FlexGridDrawCellFlagsContent)

このセルの描画は完了です eHandled = True End IfEnd SubEnd IfEnd Sub

VBNET

FlexGrid for WinForms

104 Copyright copy GrapeCity Inc All rights reserved

グリッド

This section discusses about various operations that can be performed on the grid

Topic Snapshot Content

Basic Operations Discusses about basic operations that can be performed on the grid

Transpose Data in GridDisplay Context Menu

Keyboard Navigation Discusses about supperted keys and their operations in

Non-edit ModeEdit Mode

Improve Performance Provides tips and tricks to get best out of your grid by improving its performance

Use Data VirtualizationUse BeginUpdate and EndUpdate MethodsKeep AutoResize Property to False (default)Assign Styles DynamicallyAvoid Modifying Styles in the OwnerDrawCell EventShow Ellipses in a Single ColumnShow Multi-line Text in a CellRetrieve Data Sorting When Bound to a Data TableSpecify Character Limit for Column

基本操作

This topic discusses about various operations that require handling at the grid level

Transpose Data in GridTransposing data refers to swapping column data and row data In WinForms FlexGrid this can be achieved usingTranspose() method of the C1FlexGrid class as shown in the code below

Note that data can be transposed only in the case of unbound grid Also if grid has sorting applied on a column theTranspose() method removes sorting before transposing the data

Display Context MenuContext menus can be helpful to user as they provide shortcuts for actions that are frequently used In FlexGrid therecan be two scenarios to display a context menu

Display context menu in non-edit modeDisplay context menu in edit mode

Display Context Menu in Non-edit Mode

To display context menu when grid is in non-edit mode you need to create an instance of ContextMenuStrip controladd the menu items and assign the instance to ContextMenuStrip property of the Control class

c1FlexGrid1Transpose()

C

C1FlexGrid1Transpose()

VBNET

FlexGrid for WinForms

105 Copyright copy GrapeCity Inc All rights reserved

Refer to the code below to see how to display a context menu in WinForms FlexGrid in non-edit mode

Display Context Menu in Edit Mode

To display context menu in edit mode you need to display the context menu on editor by using StartEdit event ofthe C1FlexGrid class In the StartEdit event instantiate the editor and the ContextMenuStrip add menu items andthen assign it to ContextMenuStrip property of the editor

Create an instance of ContextMenuStrip controlContextMenuStrip cm = new ContextMenuStrip()

Add menu items to the context menucmItemsAdd(Add Above)cmItemsAdd(Add Below)cmItemsAdd(Add Left)cmItemsAdd(Add Right)

Assign the instance to ContextMenuStrip property c1FlexGrid1ContextMenuStrip = cm

C

Create an instance of ContextMenuStrip controlDim cm As ContextMenuStrip = New ContextMenuStrip()

Add menu items to the context menucmItemsAdd(Add Above)cmItemsAdd(Add Below)cmItemsAdd(Add Left)cmItemsAdd(Add Right)

Assign the instance to ContextMenuStrip property c1FlexGrid1ContextMenuStrip = cm

VBNET

FlexGrid for WinForms

106 Copyright copy GrapeCity Inc All rights reserved

Use the code below to display context menu in WinForms FlexGrid in edit mode

private void C1FlexGrid1_StartEdit(object sender C1WinC1FlexGridRowColEventArgs e) TextBox tb = (TextBox)c1FlexGrid1Editor

Create context menu ContextMenuStrip cm2 = new ContextMenuStrip() cm2ItemsAdd(Cut) cm2ItemsAdd(Copy) cm2ItemsAdd(Paste) Set context menu tbContextMenuStrip = cm2

C

Private Sub C1FlexGrid1_StartEdit(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) Dim tb As TextBox = CType(c1FlexGrid1Editor TextBox)

Create context menu Dim cm2 As ContextMenuStrip = New ContextMenuStrip() cm2ItemsAdd(Cut) cm2ItemsAdd(Copy) cm2ItemsAdd(Paste)

Set context menu tbContextMenuStrip = cm2End Sub

VBNET

キーボードによる移動

With built-in keyboard support FlexGrid lets you perform the basic navigation operations such as moving the focusentering or exiting the edit mode etc with a perfect ease just by using keys Below tables list the supported keys andtheir corresponding operations in non-edit as well as in edit mode of the cell

Non-edit Mode

Key Sequence Key Action

FlexGrid for WinForms

107 Copyright copy GrapeCity Inc All rights reserved

uarr

larr rarr

darr

Moves focus to the adjacent cell in direction indicated by the arrow key

Shift + ArrowSelects adjacent cells in direction indicated by the arrow key

F2Grid is editable Toggles the cell to edit mode If a value exists in the cell it getsselected Else the grid simply displays a cursor in the cell

Grid is not editable No action

EnterGrid is editable Toggles the cell to edit mode If a value exists in the cell it getsselected Else the grid simply displays a cursor in the cell

Grid is not editable Moves the selection down to the next visible row

You can also change default behavior of Enter key press by using the KeyActionEnterproperty

HomeMoves focus to the first cell of row

EndMoves focus to the last cell of row

Ctrl + HomeMoves focus to the first cell of column

Ctrl + EndMoves focus to the last cell of column

TabBy default grid ignores the Tab key press and lets it cycle through the controls on theform However you can define the action to be performed on Tab key press by usingthe KeyActionTab property

Ctrl + C

Ctrl + X

Ctrl + V

Performs usual clipboard operations that is copy(Ctrl+C) cut(Ctrl+X) and paste(Ctrl+V)when AutoClipboard property is set to true (Default value is false)

Edit Mode

Key Sequence Key Action

uarr

darr

Moves focus to the adjacent cell in the direction indicated by arrow key

FlexGrid for WinForms

108 Copyright copy GrapeCity Inc All rights reserved

larr rarrMoves cursor by one character in the direction indicated by arrow key When cursor is onthe first or last character moves focus to the adjacent cell in the direction of arrow key

EnterToggles the cell to non-edit mode and moves focus to the cell below You can also changedefault behavior of Enter key press by using the KeyActionEnter property

EscCancels editing and exits the edit mode

TabBy default grid ignores the Tab key press and lets it cycle through the controls on theform However you can define the action to be performed on Tab key press by usingthe KeyActionTab property

パフォーマンスの向上

Use Data VirtualizationTo efficiently render large data sets FlexGrid supports data vitualization in which data is fetched in pages as the user scrolls down The gridknows the total number of rows but only loads and displays those that are visible to the user For instance you can use C1DataCollectionpackage to implement virtualizable data source Create a class inherited from the C1VirtualDataCollection and implement GetPageAsyncmethod which returns one page of data from data source you have assigned The following GIF shows how FlexGrid appears in the virtualscrolling mode

public class VirtualModeCollectionView C1VirtualDataCollectionltCustomergt public int TotalCount get set = 1_000 protected override async TaskltTupleltint IReadOnlyListltCustomergtgtgt GetPageAsync(int pageIndex int startingIndex int count IReadOnlyListltSortDescriptiongt sortDescriptions = null FilterExpression filterExpression = null CancellationToken cancellationToken = default(CancellationToken)) await TaskDelay(500 cancellationToken)Simulates network traffic return new Tupleltint IReadOnlyListltCustomergtgt(TotalCount EnumerableRange(startingIndex count)Select(i =gt new Customer(i))ToList())

C

Public Class VirtualModeCollectionView

VBNET

FlexGrid for WinForms

109 Copyright copy GrapeCity Inc All rights reserved

Use BeginUpdate and EndUpdate MethodsThe BeginUpdate and EndUpdate methods are used to optimize the performance of the grid Call BeginUpdate before making extensivechanges and call EndUpdate when done to suspend repainting This reduces flicker and increases performance This optimization is especiallyeffective when adding large number of rows to the grid because it needs to recalculate ranges and update scrollbars each time a row is added

The code below shows how to add a large number of rows to the WinForms FlexGrid efficiently Note how the EndUpdate method is calledinside a finally block to ensure repainting is properly restored

Keep AutoResize Property to False (default)In case of bound grid if AutoResize property is set to true the control automatically resizes its columns to fit the widest entry every time newdata is read from the data source If the data source contains a large number of rows and columns the automatic resizing may take a relativelylong time In such cases you should consider setting AutoResize to false and setting the column widths directly in code

Assign Styles DynamicallyFlexGrid allows you to create cell styles and assign them to rows columns and arbitrary cell ranges You can use this feature to format the gridcells conditionally Usually you do this by using the SetCellStyle() method However in that case you have to update the style whenever the cellvalue changes Also if the grid is bound to a data source styles are lost whenever data source is reset after operations such as sorting andfiltering A better alternative in these cases is to use the OwnerDraw feature and select styles dynamically based on the cell values For example

Inherits C1VirtualDataCollection(Of Customer)

Public Property TotalCount As Integer = 1_000

Protected Overrides Async Function GetPageAsync(ByVal pageIndex As Integer ByVal startingIndex As Integer ByVal count As Integer ByVal Optional sortDescriptions As IReadOnlyList(Of SortDescription) = Nothing ByVal Optional filterExpression As FilterExpression = Nothing ByVal Optional cancellationToken As CancellationToken = DirectCast(Nothing CancellationToken)) As Task(Of Tuple(Of Integer IReadOnlyList(Of Customer))) Await TaskDelay(500 cancellationToken) Simulates network traffic Return New Tuple(Of Integer IReadOnlyList(Of Customer))(TotalCount EnumerableRange(CInt(startingIndex) CInt(count))[Select](Function(i) New Customer(i))ToList()) End FunctionEnd Class

void UpdateGrid(C1FlexGrid c1FlexGrid1) try c1FlexGrid1BeginUpdate() suspend painting to avoid flicker c1FlexGrid1RowsCount = 1 for (int i = 1 i lt 10000 i++) c1FlexGrid1AddItem(Row + iToString()) finally c1FlexGrid1EndUpdate() always restore painting

C

Private Sub UpdateGrid(ByVal c1FlexGrid1 As C1FlexGrid) Try c1FlexGrid1BeginUpdate() suspend painting to avoid flicker c1FlexGrid1RowsCount = 1

For i As Integer = 1 To 10000 - 1 c1FlexGrid1AddItem(Row amp iToString()) Next

Finally c1FlexGrid1EndUpdate() always restore painting End TryEnd Sub

VBNET

FlexGrid for WinForms

110 Copyright copy GrapeCity Inc All rights reserved

the sample code shows how to display negative values in red color and values above 1000 in green color in the WinForms FlexGrid

Avoid Modifying Styles in the OwnerDrawCell EventAnother way to improve performance is not to modify the CellStyle object passed as a parameter in the OwnerDrawCell event Instead assign anew value to the eStyle parameter This is important because the CellStyle passed to the event handler is often used by other cells Forexample you could unintentionally change a normal style of the WinForms FlexGrid which would affect other similar cells as well in the grid

private void Form1_Load(object sender EventArgs e) Fill a column with random values c1FlexGrid1Cols[1]DataType = typeof(int) Random rnd = new Random() for (int r = 1 r lt c1FlexGrid1RowsCount r++) c1FlexGrid1[r 1] = rndNext(-10000 10000) Create style used to show negative values c1FlexGrid1StylesAdd(Red)ForeColor = ColorRed Enable OwnerDraw by setting the DrawMode property c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw c1FlexGrid1OwnerDrawCell += new C1WinC1FlexGridOwnerDrawCellEventHandler(C1FlexGrid1_OwnerDrawCell)

private void C1FlexGrid1_OwnerDrawCell(object sender OwnerDrawCellEventArgs e) if(eMeasuring) Check that the row and column contain integer data if (eRow gt 0 ampamp c1FlexGrid1Cols[eCol]DataType == typeof(int)) Apply the style Red eStyle = c1FlexGrid1Styles[Red]

C

Private Sub Form1_Load(ByVal sender As Object ByVal e As EventArgs) Fill a column with random values c1FlexGrid1Cols(1)DataType = GetType(Integer) Dim rnd As Random = New Random()

For r As Integer = 1 To c1FlexGrid1RowsCount - 1 c1FlexGrid1(r 1) = rnd[Next](-10000 10000) Next

Create style used to show negative values c1FlexGrid1StylesAdd(Red)ForeColor = ColorRed

Enable OwnerDraw by setting the DrawMode property c1FlexGrid1DrawMode = C1WinC1FlexGridDrawModeEnumOwnerDraw c1FlexGrid1OwnerDrawCell += New C1WinC1FlexGridOwnerDrawCellEventHandler(AddressOf C1FlexGrid1_OwnerDrawCell) End Sub

Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As OwnerDrawCellEventArgs) If Not eMeasuring Then

Check that the row and column contain integer data If eRow gt 0 AndAlso c1FlexGrid1Cols(eCol)DataType Is GetType(Integer) Then Apply the style Red eStyle = c1FlexGrid1Styles(Red) End If End If End Sub

VBNET

FlexGrid for WinForms

111 Copyright copy GrapeCity Inc All rights reserved

Show Ellipses in a Single ColumnThe Trimming property should be used to show ellipses in a single column of the grid To determine how long strings are trimmed to fit the cellthe Trimming property can be set to either None Character Word EllipsisCharacter EllipsisWord or EllipsisPath For more information ontrimming see Display Trimmed Text

The following code sets the Trimming property to show ellipses at the end of the second WinForms Flexgrid column with the text trimmed tothe nearest character

Show Multi-line Text in a CellWhen showing multiple lines of text in a cell use the WordWrap and Height properties The WordWrap property determines whether the gridshould automatically break long strings that contain spaces and display them in multiple lines Strings that contain hard line breaks (vbCrLf ornr) are always displayed in multiple lines Multiple line text can be displayed in both fixed and scrollable cells For more information on wordwrapping see Wrap Text

Refer to code below to see how a multi-line text should be effectively displayed in the WinForms FlexGrid

CORRECT APPROACHprivate void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) Select style to use when painting this cell eStyle = MyStyleSelector(eRow eCol) WRONG APPROACHprivate void C1FlexGrid1_OwnerDrawCell(object sender C1WinC1FlexGridOwnerDrawCellEventArgs e) Select style to use when painting this cell This is wrong because changing any CellStyle objects invalidates the grid which would cause this event handler to be called over and over again eStyleColor = MyColorSelector(eRow eCol)

C

CORRECT APPROACHPrivate Sub C1FlexGrid1_OwnerDrawCellMethod(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) Select style to use when painting this celleStyle = MyStyleSelector(eRow eCol)End Sub

WRONG APPROACHPrivate Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object ByVal e As C1WinC1FlexGridOwnerDrawCellEventArgs) Select style to use when painting this cell This is wrong because changing any CellStyle objects invalidates the grid which would cause this event handler to be called over and over againeStyleColor = MyColorSelector(eRow eCol)End Sub

VBNET

c1FlexGrid1Cols[1]StyleNewTrimming =StringTrimmingEllipsisCharacter

C

c1FlexGrid1Cols(1)StyleNewTrimming = StringTrimmingEllipsisCharacter

VBNET

Set the WordWrap property

C

FlexGrid for WinForms

112 Copyright copy GrapeCity Inc All rights reserved

Retrieve Data Sorting When Bound to a Data TableTo maintain the way the grid is sorted when data is refreshed you can use the default views Sort property and a sort expression The Sortproperty uses a string containing the column name followed by ASC(default) or DESC to sort the column in ascending or descending orderrespectively Multiple columns can be sorted by specifying each column name separated by a comma A sort expression can include names ofgrid columns or a calculation Setting the sort expression at run time immediately reflects the changes in the data view

Below code shows how to use the sort expression with Sort property in the WinForms FlexGrid

Specify Character Limit for ColumnTo set the maximum number of characters a user can enter for any given column use the SetupEditor event You must declare an externaleditor such as C1TextBox in the StartEdit event of the C1FlexGrid class Then in the SetupEditor event you can set the maximum number ofcharacters that are allowed in a column cell

Use the code below to set the character limit for a WinForms FlexGrid column

c1FlexGrid1Styles[Normal]WordWrap = true Set the row heightc1FlexGrid1Rows[1]Height = 2 fgRowsDefaultSize Add text to the cellc1FlexGrid1[1 2] = This is the first line rn This is the second line

Set the WordWrap property c1FlexGrid1Styles(Normal)WordWrap = True

Set the row height c1FlexGrid1Rows(1)Height = 2 fgRowsDefaultSize

Add text to the cell c1FlexGrid1(1 2) = This is the first line amp vbCrLf amp This is the second line

VBNET

Sort the data by the UnitsInStock column then by the ProductID column thisproductsBindingSourceSort = UnitsInStock ASC ProductID ASC

C

Sort the data by the UnitsInStock column then by the ProductID columnMeproductsBindingSourceSort = UnitsInStock ASC ProductID ASC

VBNET

private void C1FlexGrid1_StartEdit(object sender C1WinC1FlexGridRowColEventArgs e) c1FlexGrid1Editor = c1TextBox private void C1FlexGrid1_SetupEditor(object sender RowColEventArgs e) Set the 3rd column to allow 20 characters and the rest only 10 if (eCol == 2) c1TextBoxMaxLength = 20 else c1TextBoxMaxLength = 10

C

Private Sub C1FlexGrid1_StartEdit(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs)

VBNET

FlexGrid for WinForms

113 Copyright copy GrapeCity Inc All rights reserved

c1FlexGrid1Editor = c1TextBox End Sub

Private Sub C1FlexGrid1_SetupEditor(ByVal sender As Object ByVal e As RowColEventArgs)

Set the 3rd column to allow 20 characters and the rest only 10 If eCol = 2 Then c1TextBoxMaxLength = 20 Else c1TextBoxMaxLength = 10 End If End Sub

FlexGrid for WinForms

114 Copyright copy GrapeCity Inc All rights reserved

スクロールバー

Display or Hide the Scroll BarIn FlexGrid you can manage the display of scroll bars using the ScrollBars property which lets you choose whether todisplay horizontal vertical both or no scroll bar through the ScrollBars enumeration

Below code shows how to always display both the scrollbars in the WinForms FlexGrid

Set Scroll PositionTo scroll FlexGrid to a specified location you can set TopRow and LeftCol property of the C1FlexGrid class TopRowproperty scrolls the grid vertically while LeftCol sets the horizontal scroll position of the grid The maximum value ofthese properties depends on the total number of rows or columns and the count that can be displayed in the gridThis feature is really useful in scenarios like synchronized scrolling of multiple grids

Use the code below to set scroll position of the WinForms FlexGrid

水平および垂直スクロールバーを表示しますc1FlexGrid1ScrollBars = ScrollBarsBoth 常にスクロールバーを表示しますc1FlexGrid1ScrollOptions = ScrollFlagsAlwaysVisible

C

水平および垂直スクロールバーを表示しますc1FlexGrid1ScrollBars = ScrollBarsBoth

常にスクロールバーを表示しますc1FlexGrid1ScrollOptions = ScrollFlagsAlwaysVisible

VBNET

スクロール位置を設定しますc1FlexGrid1TopRow = 3c1FlexGrid1LeftCol = 2

C

スクロール位置を設定しますc1FlexGrid1TopRow = 3

VBNET

FlexGrid for WinForms

115 Copyright copy GrapeCity Inc All rights reserved

Other Scroll OptionsFlexGrid also provides more options to handle various aspects of displaying a scroll bar through ScrollOptionsproperty This property accepts the values from ScrollFlags enumeration which lets you customize the scroll baroptions as described in the table below

Value Scroll Operation

AlwaysVisible Displays the scroll bar even when they are disable or there is no scrollable area

DelayedScroll Scrolls the content only after user has released the scrollbar thumb

KeepMergedRangePosition Can not set scroll position to the first cell of a merged range

None Uses the default scrolling behavior

ScrollByRowColumn Scrolls the content in units of rows or columns instead of scrolling by pixels

ShowScrollTips Fires the ShowScrollTip event and displays a tooltip next to the vertical scrollbarwhile scrolling vertically

Following code shows how to scroll the WinForms FlexGrid by rows or columns only

c1FlexGrid1LeftCol = 2

行や列単位でスクロールします c1FlexGrid1ScrollOptions = ScrollFlagsScrollByRowColumn

C

行や列単位でスクロールしますc1FlexGrid1ScrollOptions = ScrollFlagsScrollByRowColumn

VBNET

FlexGrid for WinForms

116 Copyright copy GrapeCity Inc All rights reserved

選択

Selection ModesFlexGrid by default allows to select a continuous batch of cells using mouse or keyboard and entire row or column by clicking thecorresponding header However the default behavior can be changed to allow selection in units of cell row column etc byusing SelectionMode property of the C1FlexGrid class The property accepts values from the SelectionModeEnumenumeration Below table gives a quick snapshot of how selection looks like in each of these modes

Value Description Snapshot

Default Allows selection of continuous batch of cells using mouse orkeyboard Also lets the user select entire row or column onclicking the respective header

Cell Allows selection of single cell at a time

CellRange Allows selection of continuous batch of cells using mouse orkeyboard

Column Allows selection of single column at a time

ColumnRange Allows selection of multiple contiguous columns at a time

ListBox Allows selection of multiple non-contiguous rows using the Ctrlkey

FlexGrid for WinForms

117 Copyright copy GrapeCity Inc All rights reserved

Row Allows selection of single row at a time

RowRange Allows selection of multiple contiguous rows at a time

Set SelectionFlexGrid provides various ways to set the selection through code You can use any of these methods depending on the requirementsuch as selecting the single cell cell range or rows

Selection MethodProperty Sample code

Single cell Set the Row and Col property Default value of both of theseproperties is 1 Hence by default selection is set to the firstscrollable cell on top left of the grid

Example Title

c1FlexGrid1Row = 2c1FlexGrid1Col = 1

Call the Select(rowIndex colIndex) method to select a singlecell

Example Title

c1FlexGrid1Select(2 1)

Cell range Set the RowSel and ColSel property These properties set theselection starting from value set in Row and Col property tothe specified row and column Note that to specify a blockselection you must set Row and before setting RowSel andColSel

Example Title

c1FlexGrid1Row = 2c1FlexGrid1Col = 1c1FlexGrid1RowSel = 4c1FlexGrid1ColSel = 3

Call the Select(CellRange Boolean) method to select a cellrange in a single call

Example Title

CellRange cellRange = new CellRange()cellRanger1 = 2cellRanger2 = 4cellRangec1 = 1cellRangec2 = 3c1FlexGrid1Select(cellRange)

Rows

(If SelectionModes =

SelectionModesEnum

ListBox)

Set the RowSelected property to true for individual rowobjects to select the non-continuous rows

Example Title

c1FlexGrid1SelectionMode = SelectionModeEnumListBoxc1FlexGrid1Rows[1]Selected = truec1FlexGrid1Rows[4]Selected =

Value Description Snapshot

FlexGrid for WinForms

118 Copyright copy GrapeCity Inc All rights reserved

true

Get Selection To get selected range of the WinForms FlexGrid you can use Selection property of the C1FlexGrid class

Select Text on Double ClickBy default double click on a grid cell changes the cell state to edit mode and shows the cursor at position of the mouse pointerHowever you can change this behavior and select the cell value on double click of a cell This can be done by detecting anddisabling the double click in BeforeDoubleClick event Then call the StartEditing method to enter the edit mode change theeditor to a TextBox and call the SelectAll method to select the cell value

Following code shows how you can select text of the WinForms FlexGrid cell on a double click

private void Button1_Click(object sender EventArgs e) C1WinC1FlexGridCellRange cr cr = c1FlexGrid1Selection MessageBoxShow(Selected rangen + crr1 + + crc1 + to + crr2 + + crc2)

C

Private Sub Button1_Click(ByVal sender As Object ByVal e As EventArgs) Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1Selection MessageBoxShow(Selected range amp vbLf amp crr1 amp + crc1 amp to + crr2 amp + crc2)End Sub

VBNET

private void C1FlexGrid1_BeforeDoubleClick(object sender BeforeMouseDownEventArgs e) デフォルトのダブルクリックを無効にします eCancel = true 編集モードに入ります c1FlexGrid1StartEditing() TextBoxクラスに変換しSelectAllメソッドを使用して選択します TextBox tb = (TextBox)c1FlexGrid1Editor tbSelectAll()

C

Private Sub C1FlexGrid1_BeforeDoubleClick(ByVal sender As Object ByVal e As BeforeMouseDownEventArgs) デフォルトのダブルクリックを無効にします eCancel = True 編集モードに入ります c1FlexGrid1StartEditing() TextBoxクラスに変換しSelectAllメソッドを使用して選択します Dim tb As TextBox = CType(c1FlexGrid1Editor TextBox) tbSelectAll()End Sub

VBNET

Selection MethodProperty Sample code

FlexGrid for WinForms

119 Copyright copy GrapeCity Inc All rights reserved

編集

This topic discusses about various events and methods which are related to editing and also about how to disableediting

Topic Content

Edit Mode Discusses various events and methods related to editing

Disable Editing Discusses how to disable editing in grid at various levels

Disable Grid EditingDisable Row or Column EditingDisable Cell Editing

編集モード

In FlexGrid edit mode can be invoked at runtime using mouse click or even keyboard To determineprogrammatically whether the grid is in edit mode you can read the value of Editor property If the grid is in editmode the property returns a reference to the control that is being used as editor such as TextBox or ComboBoxHowever if the grid is not in edit mode the property returns null

To put the grid in edit mode programmatically you can use the StartEditing method and to finish editing you can callthe FinishEditing method You can also retain the state of edit mode in grid while navigating through the cells byusing the PreserveEditMode property

In addition FlexGrid fires various events to facilitate better control on the editing process Below table lists thesequence of events which are fired by the grid during the editing process

Event Name Description

BeforeEdit The event fires whenever an editable cell is selected It allows you to prevent the cell from beingedited by setting the events Cancel parameter to true You can also modify the ComboList propertyso the appropriate drop-down button gets painted in the cell Note that the user might not actuallystart editing after this he could simply move the selection to a different cell or control

StartEdit The event is similar to BeforeEdit except the user has actually typed a key or clicked the dropdownbutton in the cell and really is about to start editing You can still cancel the editing at this point Notethat the Editor property is still null at this point because the control hasnt yet determined the typeof editor that should be used You can assign custom editors to the Editor property at this point

ChangeEdit The event is a wrapper of editorTextChanged event The event fires when the contents of the editorchange You can use this event to keep track of the current content in editor

SetupEditor The event fires after the editor control has been created and configured to edit the cell but before itis displayed You can change the editor properties at this point (for example set the maximum lengthor password character to be used in a TextBox editor) You can also attach your own event handlers tothe editor

ValidateEdit The event fires when the user is done editing before the editor value gets copied back into the gridYou can examine the original value by retrieving it from the grid (the event provides the coordinatesof the cell) You can examine the new value about to be assigned to the grid through the Editorproperties (for example EditorText) If the new value is not valid for the cell set the Cancel parameterto true and the grid remains in edit mode If instead of keeping the cell in edit mode you wouldrather restore the original value and leave edit mode set Cancel parameter to true and then call theFinishEditing method

LeaveEdit This event fires after the grid control leaves edit mode You can use this event to approve or deny the

FlexGrid for WinForms

120 Copyright copy GrapeCity Inc All rights reserved

new cell content or to change the editor content about to be committed

AfterEdit This event fires after the new value has been applied to the cell and the editor has been deactivatedYou can use this event to update anything that depends on the cell value (for example subtotals orsorting)

Also there are few events which are related to keyboard operations and are fired when a key is pressed They aresimilar to their counterparts from SystemWindowsFormsControl class apart from the fact that they occur when thegrid is in edit mode

Event Description

KeyDownEdit This event fires when grid is in edit mode and a key is pressed You can use this event toperform an action once or even multiple times while the key is held down such as movinga cursor

KeyPressEdit This event fires when grid is in edit mode and a character key is pressed You can use thisevent to perform any operation related to typing such as handling input in the cell editor

KeyUpEdit This event fires when grid is in edit mode and key is released You can use this event toplace a logic that executes after KeypressEdit logic has taken effect

Event Name Description

編集の無効化

FlexGrid by default allows end-user to edit the cell values at runtime However with FlexGrid you can easily managehow much control you want to give to the end-users using various properties provided by the FlexGrid

Disable Grid EditingTo disable editing of the whole WinForms FlexGrid you need to set AllowEditing property of the C1FlexGrid class tofalse as shown in the code below

Disable Row or Column EditingTo disable the editing of a particular row or column of the WinForms FlexGrid you can set the AllowEditing propertyof Row or Column object to false as shown in the code below

グリッドで編集を無効にします c1FlexGrid1AllowEditing = false

C

グリッドで編集を無効にしますc1FlexGrid1AllowEditing = False

VBNET

3行目の編集を無効にしますc1FlexGrid1Rows[3]AllowEditing = false 3列目の編集を無効にしますc1FlexGrid1Cols[3]AllowEditing = false

C

FlexGrid for WinForms

121 Copyright copy GrapeCity Inc All rights reserved

Disable Cell EditingTo disable editing of a particular cell you can use the BeforeEdit event and set the Cancel parameter for thatparticular cell to true

3行目の編集を無効にしますc1FlexGrid1Rows(3)AllowEditing = False

3列目の編集を無効にしますc1FlexGrid1Cols(3)AllowEditing = False

VBNET

セル編集を無効にしますprivate void C1FlexGrid1_BeforeEdit(object sender RowColEventArgs e) if ((eCol == 4) ampamp (eRow == 2)) eCancel = true

C

セル編集を無効にしますPrivate Sub C1FlexGrid1_BeforeEdit(ByVal sender As Object ByVal e As RowColEventArgs) If eCol = 4 AndAlso eRow = 2 Then eCancel = True End IfEnd Sub

VBNET

FlexGrid for WinForms

122 Copyright copy GrapeCity Inc All rights reserved

並べ替え

Sorting is one of the basic features a grid must have and FlexGrid provides you complete control on how data can besorted in ascending or descending order for easier data analysis This topic discusses about sorting in FlexGrid andother related operations

Topic Snapshot Content

Sort Operations Discusses various operations related to sorting

Sorting through CodeSort Multiple ColumnsRevertUndo SortingDisable Sort on a Particular ColumnSort OrderCustom Sorting

Sort Indicator Discusses how to hide position and customize sort indicator

HideDisplay Sort IndicatorPosition Sort IndicatorCustomize Sort Indicator

並べ替えの操作

FlexGrid by default allows end-users to apply sorting on a single column by clicking the column header in ascending ordescending order However the grid also provides you flexibility so that you can sort your data according to yourrequirement Below sections take you through the ways to perform various operations related to sorting

Sorting through CodeYou can apply sorting through code by calling Sort method of the C1FlexGrid class The method takes SortFlagsenumeration as its parameter which lets you provide the various sort options such as setting the sort order and ignorecasing The method has various overloads which gives you flexibility to apply sorting either on a column or a range ofcells rows or columns

Use the code below to sort columns and apply sorting options through code in the WinForms FlexGrid

FlexGrid for WinForms

123 Copyright copy GrapeCity Inc All rights reserved

Sort Multiple ColumnsTo apply sorting on multiple columns through code you can use the Sort property of Column class and then call theSort() method with SortFlags set to UseColSort The Sort property accepts values from SortFlags enumeration

Following code shows how to sort multiple columns of the WinForms FlexGrid through code

To allow user to sort multiple columns at runtime set AllowSorting property of the C1FlexGrid class to MultiColumn Theproperty accepts values from the AllowSortingEnum enumeration

Following code shows how to let user sort multiple columns of the WinForms FlexGrid at run-time

方法1 2番目の列を降順で並べ替えますc1FlexGrid1Sort(C1WinC1FlexGridSortFlagsDescending 2) 方法 2SortFlagを使用して複数の並べ替えオプションを指定しますC1WinC1FlexGridSortFlags order = C1WinC1FlexGridSortFlagsAscending | C1WinC1FlexGridSortFlagsIgnoreCase Sortメソッドを呼び出しますc1FlexGrid1Sort(order 2)

C

方法1 2番目の列を降順で並べ替えますc1FlexGrid1Sort(C1WinC1FlexGridSortFlagsDescending 2)

方法2 SortFlagを使用して複数の並べ替えオプションを指定しますDim order As C1WinC1FlexGridSortFlags = C1WinC1FlexGridSortFlagsAscending Or C1WinC1FlexGridSortFlagsIgnoreCase

Sortメソッドを呼び出しますc1FlexGrid1Sort(order 2)

VBNET

複数列を並べ替えますc1FlexGrid1Cols[2]Sort = SortFlagsAscendingc1FlexGrid1Cols[3]Sort = SortFlagsDescending Sortメソッドを呼び出しますc1FlexGrid1Sort(SortFlagsUseColSort 2 3)

C

複数列を並べ替えますc1FlexGrid1Cols(2)Sort = SortFlagsAscendingc1FlexGrid1Cols(3)Sort = SortFlagsDescending

Sortメソッドを呼び出しますc1FlexGrid1Sort(SortFlagsUseColSort 2 3)

VBNET

グリッドの複数の列での並べ替えを許可します c1FlexGrid1AllowSorting = AllowSortingEnumMultiColumn

C

FlexGrid for WinForms

124 Copyright copy GrapeCity Inc All rights reserved

RevertUndo SortingTo remove sorting from the grid you can set SortDefinition property of the C1FlexGrid class to an empty string

Below code how to remove sorting from the WinForms FlexGrid

Disable Sort on a Particular ColumnTo disable sorting on a particular column you need to set the AllowSorting property of that Column object to false

Use the code below to disable sorting on a particular column of the WinForms FlexGrid

Sort OrderOrder of sorting usually varies in case of bound and unbound mode When a column header is clicked in case of boundmode sorting is done same as DefaultViewSort property of the data table However in case of unbound mode columnis sorted either according to StringCompare method or by differentiating the lower and upper case according to theculture

Refer to the code below to specify sorting order of a WinForms FlexGrid column

グリッドの複数の列での並べ替えを許可しますc1FlexGrid1AllowSorting = AllowSortingEnumMultiColumn

VBNET

並べ替えを削除します c1FlexGrid1SortDefinition = stringEmpty

C

並べ替えを削除しますc1FlexGrid1SortDefinition = StringEmpty

VBNET

グリッドの特定の列での並べ替えを無効にしますc1FlexGrid1Cols[2]AllowSorting = false

C

グリッドの特定の列での並べ替えを無効にしますc1FlexGrid1Cols(2)AllowSorting = False

VBNET

C1WinC1FlexGridSortFlags order = C1WinC1FlexGridSortFlagsAscending | C1WinC1FlexGridSortFlagsIgnoreCase c1FlexGrid1Sort(order 2)

C

Dim order As C1WinC1FlexGridSortFlags = C1WinC1FlexGridSortFlagsAscending Or C1WinC1FlexGridSortFlagsIgnoreCasec1FlexGrid1Sort(order 2)

VBNET

FlexGrid for WinForms

125 Copyright copy GrapeCity Inc All rights reserved

Custom SortingFlexGrid provides several sorting options which are required for most commonly used scenarios such as ignore case usethe display value etc However if you need to have more flexibility and control over sort operation you can even writeyour own custom logic using the IComparer class For instance the example below sorts the Name column by fileextensions In the sample code custom logic to sort by file extension is implemented in the FileNameComparer class whichis then passed as parameter to Sort() method of the C1FlexGrid class

The code below demonstrates how to apply custom sorting on the WinForms FlexGrid columns

c1FlexGrid1Sort(new FileNameComparer(c1FlexGrid1 eOrder)) class FileNameComparer IComparer C1FlexGrid c1FlexGrid1 bool _desc

ctor public FileNameComparer(C1FlexGrid flex SortFlags order) c1FlexGrid1 = flex _desc = ((order amp SortFlagsDescending) = 0) IComparer public int Compare(object r1 object r2) ファイル名を取得します string s1 = (string)c1FlexGrid1[((Row)r1)Index Name] string s2 = (string)c1FlexGrid1[((Row)r2)Index Name]

拡張機能を比較します int icmp = stringCompare(PathGetExtension(s1) PathGetExtension(s2) true)

並べ替え順(昇順または降順)を返します return (_desc) -icmp icmp

C

C1FlexGrid1Sort(New FileNameComparer(C1FlexGrid1 SortFlagsAscending))

Public Class FileNameComparer Implements IComparer

Private c1FlexGrid1 As C1FlexGrid Private _desc As Boolean

Public Sub New(ByVal flex As C1FlexGrid ByVal order As SortFlags) c1FlexGrid1 = flex _desc = ((order And SortFlagsDescending) ltgt 0) End Sub

Public Function Compare(r1 As Object r2 As Object) As Integer Implements IComparerCompare Dim s1 As String = CStr(c1FlexGrid1((CType(r1 Row))Index Name)) Dim s2 As String = CStr(c1FlexGrid1((CType(r2 Row))Index Name)) Dim icmp As Integer = StringCompare(PathGetExtension(s1) PathGetExtension(s2) True) Return If((_desc) -icmp icmp) End Function

VBNET

FlexGrid for WinForms

126 Copyright copy GrapeCity Inc All rights reserved

For detailed implementation of custom sorting see the product sample named Custom Sort

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing WinFormsEdition using ComponentOneControlPanelexe

並べ替えのインジケータ

FlexGrid displays sort indicator a small triangular arrow sign to indicate the direction of sorting The grid alsoprovides flexibility to hide display position or customize the indicator

Hide or Display Sort IndicatorFlexGrid by default displays the sort indicator when a column header is clicked to sort the columns However you canhide the indicator by setting the ShowSortPosition property to None The property accepts valuesfrom ShowSortPositionEnum enumeration

Use the code below to hide the sort indicator displayed on the sorted WinForms FlexGrid column

Position Sort IndicatorSort indicator by default gets displayed towards the right side of the header cell However when the filtering isapplied on a column the sort indicator displays on top of the header cell to give place to the filtering icon You can fixthe position of sort indicator by setting value of ShowSortPosition property to Top or Right

Customize the position of column sort indicator in WinForms FlexGrid using the code below

Customize Sort IndicatorFlexGrid provides the GlyphEnum enumeration which lets you specify the image to be used for sort indicator Formore information on the GlyphEnum and glyph customization see Custom Glyphs

並べ替えインジケータを非表示にしますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumNone

C

並べ替えインジケータを非表示にしますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumNone

VBNET

並べ替えインジケータの位置を上に変更しますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumTop

C

並べ替えインジケータの位置を上に変更しますc1FlexGrid1ShowSortPosition = ShowSortPositionEnumTop

VBNET

FlexGrid for WinForms

127 Copyright copy GrapeCity Inc All rights reserved

フィルタ

Grid filtering lets you narrow down display records according to a specified condition applied on a column It is especially useful in case of large data sets asit lets you easily analyze data by displaying a specific type of records only

This section discusses about the process types and customization of filters

Topic Snapshot Content

Filter Operations Discusses about how to enable or apply filtering and other related operations

Allow FilteringFiltering through CodeCustom FilteringRemove FilteringTypes of Filters

Filter UI Discusses about filtering icon its customization and how to set the filter language

Show Filter IconUse Custom IconsChange Filter Language

フィルタの操作

Data filtering in a grid can be performed in two ways

Header-based Filter

In header-based filtering an icon is displayed in the header cell of column which gives you options to specify the filter in a drop-down and alsoindicates if the filter is applied on a particular column In FlexGrid this behavior can be achieved by simply using AllowFiltering property of the gridIn this case filter does not require any extra real estate on the screen This approach also gives you flexibility to customize and create better filtereditors More details about same is given in the sections below

Filter Row

Filter row is a row dedicated for displaying the filtering criteria and appears just below the column header So in this case user can always see thefiltered columns and their current filtering criteria But this added advantage comes at the cost of extra screen real estate that a filter row needs InFlexGrid you can easily achieve filter row using the custom implementation For implementation see the product sample named Filter Row

Note The Filter Row sample is located at DocumentsComponentOne SamplesWinFormsv452C1FlexGridCS on your system if you haveinstalled the samples while installing WinForms Edition using ComponentOneControlPanelexe

Allow FilteringIn FlexGrid filtering can be enabled by setting the C1FlexGridAllowFiltering property to true This enables the default ColumnFilter on allcolumns of the grid The ColumnFilter lets the users choose from ValueFilter and ConditionFilter at runtime

FlexGrid for WinForms

128 Copyright copy GrapeCity Inc All rights reserved

You can also specify the filter types for each column by setting the AllowFiltering property of each Column object AllowFiltering property ofcolumn lets you choose from any of the following values

Value Description

Default Enables the ColumnFilter which is a combination of ValueFilter and ConditionFilter and gives user a runtime option to choose eitherof them

ByValue Enables ValueFilter which contains a checkbox list of values present in that column User can check off the values that should not bedisplayed in the filtered output

ByCondition Enables ConditionFilter which lets you specify combination of two conditions such as equals greater than contains etc Youcan combine the specified conditions using And and Or operator

Custom Lets you instantiate a custom filter and explicitly assign it to Filter property of the column

None Disables filtering for that column

Use the following code snippet to enable a condition filter on first column of the WinForms FlexGrid

For more details regarding abovementioned filter types see Types of Filters

Filtering through CodeAlthough AllowFiltering property of grid enables grid filtering and can be used in most common scenarios there may be cases where you need tofurther fine tune the filter options This can be achieved by modifying AllowFiltering and Filter properties of individual columns For example thecode below enables filtering in the WinForms FlexGrid but restricts the filtering to columns of type string

You can also customize the filtering process further by creating filters and assigning them to columns or by retrieving existing filters and modifyingtheir properties For example the code below creates a ConditionFilter in the WinForms FlexGrid configures it to select all items that are equal toGermany and then assigns the new filter to the ShipCountry column

グリッドでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = true 列1に対してフィルタを指定しますc1FlexGrid1Cols[1]AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

C

グリッドでのフィルタリングを許可しますc1FlexGrid1AllowFiltering = True

列1に対してフィルタを指定しますc1FlexGrid1Cols(1)AllowFiltering = C1WinC1FlexGridAllowFilteringByCondition

VBNET

文字列型の列にフィルタリングを制限します foreach (Column c in c1FlexGrid1Cols) cAllowFiltering = cDataType == typeof(string) AllowFilteringDefault AllowFilteringNone

C

文字列型の列にフィルタリングを制限しますFor Each c As Column In c1FlexGrid1Cols cAllowFiltering = If(cDataType Is GetType(String) AllowFilteringDefault AllowFilteringNone)Next

VBNET

グリッドでフィルタリングを有効にします c1FlexGrid1AllowFiltering = true 新しいConditionFilterを作成します C1WinC1FlexGridConditionFilter Filter Filter = new C1WinC1FlexGridConditionFilter()

C

FlexGrid for WinForms

129 Copyright copy GrapeCity Inc All rights reserved

Custom FilteringWhen filtering is applied to FlexGrid it hides the rows that do not qualify the filtering criteria by setting their Visible property to false However insome cases you may want to customize this behavior For such scenarios you can use the BeforeFilter and AfterFilter events fired by FlexGridThe below example customizes the filtering behavior of WinForms FlexGrid by applying a different style to non-qualifying rows instead of hidingthem

Germanyのアイテムを絞り込むためのフィルタを作成します FilterCondition1Operator = C1WinC1FlexGridConditionOperatorEquals FilterCondition1Parameter = Germany 「ShipCountry」列に新しいフィルタを割り当てます c1FlexGrid1Cols[ShipCountry]Filter = Filter フィルタを適用します c1FlexGrid1ApplyFilters()

グリッドでフィルタリングを有効にしますc1FlexGrid1AllowFiltering = True

新しいConditionFilterを作成しますDim Filter As C1WinC1FlexGridConditionFilterFilter = New C1WinC1FlexGridConditionFilter()

Germanyのアイテムを絞り込むためのフィルタを作成しますFilterCondition1[Operator] = C1WinC1FlexGridConditionOperatorEqualsFilterCondition1Parameter = Germany

「ShipCountry」列に新しいフィルタを割り当てますc1FlexGrid1Cols(ShipCountry)Filter = Filter

フィルタを適用しますc1FlexGrid1ApplyFilters()

VBNET

private void c1FlexGrid1_BeforeFilter(object sender CancelEventArgs e) c1FlexGrid1BeginUpdate()

private void c1FlexGrid1_AfterFilter(object sender EventArgs e) フィルタリングされた行を表示するために使用されるスタイルを取得します var cs = c1FlexGrid1Styles[filteredOut]

すべての行にスタイルを適用します

C

FlexGrid for WinForms

130 Copyright copy GrapeCity Inc All rights reserved

The above code uses a custom style named filteredout which can be defined as shown in the code below

Remove FilteringUser can remove column filtering at runtime by using Clear option given in the filter UI of each column You can also remove filtering of the wholegrid programmatically by passing the empty string in FilterDefinition property of FlexGrid

Below code demonstrates how to clear all the filters from the WinForms FlexGrid

for (int r = c1FlexGrid1RowsFixed r lt c1FlexGrid1RowsCount r++) var row = c1FlexGrid1Rows[r] if (rowVisible) 通常の行スタイルをリセットします rowStyle = null else フィルタリングされた行 見えるようにしスタイルを適用します rowVisible = true rowStyle = cs

更新を再開します c1FlexGrid1EndUpdate()

Private Sub c1FlexGrid1_BeforeFilter(ByVal sender As Object ByVal e As CancelEventArgs) c1FlexGrid1BeginUpdate()End Sub

Private Sub c1FlexGrid1_AfterFilter(ByVal sender As Object ByVal e As EventArgs) フィルタリングされた行を表示するために使用されるスタイルを取得します Dim cs = c1FlexGrid1Styles(filteredOut)

すべての行にスタイルを適用します For r = c1FlexGrid1RowsFixed To c1FlexGrid1RowsCount - 1 Dim row = c1FlexGrid1Rows(r)

If rowVisible Then 通常の行スタイルをリセットします rowStyle = Nothing Else フィルタリングされた行 見えるようにしスタイルを適用します rowVisible = True rowStyle = cs End If Next

更新を再開します c1FlexGrid1EndUpdate()End Sub

VBNET

フィルタによって除外された行のスタイルを作成しますvar cs = c1FlexGrid1StylesAdd(filteredOut)csBackColor = ColorLightGraycsForeColor = ColorDarkGray

C

フィルタによって除外された行のスタイルを作成しますDim cs = c1FlexGrid1StylesAdd(filteredOut)csBackColor = ColorLightGraycsForeColor = ColorDarkGray

VBNET

フィルタ定義を空の文字列に設定してフィルタリングを削除しますc1FlexGrid1FilterDefinition = stringEmpty

C

FlexGrid for WinForms

131 Copyright copy GrapeCity Inc All rights reserved

フィルタ定義を空の文字列に設定してフィルタリングを削除しますc1FlexGrid1FilterDefinition = StringEmpty

VBNET

フィルタの種類

FlexGrid not only provides built-in filters such as Column filter Value filter and Condition Filter but also lets youcreate your own custom filter The built-in filters are provided through AllowFiltering property of Column class whichlets you set the type of filter to be applied on a particular column On the other hand the custom filters make use ofthe IC1ColumnFilter interface and the IC1ColumnFilterEditor interface This topic discusses the implementation ofbuilt-in and custom filters in detail

Column FilterColumn filter is the default filter that is applied to all the columns automatically when AllowFiltering property of thegrid is set to true The ColumnFilter is a combination of ValueFilter and ConditionFilter (discussed below) and givesuser an option to choose either of them at runtime While working with code you can use its ValueFilterand ConditionFilter properties to access the two types of filters The filter also provides Apply method to apply filterto a value and Reset method to reset the filter and hence making it inactive

Use the below code to apply column filter on ProductName column of the WinForms FlexGrid

列フィルタ(ProductNameが「C」で始まる製品をフィルター処理します)ColumnFilter colFilter = new ColumnFilter()colFilterConditionFilterCondition1Parameter = CcolFilterConditionFilterCondition1Operator = ConditionOperatorBeginsWithc1FlexGrid1Cols[ProductName]Filter = colFilter

C

列フィルタ(ProductNameが「C」で始まる製品をフィルター処理します) Dim colFilter As ColumnFilter = New ColumnFilter()

VBNET

FlexGrid for WinForms

132 Copyright copy GrapeCity Inc All rights reserved

Value FilterValue filter refers to the value based filter which gets enabled on setting the AllowFiltering property of column toByValue The ValueFilter provides the dropdown list of all values with checkbox which lets the user select the valueswhich are to be displayed in the output These values can be get or set through the ShowValues property You canalso set a limit on number of values to be displayed in the dropdown list by setting the ValuesLimit property Just likecolumn filter value filter also provides Apply method to apply filter to a value and Reset method to reset the filter

Below code shows how to apply ValueFilter on a column of the WinForms FlexGrid

Condition FilterCondition filter refers to a filter based on one or two logical conditions which can be enabled by setting theAllowFiltering property to ByCondition The ConditionFilter gives user an option to set the conditionsthrough Condition1 and Condition2 properties which can be combined using ANDOR operator by settingthe AndConditions property to filter the records Similar to other filters this class also provides Apply and Resetmethod

colFilterConditionFilterCondition1Parameter = C colFilterConditionFilterCondition1[Operator] = ConditionOperatorBeginsWith c1FlexGrid1Cols(ProductName)Filter = colFilter

値フィルタ(CategoryIdが12358である製品をフィルタ処理します)ValueFilter valueFilter = new ValueFilter()valueFilterShowValues = new object[] 1 2 3 5 8 c1FlexGrid1Cols[CategoryId]Filter = valueFilter

C

値フィルタ(CategoryIdが12358である製品をフィルタ処理します) Dim valueFilter As ValueFilter = New ValueFilter() valueFilterShowValues = New Object() 1 2 3 5 8 c1FlexGrid1Cols(CategoryId)Filter = valueFilter

VBNET

FlexGrid for WinForms

133 Copyright copy GrapeCity Inc All rights reserved

Below code demonstrates how to apply a ConditionFilter on a WinForms FlexGrid column

Custom FilterThe abovementioned filters provide you enough flexibility to implement most common filtering scenarios efficientlyIn addition custom filter option also lets you create your own filter to meet any other specialized requirements ofyour application To create a custom filter you need to create a filter class that implements the IC1ColumnFilterinterface and an editor class that implements the IC1ColumnFilterEditor interface Below example shows theimplementation of a custom string filter which lets you filter based on ranges

条件フィルタ(UnitPricegt = 50およびlt= 100の製品をフィルタ処理します)ConditionFilter conditionFilter = new ConditionFilter()conditionFilterCondition1Parameter = 50conditionFilterCondition1Operator = ConditionOperatorGreaterThanOrEqualToconditionFilterCondition2Parameter = 100conditionFilterCondition2Operator = ConditionOperatorLessThanOrEqualToconditionFilterAndConditions = truec1FlexGrid1Cols[UnitPrice]Filter = conditionFilter

C

条件フィルタ(UnitPricegt = 50およびlt= 100の製品をフィルタ処理します) Dim conditionFilter As ConditionFilter = New ConditionFilter() conditionFilterCondition1Parameter = 50 conditionFilterCondition1[Operator] = ConditionOperatorGreaterThanOrEqualTo conditionFilterCondition2Parameter = 100 conditionFilterCondition2[Operator] = ConditionOperatorLessThanOrEqualTo conditionFilterAndConditions = True c1FlexGrid1Cols(UnitPrice)Filter = conditionFilter

VBNET

FlexGrid for WinForms

134 Copyright copy GrapeCity Inc All rights reserved

Following is the code of a custom filter created for the WinForms FlexGrid Note that the class implementsIC1CustomFilter interface

StringFiltercs

class StringFilter C1WinC1FlexGridIC1ColumnFilter

ListltPointgt _ranges = new ListltPointgt()

ltsummarygt このフィッタが受け入れる文字列を定義するポイントのリストを取得します ltsummarygt public ListltPointgt Ranges get return _ranges

範囲リストが空でない場合フィルタはアクティブです public bool IsActive get return _rangesCount gt 0

フィルタをリセットします public void Reset() _rangesClear()

指定された日付にフィルタを適用します public bool Apply(object value) if (value = null)

C

FlexGrid for WinForms

135 Copyright copy GrapeCity Inc All rights reserved

var s = valueToString() if (sLength gt 0) int c = charToUpperInvariant(s[0]) foreach (var cr in _ranges) if (c gt= charToUpperInvariant((char)crX) ampamp c lt= charToUpperInvariant((char)crY)) return true return false

このフィルタのエディタコントロールを返します public C1WinC1FlexGridIC1ColumnFilterEditor GetEditor() return new StringFilterEditor()

Friend Class StringFilter Implements C1WinC1FlexGridIC1ColumnFilter Private _ranges As List(Of Point) = New List(Of Point)()

ltsummarygt このフィッタが受け入れる文字列を定義するポイントのリストを取得します ltsummarygt Public ReadOnly Property Ranges As List(Of Point) Get Return _ranges End Get End Property

範囲リストが空でない場合フィルタはアクティブです Public ReadOnly Property IsActive As Boolean Implements C1WinC1FlexGridIC1ColumnFilterIsActive Get Return _rangesCount gt 0 End Get End Property

フィルタをリセットします Public Sub Reset() Implements C1WinC1FlexGridIC1ColumnFilterReset _rangesClear() End Sub

指定された日付にフィルタを適用します Public Function Apply(ByVal value As Object) As Boolean Implements C1WinC1FlexGridIC1ColumnFilterApply If value IsNot Nothing Then Dim s = valueToString()

If sLength gt 0 Then Dim c As Integer = AscW(CharToUpperInvariant(s(0)))

VBNET

FlexGrid for WinForms

136 Copyright copy GrapeCity Inc All rights reserved

Following is the code of a custom class that implements IC1CustomFilterEditor interface

StringFilterEditorcs

For Each cr In _ranges

If c gt= AscW(CharToUpperInvariant(MicrosoftVisualBasicChrW(crX))) AndAlso c lt= AscW(CharToUpperInvariant(MicrosoftVisualBasicChrW(crY))) Then Return True End If Next End If End If

Return False End Function

このフィルタのエディタコントロールを返します Public Function GetEditor() As C1WinC1FlexGridIC1ColumnFilterEditor Implements C1WinC1FlexGridIC1ColumnFilterGetEditor Return New StringFilterEditor() End Function

End Class

public partial class StringFilterEditor UserControl C1WinC1FlexGridIC1ColumnFilterEditor StringFilter _filter

public StringFilterEditor() InitializeComponent()

public void Initialize(C1WinC1FlexGridC1FlexGridBase grid int columnIndex C1WinC1FlexGridIC1ColumnFilter filter) _filter = (StringFilter)filter

チェックボックスの値を初期化します foreach (var pt in _filterRanges) switch ((char)ptX) case A _chkAEChecked = true break case F _chkFJChecked = true break case K _chkKOChecked = true break case P _chkPTChecked = true

C

FlexGrid for WinForms

137 Copyright copy GrapeCity Inc All rights reserved

break case U _chkUZChecked = true break public void ApplyChanges() フィルタをリセットします _filterRangesClear()

選択した範囲を追加します foreach (Control ctl in thisControls) var cb = ctl as CheckBox if (cb = null ampamp cbChecked) var pt = new Point((int)cbText[0] (int)cbText[cbTextLength - 1]) _filterRangesAdd(pt) public bool KeepFormOpen get return false void _chkAE_CheckedChanged(object sender EventArgs e) var cb = sender as CheckBox cbFont = new Font(Font cbChecked FontStyleBold FontStyleRegular)

Public Partial Class StringFilterEditor Inherits UserControl Implements C1WinC1FlexGridIC1ColumnFilterEditor

Private _filter As StringFilter Public Sub New() InitializeComponent() End Sub

Public Sub Initialize(ByVal grid As C1WinC1FlexGridC1FlexGridBase ByVal columnIndex As Integer ByVal filter As C1WinC1FlexGridIC1ColumnFilter) Implements C1WinC1FlexGridIC1ColumnFilterEditorInitialize _filter = CType(filter StringFilter)

チェックボックスの値を初期化します For Each pt In _filterRanges

Select Case MicrosoftVisualBasicChrW(ptX) Case Ac _chkAEChecked = True Case Fc _chkFJChecked = True Case Kc _chkKOChecked = True Case Pc

VBNET

FlexGrid for WinForms

138 Copyright copy GrapeCity Inc All rights reserved

_chkPTChecked = True Case Uc _chkUZChecked = True End Select Next End Sub

Public Sub ApplyChanges() Implements C1WinC1FlexGridIC1ColumnFilterEditorApplyChanges フィルタをリセットします _filterRangesClear()

選択した範囲を追加します For Each ctl As Control In Controls Dim cb = TryCast(ctl CheckBox)

If cb IsNot Nothing AndAlso cbChecked Then Dim pt = New Point(MicrosoftVisualBasicAscW(cbText(0)) MicrosoftVisualBasicAscW(cbText(cbTextLength - 1))) _filterRangesAdd(pt) End If Next End Sub

Public ReadOnly Property KeepFormOpen As Boolean Implements C1WinC1FlexGridIC1ColumnFilterEditorKeepFormOpen Get Return False End Get End Property

Private Sub _chkAE_CheckedChanged(ByVal sender As Object ByVal e As EventArgs) Dim cb = TryCast(sender CheckBox) cbFont = New Font(MyBaseFont If(cbChecked FontStyleBold FontStyleRegular)) End Sub

End Class

フィルタUI

FlexGrid provides several options to flexibly customize the filtering UI and lets you create your own unique filter for yourapplication The control allows you to show hide and customize the filtering icon You can even change the language displaying infilter to meet your localization requirements

Show Filter Icon

FlexGrid by default shows the filtering icon( ) when mouse hovers over the filterable column header However you can chooseto display the filtering icon always by setting ShowFilterIcon property of the C1FlexGrid class to Always The property accepts thevalues from FilterIconVisibility enumeration

FlexGrid for WinForms

139 Copyright copy GrapeCity Inc All rights reserved

Use the code below to always display the filter icon on filtered columns of the WinForms FlexGrid

Use Custom IconsFlexGrid also lets you customize the filtering icon by using Glyphs property of the C1FlexGrid class which accepts an imagethrough GlyphEnum enumeration You can also change icon displayed on the current filtered column using the same enumerationFor more information about custom glyphs see Custom Glyphs

常にフィルタのアイコンを表示しますc1FlexGrid1ShowFilterIcon = C1WinC1FlexGridFilterIconVisibilityAlways

C

常にフィルタのアイコンを表示しますc1FlexGrid1ShowFilterIcon = C1WinC1FlexGridFilterIconVisibilityAlways

VBNET

FlexGrid for WinForms

140 Copyright copy GrapeCity Inc All rights reserved

Following code displays how to apply custom icons on filtered columns of the WinForms FlexGrid

Change Filter LanguageBy default FlexGrid localizes the column filter editor to use language specified by the CurrentUICulture setting However you canuse the Language property to override the default and specify the language to be used when grid displays the column filter editor

Use the below code to change the display language of filter in the WinForms FlexGrid

フィルタのアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilterEditor] = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilteredColumn] = ImageFromFile(filterico)

C

フィルタのアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilterEditor) = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilteredColumn) = ImageFromFile(filterico)

VBNET

フィルタ言語を日本語に設定しますc1FlexGrid1Language = C1UtilLocalizationLanguageJapanese

C

フィルタ言語を日本語に設定しますc1FlexGrid1Language = C1UtilLocalizationLanguageJapanese

VBNET

FlexGrid for WinForms

141 Copyright copy GrapeCity Inc All rights reserved

検索

With FlexGrid you can easily perform search either on the entire grid or just a specific column This topic discusseshow you can enable search in FlexGrid

Search in Entire GridTo search the entire FlexGrid you need to add the C1FlexGridSearchPanel control to the form and associate it with thegrid to be searched using SetC1FlexGridSearchPanel method The C1FlexGridSearchPanel control highlights thesearch results and filters the records having search results automatically However you can choose not to highlight theresults by setting the HighlightSearchResults to false It also provides a SearchMode property to set whether tostart the search automatically or on hitting the Search button or Enter key You can also set the watermark in searchbox as well as a time delay in search

Use the code below to search the entire WinForms FlexGrid using SearchPanel

検索パネルを検索対象のFlexGridに関連付けますc1FlexGridSearchPanel1SetC1FlexGridSearchPanel(c1FlexGrid1 c1FlexGridSearchPanel1)

検索を構成しますc1FlexGridSearchPanel1HighlightSearchResults = truec1FlexGridSearchPanel1SearchMode = C1WinC1FlexGridSearchModeAlways c1FlexGridSearchPanel1Watermark = Search productsc1FlexGridSearchPanel1SearchDelay = 2

C

検索パネルを検索対象のFlexGridに関連付けます

VBNET

FlexGrid for WinForms

142 Copyright copy GrapeCity Inc All rights reserved

Search in ColumnTo enable column-wise search FlexGrid provides AutoSearch property of the C1FlexGrid class which accepts valuesfrom AutoSearchEnum enumeration The enumeration lets you start downward column search from the first scrollablerow or from the current cursor position To search a value in a particular column you need to keep the cursor in thatcolumn and type the value to be searched and grid automatically jumps to the search result in that column You canalso set delay in search by setting the AutoSearchDelay property

Following code enables column-wise search in the WinForms FlexGrid

c1FlexGridSearchPanel1SetC1FlexGridSearchPanel(c1FlexGrid1 c1FlexGridSearchPanel1)

検索を構成しますc1FlexGridSearchPanel1HighlightSearchResults = Truec1FlexGridSearchPanel1SearchMode = C1WinC1FlexGridSearchModeAlwaysc1FlexGridSearchPanel1Watermark = Search productsc1FlexGridSearchPanel1SearchDelay = 2

一番上の行からの列単位の検索を有効にしますc1FlexGrid1AutoSearch = C1WinC1FlexGridAutoSearchEnumFromTopc1FlexGrid1AutoSearchDelay = 2

C

一番上の行からの列単位の検索を有効にしますc1FlexGrid1AutoSearch = C1WinC1FlexGridAutoSearchEnumFromTopc1FlexGrid1AutoSearchDelay = 2

VBNET

FlexGrid for WinForms

143 Copyright copy GrapeCity Inc All rights reserved

マージ

FlexGrid allows you to merge cells with same values making them span multiple rows or columns This capability is useful for enhancing appearance andclarity of data displayed in the grid The effect of these settings is similar to the HTML ltROWSPANgt and ltCOLSPANgt tags

Cell merging has several possible uses For example you can use it to create merged table headers merged data views or grids where the text spills intoadjacent columns This section discusses these scenarios in the topics below

Topic Snapshot Content

Auto-merge Discusses about how to enable automatic merging in grid

Free auto-mergeRestricted auto-mergeMerge table headers

Handle Spilling Text Discusses how to display long texts in normal and node rows

Handle Spill in Normal CellsHandle Text in Node Rows

Custom Merge Discusses about ways to customize the default merging behavior

Method 1 Use IComparer interfaceMethod 2 Override the GetMergedRange method

自動マージ

FlexGrid lets you enable automatic cell merging in the grid by setting the AllowMerging property to a value other than None Inaddition you need to set the AllowMerging property of each target row or column to true Merging occurs only if adjacent cellscontain the same non-empty string There is no method to force a pair of cells to merge The merging is done automaticallybased on the cell contents This feature makes it easy to provide merged views of sorted data where values in adjacent rowspresent repeated data

Free Auto-mergeFree auto-merge refers to merging of cells with just one pre-condition of having same values in adjacent cells To automaticallymerge the cells in a row or a column you simply need to set AllowMerging property of the C1FlexGrid class to Free and setAllowMerging property of the target row or column object to true

FlexGrid for WinForms

144 Copyright copy GrapeCity Inc All rights reserved

Below code shows how to apply free merging on a WinForms FlexGrid column

Restricted Auto-mergeIn most of the scenarios you would want the grid to merge the grid cells with same values only if cells above or in left directionare also merged This behavior is called restricted auto-merge and can be achieved by setting the C1FlexGridAllowMergingproperty to RestrictAll RestrictRows or RestrictCols This is required in addition to setting the AllowMerging property oftarget row or column to true

Use the code below to allow restricted auto-merging on a WinForms FlexGrid column

Merge Table HeadersMerging the header cells specially in case of multi-row header is another very common scenario used in grids and tables Tomerge the header cells you must set the C1FlexGridAllowMerging property to FixedOnly You must also set theAllowMerging property of designated row and columns to true In this case headers cells with same value merge together togive a simplified appearance

許可される結合の種類を指定しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFree 結合を許可する列を指定しますc1FlexGrid1Cols[2]AllowMerging = true

C

許可される結合の種類を指定しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFree

結合を許可する列を指定しますc1FlexGrid1Cols(2)AllowMerging = True

VBNET

結合を許可する列を指定しますc1FlexGrid1Cols[3]AllowMerging = true 左側のセルが結合されている場合にのみ列を結合しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumRestrictCols

C

結合を許可する列を指定しますc1FlexGrid1Cols(3)AllowMerging = True

左側のセルが結合されている場合にのみ列を結合しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumRestrictCols

VBNET

FlexGrid for WinForms

145 Copyright copy GrapeCity Inc All rights reserved

Following code demonstrates how to apply merging only on table headers of the WinForms FlexGrid

Custom Auto-mergeFlexGrid also provides a Custom option through AllowMerging enumeration In this case auto-merge is performed on cellrange collection provided using MergedRanges property of the C1FlexGrid class The custom auto-merge is performedindependent of cell content For instance below image shows the merging of two specified cell ranges despite of the differentcell values

固定の行と列の結合を許可しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnly

C

固定の行と列の結合を許可しますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumFixedOnly

VBNET

FlexGrid for WinForms

146 Copyright copy GrapeCity Inc All rights reserved

Use the following code snippet to apply custom merge on the WinForms FlexGrid

結合のモードをアクティブにしますthisc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumCustom

いくつかのマージされた範囲を定義します 2つのセルは幅が広く1つのセルは高いですthisc1FlexGrid1MergedRangesAdd(2 2 2 3)

3つのセルは幅が広く3つのセルは高さですthisc1FlexGrid1MergedRangesAdd(5 2 7 4)

C

結合のモードをアクティブにしますMec1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumCustom

いくつかのマージされた範囲を定義します 2つのセルは幅が広く1つのセルは高いですMec1FlexGrid1MergedRangesAdd(2 2 2 3)

3つのセルは幅が広く3つのセルは高さですMec1FlexGrid1MergedRangesAdd(5 2 7 4)

VBNET

はみ出して表示されるセルの処理

In FlexGrid you can create the same behavior as excel for handling long text entries by spilling them into emptyadjacent cells This behavior not only helps you in handling long text entries of usual cells but also in displayingoutline nodes which are different from data rows This topic discusses these two scenarios in the following sectionsThese settings work on the grid level and does not need you to set AllowMerging property of specific row or column

Handle Spill in Normal CellsThis FlexGrid setting causes text that is too long to fit in a cell to spill into empty adjacent cells If you have a longentry in a cell and the adjacent cell is empty the entry spills onto the adjacent cells to occupy as much room as

FlexGrid for WinForms

147 Copyright copy GrapeCity Inc All rights reserved

needed This behavior can be achieved by setting the AllowMerging property to Spill For instance in the imagebelow long data strings from TestGroup column cells spill to the empty Flag column cells giving a better visibility ofdata while using the available space on the grid

Following code enables spilling of long text to adjacent empty cell in the WinForms FlexGrid

Handle Text in Node RowsThe Nodes setting is similar to Spill but only applies to outline nodes This setting is useful when data is organizedinto groups and the node rows contain information in a format different from the data rows For this you must setthe C1FlexGridAllowMerging property to Nodes

長いテキストを隣接する空のセルにこぼしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumSpill

C

長いテキストを隣接する空のセルにこぼしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumSpill

VBNET

FlexGrid for WinForms

148 Copyright copy GrapeCity Inc All rights reserved

Following code shows how to handle long text in node rows of the WinForms FlexGrid

ノード行の長いテキストを隣接する空のセルにスピルします c1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumNodes

C

ノード行の長いテキストを隣接する空のセルにスピルしますc1FlexGrid1AllowMerging = C1WinC1FlexGridAllowMergingEnumNodes

VBNET

カスタムのマージ

FlexGrid by default gives you enough options to merge in most common scenarios using AllowMerging propertyHowever there may be instances where you want to customize the merging options to get more out of your grid Youcan customize the default merging behavior in two ways

Method 1 Use IComparer InterfaceBy default the grid merges adjacent cells containing same non-null value In default scenario string comparisons arecase-sensitive and blanks are included However you can also merge cells using a case-insensitive comparison andtrimming blanks by writing a custom class that implements IComparer interface and assign it to CustomComparerproperty of the C1FlexGrid class

Method 2 Override the GetMergedRange MethodAnother way is to create a new class that derives from the C1FlexGrid class and overrides the GetMergedRangeand GetData methods to provide your own custom merging logic It merges the cells based on contextual

FlexGrid for WinForms

149 Copyright copy GrapeCity Inc All rights reserved

understanding of data in FlexGrid which is implemented through the overridden methods in the sample The belowexample demonstrates custom merging in timetable of each lecturer using the WinForms FlexGrid

public override CellRange GetMergedRange(int row int col bool clip) 結合のロジックで使用するID列のインデックスを保存します _colIndex = ColsIndexOf(LecturerID)

結合する時にカスタムデータを使用するようにフラグを設定します _doingMerge = true

基本クラスの結合のロジックを呼び出します(GetDataメソッドを使用してデータを取得します) CellRange cellRange = baseGetMergedRange(row col clip)

GetDataが通常どおりに動作するようにフラグをリセットします _doingMerge = false

結合された範囲を返します return cellRange

public override Object GetData(int row int col) 結合範囲を決定するためのデータを取得します ID列のコンテンツを追加して異なるIDの行のセルがマージされないようにします if (_doingMerge ampamp _colIndex gt -1 ampamp col = _colIndex) SystemDiagnosticsDebugWriteLine($rowcol) return baseGetDataDisplay(row col) + baseGetDataDisplay(row _colIndex)

C

FlexGrid for WinForms

150 Copyright copy GrapeCity Inc All rights reserved

For detailed implementation of more scenarios of custom merging see the product Projects named CustomMergeCustomMerge2 CustomMerge3 CustomMerge4

Note The abovementioned product samples are located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installingWinForms Edition using ComponentOneControlPanelexe

表示測定編集などするデータを取得します 基本クラスに通常どおり処理させます return baseGetData(row col)

Public Overrides Function GetMergedRange(ByVal row As Integer ByVal col As Integer ByVal clip As Boolean) As CellRange 結合のロジックで使用するID列のインデックスを保存します _colIndex = ColsIndexOf(LecturerID)

結合する時にカスタムデータを使用するようにフラグを設定します _doingMerge = True

基本クラスの結合のロジックを呼び出します(GetDataメソッドを使用してデータを取得します) Dim cellRange As CellRange = MyBaseGetMergedRange(row col clip)

GetDataが通常どおりに動作するようにフラグをリセットします _doingMerge = False

結合された範囲を返します Return cellRangeEnd Function

Public Overrides Function GetData(ByVal row As Integer ByVal col As Integer) As Object 結合範囲を決定するためのデータを取得します ID列のコンテンツを追加して異なるIDの行のセルがマージされないようにします If _doingMerge AndAlso _colIndex gt -1 AndAlso col ltgt _colIndex Then DebugWriteLine($rowcol) Return MyBaseGetDataDisplay(row col) + MyBaseGetDataDisplay(row _colIndex) End If

表示測定編集などするデータを取得します 基本クラスに通常どおり処理させます Return MyBaseGetData(row col)End Function

VBNET

FlexGrid for WinForms

151 Copyright copy GrapeCity Inc All rights reserved

グループ

Grouping refers to organizing the grid data into a hierarchical structure where rows with common column value aredisplayed as a group The feature also lets you expand or collapse the groups to facilitate easier analysis of grid data

In FlexGrid grouping can be achieved through code as well as through user interaction via column context menuand FlexGridGroupPanel control This topic discusses these ways and additional operations related to grouping

Grouping through CodeFlexGrid provides GroupDescriptions property to describe how data source items are grouped in the grid Thisproperty accepts the instance of any collection which implements IList interface (eg List) as its value The items of thecollection describe grouping using a property name as the criterion

Following code shows how to apply grouping in the WinForms FlexGrid through code

Grouping through Group Panel

CustomerIDでデータをグループ化しますc1FlexGrid1GroupDescriptions = new ListltGroupDescriptiongt() new GroupDescription(CustomerID)

C

CustomerIDでデータをグループ化しますc1FlexGrid1GroupDescriptions = New List(Of GroupDescription)() From New GroupDescription(CustomerID)

VBNET

FlexGrid for WinForms

152 Copyright copy GrapeCity Inc All rights reserved

FlexGrid also lets you create groups at runtime using an extension control named C1FlexGridGroupPanel which isprovided by the C1WinC1FlexGridGroupPanel assembly

To achieve grouping in FlexGrid at runtime add the C1FlexGridGroupPanel control to the form and bind it with thegrid to be bound using FlexGrid property of the C1FlexGridGroupPanel class Once a grid is bound to the grouppanel control you can drag and drop the columns to panel in order to group the grid by that column To create anested hierarchy of dragged columns you can drag multiple columns in the desired order You can also set themaximum number of groups allowed within FlexGrid using MaxGroups property of the C1FlexGridGroupPanel classBy default all the created groups appear in the expanded state To change this setting and display the groups incollapsed state by default you can set the AutoExpandAllGroups property to false The group panel control alsoprovides the Text property to display a string when no columns are dropped on the panel

Use the code below to apply grouping in WinForms FlexGrid through the FlexGridGroupPanel control

C1FlexGridGroupPanel c1FlexGridGroupPanel = new C1FlexGridGroupPanel()c1FlexGridGroupPanelBounds = new SystemDrawingRectangle(00 650 150)thisControlsAdd(c1FlexGridGroupPanel) C1FlexGridGroupPanelの一般プロパティを設定しますc1FlexGridGroupPanelFlexGrid = c1FlexGrid1c1FlexGridGroupPanelText = Drag the columns herec1FlexGridGroupPanelMaxGroups = 5c1FlexGridGroupPanelAutoExpandAllGroups = true

C

Dim c1FlexGridGroupPanel As C1FlexGridGroupPanel = New C1FlexGridGroupPanel() c1FlexGridGroupPanelBounds = New DrawingRectangle(0 0 650 150) MeControlsAdd(c1FlexGridGroupPanel)

VBNET

FlexGrid for WinForms

153 Copyright copy GrapeCity Inc All rights reserved

Grouping through Context MenuFlexGrid provides support for column context menu at run-time to facilitate quick actions related to columnoperations One of these context menu options is Group By This Column You can use this context menu option togroup the grid data by any of the columns at run-time Once grouping is applied you also get the Ungroup option toremove grouping To enable the column context menu you need to set ColumnContextMenuEnabled propertyprovided by the C1FlexGrid class to true By default this property is set to false

Grouping and MoreApart from the default features grouping in FlexGrid comes with many other options to give you ample flexibility tomeet your requirements

Use the SubtotalPosition property to change the position of group row which gets displayed above the groupby defaultSet the HideGroupedColumns property to true to hide the columns by which grid is groupedChange the format of group header by using the GroupHeaderFormat property By default the group row

C1FlexGridGroupPanelの一般プロパティを設定します c1FlexGridGroupPanelFlexGrid = c1FlexGrid1 c1FlexGridGroupPanelText = Drag the columns here c1FlexGridGroupPanelMaxGroups = 5 c1FlexGridGroupPanelAutoExpandAllGroups = True

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = true

C

列のコンテキストメニューを有効にしますc1FlexGrid1ColumnContextMenuEnabled = True

VBNET

FlexGrid for WinForms

154 Copyright copy GrapeCity Inc All rights reserved

displays a string of namevalue formatSet the C1FlexGridAllowMerging property to AllowMergingEnumNodes to spill the long group headercontent into the adjacent empty cells For more information see Handle Text in Node RowsDisplay aggregate value of columns in group header by using Aggregate property of the Column classUse AllowSorting property to sort the groups based on their valuesUse the GridTreeStyle property to customize the appearance of outline tree that shows the grouping inFlexGrid For more information see Style the Tree Grid

FlexGrid for WinForms

155 Copyright copy GrapeCity Inc All rights reserved

集計

Summarizing data is one of the most important features of the grid where you can easily group the similar data andcalculate various types of aggregates such as Sum Average Count Max Min and more

In FlexGrid you can easily summarize data by using SubTotal method of the C1FlexGrid class It adds subtotal rows thatcontain aggregate data for the regular (non-subtotal) rows and also supports the hierarchical aggregates The method hasvarious overloads which gives you enough flexibility to deal with multiple summarizing related scenarios All theseoverloads have one parameter in common that is AggregateEnum which lets you set the type of aggregate you want toimplement Other parameters in various overloads let you set the outline level start and end column and column thatcontains values to be aggregated

Create SubtotalsBelow example demonstrates the use of SubTotal method in the WinForms FlexGrid for calculation of average aggregatebased on Score column

Style SubtotalsWhen the Subtotal method adds the rows with the aggregate information it automatically assigns in-built subtotal styles

グリッドに存在する既存の小計をすべてクリアしますc1FlexGrid1Subtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加しますc1FlexGrid1Subtotal(AggregateEnumAverage 1 3 3 4 Average for 0)

C

グリッドに存在する既存の小計をすべてクリアしますc1FlexGrid1Subtotal(AggregateEnumClear)

レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加しますc1FlexGrid1Subtotal(AggregateEnumAverage 1 3 3 4 Average for 0)

VBNET

FlexGrid for WinForms

156 Copyright copy GrapeCity Inc All rights reserved

to the new rows You can customize the appearance of the subtotal rows by changing the properties of the outline stylesin the designer with the Style Editor or using the code Below example demonstrates styling of subtotals at three levels inthe WinForms FlexGrid

Customize SubtotalsFlexGrid in addition to built-in aggregate options lets you create custom expressions in bound mode and use them assubtotals in groups along with aggregates You can specify the custom expressions for a column using GroupExpressionproperty of the Column class Below example demonstrates how to create a custom expression as a subtotal for Qualifiedcolumn of the WinForms FlexGrid

小計をレベル0でスタイル設定しますCellStyle s = c1FlexGrid1Styles[CellStyleEnumSubtotal0]sBackColor = ColorBlacksForeColor = ColorWhitesFont = new Font(c1FlexGrid1Font FontStyleBold) 小計をレベル1でスタイル設定しますs = c1FlexGrid1Styles[CellStyleEnumSubtotal1]sBackColor = ColorDarkBluesForeColor = ColorWhite

小計をレベル2でスタイル設定しますs = c1FlexGrid1Styles[CellStyleEnumSubtotal2]sBackColor = ColorDarkRedsForeColor = ColorWhitec1FlexGrid1AutoSizeCols()

C

Dim s As CellStyle = c1FlexGrid1Styles(CellStyleEnumSubtotal0) sBackColor = ColorBlack sForeColor = ColorWhite sFont = New Font(c1FlexGrid1Font FontStyleBold)

s = c1FlexGrid1Styles(CellStyleEnumSubtotal1) sBackColor = ColorDarkBlue sForeColor = ColorWhite

s = c1FlexGrid1Styles(CellStyleEnumSubtotal2) sBackColor = ColorDarkRed sForeColor = ColorWhite c1FlexGrid1AutoSizeCols()

VBNET

FlexGrid for WinForms

157 Copyright copy GrapeCity Inc All rights reserved

public void CustomizeSubTotal(C1FlexGrid c1FlexGrid1) ListltGroupDescriptiongt grps = new ListltGroupDescriptiongt() 列「Course」のグループを作成します GroupDescription grp = new GroupDescription(Course ListSortDirectionDescending true) grpsAdd(grp) 上記のグループに従ってFlexGridをグループ化します c1FlexGrid1GroupDescriptions = grps カスタムの計算式を使用してFlexGridに新しい列を追加します var column = c1FlexGrid1ColsAdd() columnName = Qualified columnDataType = typeof(object) columnCaption = Qualified(gt5000) columnAllowEditing = false columnExpression = [Attendance] [Score] GroupExpression の実装 c1FlexGrid1Cols[Score]GroupExpression = =Average([Score]) c1FlexGrid1Cols[Attendance]GroupExpression = =Average([Attendance]) c1FlexGrid1Cols[Qualified]GroupExpression = =iif(Average([Score][Attendance])lt5000falsetrue) c1FlexGrid1AutoSizeCols()

C

Public Sub CustomizeSubTotal(ByVal c1FlexGrid1 As C1FlexGrid) Dim grps As List(Of GroupDescription) = New List(Of GroupDescription)() 列「Course」のグループを作成します Dim grp As GroupDescription = New GroupDescription(Course ListSortDirectionDescending True) grpsAdd(grp)

上記のグループに従ってFlexGridをグループ化します c1FlexGrid1GroupDescriptions = grps

カスタムの計算式を使用してFlexGridに新しい列を追加します Dim column = c1FlexGrid1ColsAdd()

VBNET

FlexGrid for WinForms

158 Copyright copy GrapeCity Inc All rights reserved

columnName = Qualified columnDataType = GetType(Object) columnCaption = Qualified(gt5000) columnAllowEditing = False columnExpression = [Attendance] [Score]

GroupExpression の実装 c1FlexGrid1Cols(Score)GroupExpression = =Average([Score]) c1FlexGrid1Cols(Attendance)GroupExpression = =Average([Attendance]) c1FlexGrid1Cols(Qualified)GroupExpression = =iif(Average([Score][Attendance])lt5000falsetrue) c1FlexGrid1AutoSizeCols()End Sub

FlexGrid for WinForms

159 Copyright copy GrapeCity Inc All rights reserved

ツリーグリッド

OverviewOne of the unique and popular features of the FlexGrid control is the ability to add hierarchical grouping to regulardata grid and display it in a tree like structure called Tree Grid The Tree Grid control is very similar to the one you seein a TreeView control It shows an indented structure with collapse or expand icon next to each node row so the usercan expand and collapse the outline to see the desired level of detail by clicking on the nodes

Although you can create simple outline trees using FlexGrid grouping Tree Grid helps you implement more advanceduse cases such as displaying customer and order details In a usual grid showing such data it is difficult to see thedetails of each customer and order In such case you can create a Tree Grid to group the data in a hierarchicalstructure for better view and accessibility of information

Quick BindingLoading data in a Tree Grid is exactly the same as loading in a regular grid If the data source is available at designtime you can use the Visual Studio Property Window to set the grids DataSource property of the C1FlexGrid class andbind the grid to the data without writing even a single line of code For detailed steps see Bound Mode

You can also set the DataSource property through code Following code shows how to use the DataSource propertyto populate data in the WinForms Tree Grid

private void Bound_Node_Load(object sender EventArgs e) FlexGridを連結します BindGrid(_gridBound)

public void BindGrid(C1FlexGrid grid) DataTable _dt = new DataTable() データを取得します var fields = Country City SalesPerson Quantity ExtendedPrice var sql = stringFormat(SELECT 0 FROM Invoices ORDER BY 0 fields)

C

FlexGrid for WinForms

160 Copyright copy GrapeCity Inc All rights reserved

The code uses an OleDbDataAdapter to fill a DataTable with data then assigns datatable to DataSource property ofthe grid To turn this regular grid in a Tree grid you need to insert the node rows which is discussed in the sectionbelow

Create Nodes (Bound and Unbound Mode)To create a Tree Grid FlexGrid introduces a concept of Node rows These rows do not contain regular data and aresimply header rows under which similar data is grouped just like nodes in a usual TreeView control You can alsodefine the hierarchy of these nodes by setting the Level property These nodes can be collapsed and expanded to hideor show the data they contain The Tree Grid can be displayed in any column defined by the GridTreeColumnproperty By default this property is set to -1 which causes the tree not to be displayed at all

Bound Mode (Using InsertNode Method)

You can create node rows using InsertNode method of the RowCollection class which inserts a new node row at a

var da = new OleDbDataAdapter(sql GetConnectionString()) daFill(_dt) グリッドにデータを連結します gridDataSource = _dt ExtendedPrice 列を書式設定します gridCols[ExtendedPrice]Format = n2

static string GetConnectionString() string path = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) + ComponentOne SamplesCommon string conn = provider=microsoftjetoledb40data source=0c1nwindmdb return stringFormat(conn path)

Private Sub Bound_Node_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを連結します BindGrid(_gridBound) End Sub

Public Sub BindGrid(ByVal grid As C1FlexGrid) Dim _dt As DataTable = New DataTable() データを取得します Dim fields = Country City SalesPerson Quantity ExtendedPrice Dim sql = StringFormat(SELECT 0 FROM Invoices ORDER BY 0 fields) Dim da = New OleDbDataAdapter(sql GetConnectionString()) daFill(_dt) グリッドにデータを連結します gridDataSource = _dt ExtendedPrice 列を書式設定します gridCols(ExtendedPrice)Format = n2 End Sub

Private Shared Function GetConnectionString() As String Dim path As String = EnvironmentGetFolderPath(EnvironmentSpecialFolderPersonal) amp ComponentOne SamplesCommon Dim conn As String = provider=microsoftjetoledb40data source=0c1nwindmdb Return StringFormat(conn path) End Function

VBNET

FlexGrid for WinForms

161 Copyright copy GrapeCity Inc All rights reserved

specified index This is the low-level way of inserting totals and building outlines

The GroupBy method used here inserts node rows by grouping identical values To obtain a Node object you caneither use return value of the InsertNode method or retrieve the node for an existing row using the IsNode property

Use the following code to create nodes using InsertNode method in the bound WinForms Tree Grid

private void Bound_Node_Load(object sender EventArgs e) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) GroupBy(_gridBound Country 0) GroupBy(_gridBound City 1) public void CreateTree(C1FlexGrid grid) gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)

void GroupBy(C1FlexGrid grid string columnName int level) レベル0でグループのスタイル設定します CellStyle s0 = gridStylesAdd(Group0) s0BackColor = ColorGray s0ForeColor = ColorWhite s0Font = new Font(gridFont FontStyleBold) レベル1でグループのスタイル設定します CellStyle s1 = gridStylesAdd(Group1) s1BackColor = ColorLightGray s1ForeColor = ColorBlack object current = null for (int r = gridRowsFixed r lt gridRowsCount r++)

C

FlexGrid for WinForms

162 Copyright copy GrapeCity Inc All rights reserved

if (gridRows[r]IsNode) var value = grid[r columnName] if (objectEquals(value current)) 値が変更されました ノードを挿入します gridRowsInsertNode(r level) if (level == 0) gridRows[r]Style = s0 else if (level == 1) gridRows[r]Style = s1 最初のスクロール可能な列にグループ名を表示します grid[r gridColsFixed] = value 現在の値を更新します current = value gridAutoSizeCols()

Private Sub Bound_Node_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) GroupBy(_gridBound Country 0) GroupBy(_gridBound City 1)End Sub

Public Sub CreateTree(ByVal grid As C1FlexGrid) gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)End Sub

Private Sub GroupBy(ByVal grid As C1FlexGrid ByVal columnName As String ByVal level As Integer) レベル0でグループのスタイル設定します Dim s0 As CellStyle = gridStylesAdd(Group0) s0BackColor = ColorGray s0ForeColor = ColorWhite s0Font = New Font(gridFont FontStyleBold) レベル1でグループのスタイル設定します Dim s1 As CellStyle = gridStylesAdd(Group1) s1BackColor = ColorLightGray s1ForeColor = ColorBlack Dim current As Object = Nothing Dim r As Integer = gridRowsFixed

While r And lt gridRowsCount End While

r += 1

If True Then

If Not gridRows(r)IsNode Then Dim value = grid(r columnName)

VBNET

FlexGrid for WinForms

163 Copyright copy GrapeCity Inc All rights reserved

The code also calls the AutoSizeCols method to ensure that the column is wide enough to accommodate the TreeGrid Finally it calls the GridTreeShow method to display the nodes

Also the Node class provides following methods and properties based on TreeView object model which can be usedto manage the Tree Grid

Checked Gets or sets the check state of cell defined by NodeRow and GridTreeColumnCollapsedExpanded Gets or sets collapsed or expanded state of the nodeData Gets or sets value in the cell defined by NodeRow and GridTreeColumnImage Gets or sets image in the cell defined by NodeRow and GridTreeColumnLevel Gets or sets node level in the Tree Grid

You can also explore the outline structure using the following properties and methods

Children Gets number of child nodes under this nodeGetCellRange Gets the CellRange object that described range of rows that belong to this nodeGetNode Gets the node that has a given relationship to this node (parent first child next sibling and so on)Nodes Gets a node array containing child nodes of this node

Bound Mode (Using Subtotal Method)

In bound mode another way to create nodes is using the Subtotal method To make the Tree Grid really useful thenode rows must include summary information for the data they contain

If you create Tree Grid using the Subtotal method the subtotals are added automatically The method scans theentire grid and automatically inserts node rows with optional subtotals at locations where the grid data changes

This is the high-level way of inserting totals and building outlines

If Not ObjectEquals(value current) Then 値が変更されました ノードを挿入します gridRowsInsertNode(r level)

If level = 0 Then gridRows(r)Style = s0 ElseIf level = 1 Then gridRows(r)Style = s1 End If

最初のスクロール可能な列にグループ名を表示します grid(r gridColsFixed) = value 現在の値を更新します current = value End If End IfEnd If gridAutoSizeCols()End Sub

FlexGrid for WinForms

164 Copyright copy GrapeCity Inc All rights reserved

The first parameter of the Subtotal method is AggregateEnum enumeration which calculates various types ofaggregates like Sum Average Count Max Min and others In the code below Subtotal method of the C1FlexGridclass is used for creating nodes in a bound WinForms Tree Grid

private void SubtotalNode_Bound_Load(object sender EventArgs e) FlexGridを取得します BindGrid(_gridBound) shows Tree in Bound FlexGrid CreateTree(_gridBound) 連結されたFlexGridに小計を作成します CreateSubTotal(_gridBound)public void BindGrid(C1FlexGrid grid) DataTable dt = new DataTable() dtColumnsAdd(ID typeof(int)) dtColumnsAdd(Name typeof(string)) dtColumnsAdd(Course typeof(string)) dtColumnsAdd(Score typeof(int)) dtColumnsAdd(Attendance typeof(int)) dtColumnsAdd(Country typeof(string)) サンプルデータ dtRowsAdd(1 Helen Bennett ComputerScience 79 84 Spain) dtRowsAdd(2 Ana Trujillo Biology 78 87 Mexico) dtRowsAdd(3 Antonio Moreno Aeronautics 71 70 Spain) dtRowsAdd(4 Paolo Accorti Biology 74 63 Spain) dtRowsAdd(5 Elizabeth Brown ComputerScience 80 93 Mexico) dtRowsAdd(6 Jaime Yorres Biology 61 48 Spain) dtRowsAdd(7 Yvonne Moncada Aeronautics 85 78 Mexico) dtRowsAdd(8 Martine Ranceacute Aeronautics 67 81 Spain) dtRowsAdd(9 Sergio Gutieacuterrezy ComputerScience 62 58 Mexico) dtRowsAdd(10 Thomas Hardy Aeronautics 94 92 Mexico) dtRowsAdd(11 Patricio Simpson Aeronautics 46 52 Spain) dtRowsAdd(12 Maria Anders ComputerScience 85 73 Spain) gridDataSource = dt gridAutoSizeCols() (gridDataSource as DataTable)DefaultViewSort = Course

C

FlexGrid for WinForms

165 Copyright copy GrapeCity Inc All rights reserved

FlexGridでツリーを作成しますpublic void CreateTree(C1FlexGrid grid) gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1) gridAutoSizeCols()public void CreateSubTotal(C1FlexGrid grid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加します gridSubtotal(AggregateEnumAverage 1 3 3 4 Average for 0) gridAutoSizeCols()

Private Sub SubtotalNode_Bound_Load(ByVal sender As Object ByVal e As EventArgs) FlexGridを取得します BindGrid(_gridBound) 連結されたFlexGridにツリーを表示します CreateTree(_gridBound) Creates Subtotal(s) in Bound FlexGrid CreateSubTotal(_gridBound)End Sub

Public Sub BindGrid(ByVal grid As C1FlexGrid) Dim dt As DataTable = New DataTable() dtColumnsAdd(ID GetType(Integer)) dtColumnsAdd(Name GetType(String)) dtColumnsAdd(Course GetType(String)) dtColumnsAdd(Score GetType(Integer)) dtColumnsAdd(Attendance GetType(Integer)) dtColumnsAdd(Country GetType(String))

サンプルデータ dtRowsAdd(1 Helen Bennett ComputerScience 79 84 Spain) dtRowsAdd(2 Ana Trujillo Biology 78 87 Mexico) dtRowsAdd(3 Antonio Moreno Aeronautics 71 70 Spain) dtRowsAdd(4 Paolo Accorti Biology 74 63 Spain) dtRowsAdd(5 Elizabeth Brown ComputerScience 80 93 Mexico) dtRowsAdd(6 Jaime Yorres Biology 61 48 Spain) dtRowsAdd(7 Yvonne Moncada Aeronautics 85 78 Mexico) dtRowsAdd(8 Martine Ranceacute Aeronautics 67 81 Spain) dtRowsAdd(9 Sergio Gutieacuterrezy ComputerScience 62 58 Mexico) dtRowsAdd(10 Thomas Hardy Aeronautics 94 92 Mexico) dtRowsAdd(11 Patricio Simpson Aeronautics 46 52 Spain) dtRowsAdd(12 Maria Anders ComputerScience 85 73 Spain) gridDataSource = dt gridAutoSizeCols() TryCast(gridDataSource DataTable)DefaultViewSort = CourseEnd Sub

FlexGridでツリーを作成しますPublic Sub CreateTree(ByVal grid As C1FlexGrid) gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridTreeShow(1)

VBNET

FlexGrid for WinForms

166 Copyright copy GrapeCity Inc All rights reserved

Unbound Mode (Using Subtotal Method)

The Subtotal method is a very convenient and flexible way to create a tree grid It has a number of overloads thatallow you to specify which columns are to be grouped on and totaled on by index or by name whether to include acaption in the node rows that it inserts how to perform the grouping and so on

In the code below Subtotal method of the C1FlexGrid class is used for creating nodes in an unbound WinForms TreeGrid

gridAutoSizeCols()End Sub

Public Sub CreateSubTotal(ByVal grid As C1FlexGrid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) レベル1グループ「Course」列集計(平均)ScoreAttendanceでグリッドに小計を追加します gridSubtotal(AggregateEnumAverage 1 3 3 4 Average for 0) gridAutoSizeCols()End Sub

private void Unbound_Subtotal_Load(object sender EventArgs e) 連結されていないFlexGridにデータを追加します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) 連結されていないFlexGridに小計を作成します CreateSubTotal(_gridUnbound) public void PopulateGrid(C1FlexGrid grid) グリッドにデータを入力します Random rnd = new Random() gridRowsCount = 14 grid[0 1] = Direction grid[0 2] = Region CellRange rg = gridGetCellRange(0 3 0 gridColsCount - 1) rgData = Rnd

C

FlexGrid for WinForms

167 Copyright copy GrapeCity Inc All rights reserved

for (int r = 1 r lt gridRowsCount r++) grid[r 0] = r grid[r 1] = (r lt 7) Inbound Outbound grid[r 2] = (r lt 3) North (r lt 7) South (r lt 10) East West for (int c = 3 c lt gridColsCount c++) grid[r c] = rndNext(1000) gridCols[c]Format = gridAutoSizeCols()

FlexGridでツリーを作成しますprivate void ShowTreeNode(C1FlexGrid grid) ツリーを作成します gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols()

Creates Subtotal in FlexGridpublic void CreateSubTotal(C1FlexGrid grid) Clears any existing subtotal(s) present in grid gridSubtotal(AggregateEnumClear) for (int c = 3 c lt gridColsCount c++) Adds subtotals in grid gridSubtotal(AggregateEnumSum 0 -1 c Grand Total) gridSubtotal(AggregateEnumSum 2 2 c Total for 0) gridAutoSizeCols()

Private Sub Unbound_Subtotal_Load(ByVal sender As Object ByVal e As EventArgs) 連結されていないFlexGridにデータを追加します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) 連結されていないFlexGridに小計を作成します CreateSubTotal(_gridUnbound) End Sub

Public Sub PopulateGrid(ByVal grid As C1FlexGrid) グリッドにデータを入力します Dim rnd As Random = New Random() gridRowsCount = 14 grid(0 1) = Direction grid(0 2) = Region Dim rg As CellRange = gridGetCellRange(0 3 0 gridColsCount - 1) rgData = Rnd Dim r As Integer = 1

While r And lt gridRowsCount End While

VBNET

FlexGrid for WinForms

168 Copyright copy GrapeCity Inc All rights reserved

r += 1

If True Then grid(r 0) = r grid(r 1) = r And lt 7 Inbound Outbound grid(r 2) = r And lt 3 North r And lt 7 South r And lt 10 East West Dim c As Integer = 3

While c And lt gridColsCount End While

c += 1

If True Then grid(r c) = rnd[Next](1000) gridCols(c)Format = End If End If

gridAutoSizeCols() End Sub

FlexGridでツリーを作成します Private Sub ShowTreeNode(ByVal grid As C1FlexGrid) ツリーを作成しますFlexGridでツリーを作成します gridTreeColumn = 1 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols() End Sub

FlexGridで小計を作成します Public Sub CreateSubTotal(ByVal grid As C1FlexGrid) グリッドに存在する既存の小計をすべてクリアします gridSubtotal(AggregateEnumClear) Dim c As Integer = 3

While c And lt gridColsCount End While

c += 1

If True Then グリッドに小計を追加します gridSubtotal(AggregateEnumSum 0 -1 c Grand Total) gridSubtotal(AggregateEnumSum 2 2 c Total for 0) End If

gridAutoSizeCols() End Sub

FlexGrid for WinForms

169 Copyright copy GrapeCity Inc All rights reserved

Unbound Mode(Using IsNode Property)

In an unbound grid you can turn regular rows into node rows by simply setting the IsNode property to true If youtry to turn a regular data bound row into a node it causes the grid to throw an exception

Use the following code to create nodes using IsNode property in an unbound WinForms Tree Grid

private void Unbound_Row_Load(object sender EventArgs e) 連結されていないFlexGridにデータを入力します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound)

private void PopulateGrid(C1FlexGrid grid) FlexGridをリセットします gridRowsCount = 0 gridColsCount = 2 string fileName = testxml xmlドキュメントをロードします XmlDocument xdoc = new XmlDocument() xdocLoad(fileName) XMLドキュメントを読み取りFlexGridのノードとして表示します ShowNode(_gridUnbound xdocChildNodes[1] 0) gridAutoSizeCols() FlexGridでツリーを作成しますprivate void ShowTreeNode(C1FlexGrid grid) ツリーを作成します gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols()

FlexGridにxmlノードを追加しますprivate void ShowNode(C1FlexGrid grid XmlNode node int level)

C

FlexGrid for WinForms

170 Copyright copy GrapeCity Inc All rights reserved

コメントノードをスキップします if (nodeNodeType == XmlNodeTypeComment) return 読み取りxmlノードの新しい行を追加します int row = gridRowsCount gridRowsAdd() グリッドのセルにxmlノードデータを割り当てます grid[row 0] = nodeName xmlノードに子が1つしかないかどうかを確認します if (nodeChildNodesCount == 1) グリッドのセルにノード値を設定します grid[row 1] = nodeInnerText 新しい行をノードにします gridRows[row]IsNode = true gridRows[row]NodeLevel = level ノードに子がある場合はそれらも取得します if (nodeChildNodesCount gt 1) 子を取得するために再帰します foreach (XmlNode child in nodeChildNodes) ShowNode(_gridUnbound child level + 1)

Private Sub Unbound_Row_Load(ByVal sender As Object ByVal e As EventArgs) 連結されていないFlexGridにデータを入力します PopulateGrid(_gridUnbound) 連結されていないFlexGridにツリーを表示します ShowTreeNode(_gridUnbound) End Sub

Private Sub PopulateGrid(ByVal grid As C1FlexGrid) FlexGridをリセットします gridRowsCount = 0 gridColsCount = 2 Dim fileName As String = testxml xmlドキュメントをロードします Dim xdoc As XmlDocument = New XmlDocument() xdocLoad(fileName) XMLドキュメントを読み取りFlexGridのノードとして表示します ShowNode(_gridUnbound xdocChildNodes(1) 0) gridAutoSizeCols() End Sub

FlexGridでツリーを作成します Private Sub ShowTreeNode(ByVal grid As C1FlexGrid) ツリーを作成します gridTreeColumn = 0 gridTreeStyle = TreeStyleFlagsSimpleLeaf gridAutoSizeCols() End Sub

FlexGridにxmlノードを追加します Private Sub ShowNode(ByVal grid As C1FlexGrid ByVal node As XmlNode ByVal level As Integer) コメントノードをスキップします If nodeNodeType Is XmlNodeTypeComment Then Return

VBNET

FlexGrid for WinForms

171 Copyright copy GrapeCity Inc All rights reserved

読み取りxmlノードの新しい行を追加します Dim row As Integer = gridRowsCount gridRowsAdd() グリッドのセルにxmlノードデータを割り当てます grid(row 0) = nodeName

xmlノードに子が1つしかないかどうかを確認します If nodeChildNodesCount = 1 Then グリッドのセルにノード値を設定します grid(row 1) = nodeInnerText End If

新しい行をノードにします gridRows(row)IsNode = True gridRows(row)NodeLevel = level

ノードに子がある場合はそれらも取得します If nodeChildNodesCount And gt Then End If

1

If True Then

子を取得するために再帰します For Each child As XmlNode In nodeChildNodes ShowNode(_gridUnbound child level + 1) Next End If End Sub

ノードの操作

Tree Grid not only allows you to present the data in a structured form but it also supports performing variousoperations with the nodes You can add delete move and fetch nodes by using various methods provided bythe Node class

FlexGrid for WinForms

172 Copyright copy GrapeCity Inc All rights reserved

Add NodeYou can add a node at a specific position in the Tree Grid using AddNode method of the Node class This appends anew node row to the collection The method takes NodeTypeEnum enumeration as its argument which lets youspecify a node with respect to another given node

The code below shows how to add a node in the WinForms Tree Grid at a specific location

private void cmbAdd_SelectionChangeCommitted(object sender SystemEventArgs e) 現在の行ノードを取得します Node nd = flexRows[flexRow]Node ユーザーの要求に応じて相対を追加します (could be a child or a sibling) ndAddNode((NodeTypeEnum)(cmbAddSelectedIndex + 2) cmbAddText) flexFocus()

C

Private Sub cmbAdd_SelectionChangeCommitted(ByVal sender As Object ByVal e As EventArgs) 現在の行ノードを取得します Dim nd As Node = flexRows(flexRow)Node ユーザーの要求に応じて相対を追加します (could be a child or a sibling) ndAddNode(CType(cmbAddSelectedIndex + 2 NodeTypeEnum) cmbAddText)

VBNET

FlexGrid for WinForms

173 Copyright copy GrapeCity Inc All rights reserved

Delete NodeYou can delete a selected node from the Tree Grid using RemoveNode method of the Node class

Following code demonstrates how to delete a node from the WinForms Tree Grid

Move NodeThe Tree Grid allows you to move the node rows to a new position using Move method of the Node class Themethod takes NodeMoveEnum enumeration as an argument which lets you specify the direction in which node hasto be moved

Use the code below to move a node of the WinForms Tree Grid to a new position

flexFocus()End Sub

private void btnDelete_Click(object sender SystemEventArgs e) 現在のノードを取得します Node nd = null if ( flexRowsCount gt 0 ampamp flexRow gt= 0 ampamp flexRow lt flexRowsCount) nd = flexRows[flexRow]Node if (nd = null) FlexGridからノードを削除します ndRemoveNode() flexFocus()

C

Private Sub btnDelete_Click(ByVal sender As Object ByVal e As EventArgs) 現在のノードを取得します Dim nd As Node = Nothing

If flexRowsCount gt 0 AndAlso flexRow gt= 0 AndAlso flexRow lt flexRowsCount Then nd = flexRows(flexRow)Node End If

If nd IsNot Nothing Then FlexGridからノードを削除します ndRemoveNode() flexFocus() End IfEnd Sub

VBNET

private void btnMove_Click(object sender SystemEventArgs e) 現在の行のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択した動きを適用します

C

FlexGrid for WinForms

174 Copyright copy GrapeCity Inc All rights reserved

Select NodesIn Tree Grid you can select the nodes to perform different operations using GetNode method of the Node class Themethod takes a parameter called NodeTypeEnum enumeration which specifies a node with respect to another givennode

The code below specifies how to fetch a specific node of the WinForms Tree Grid and show it in selected state

(これにより選択したノードが移動します) if (sender == btnMoveOut) ndMove(NodeMoveEnumOut) else if (sender == btnMoveIn) ndMove(NodeMoveEnumIn) else if (sender == btnMoveUp) ndMove(NodeMoveEnumUp) else if (sender == btnMoveDown) ndMove(NodeMoveEnumDown) else if (sender == btnMoveFirst) ndMove(NodeMoveEnumFirst) else if (sender == btnMoveLast) ndMove(NodeMoveEnumLast) ノードがまだ表示されていることを確認します ndEnsureVisible() flexFocus()

Private Sub btnMove_Click(ByVal sender As Object ByVal e As EventArgs) 現在の行のノードを取得します Dim nd As Node = flexRows(flexRow)Node

ユーザーが選択した動きを適用します (これにより選択したノードが移動します) If sender Is btnMoveOut Then ndMove(NodeMoveEnumOut) ElseIf sender Is btnMoveIn Then ndMove(NodeMoveEnum[In]) ElseIf sender Is btnMoveUp Then ndMove(NodeMoveEnumUp) ElseIf sender Is btnMoveDown Then ndMove(NodeMoveEnumDown) ElseIf sender Is btnMoveFirst Then ndMove(NodeMoveEnumFirst) ElseIf sender Is btnMoveLast Then ndMove(NodeMoveEnumLast) End If

ノードがまだ表示されていることを確認します ndEnsureVisible() flexFocus()End Sub

VBNET

private void cmbSelect_SelectionChangeCommitted(object sender SystemEventArgs e) 現在の行のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択したノードを取得します nd = ndGetNode((NodeTypeEnum)cmbSelectSelectedIndex) 失敗した場合はメッセージを表示します if (nd == null) MessageBoxShow(Cant find + cmbSelectText + for this node) return ノードを選択しそれが表示されていることを確認します(スクロールして表示します)

C

FlexGrid for WinForms

175 Copyright copy GrapeCity Inc All rights reserved

Expand and Collapse NodesYou can expand and collapse all nodes in your Tree Grid application using the Collapsed property of Node class asshown in the code below This feature makes it convenient to navigate through node headers as a group whenrequired

Following code shows how to expand and collapse nodes of the WinForms Tree Grid

ndSelect() ndEnsureVisible() flexFocus()

Private Sub cmbSelect_SelectionChangeCommitted(ByVal sender As Object ByVal e As EventArgs) 現在の行のノードを取得します Dim nd As Node = flexRows(flexRow)Node ユーザーが選択したノードを取得します nd = ndGetNode(CType(cmbSelectSelectedIndex NodeTypeEnum))

失敗した場合はメッセージを表示します If nd Is Nothing Then MessageBoxShow(Cant find amp cmbSelectText amp for this node) Return End If

ノードを選択しそれが表示されていることを確認します(スクロールして表示します) nd[Select]() ndEnsureVisible() flexFocus()End Sub

VBNET

foreach (Row row in flexRowsCastltRowgt()Where(rw =gt rwIsNode == true)) Node node = rowNode nodeCollapsed = false

foreach (Row row in flexRowsCastltRowgt()Where(rw =gt rwIsNode == true)) Node node = rowNode nodeCollapsed = true

C

For Each row As Row In flexRowsCast(Of Row)()Where(Function(rw) rwIsNode = True) Dim node As Node = rowNode nodeCollapsed = False Next

For Each row As Row In flexRowsCast(Of Row)()Where(Function(rw) rwIsNode = True) Dim node As Node = rowNode nodeCollapsed = True Next

VBNET

FlexGrid for WinForms

176 Copyright copy GrapeCity Inc All rights reserved

Drag and Drop NodesIn Tree Grid you can drag and drop a selected node to a specific position by handling the MouseUp MouseDownand MouseMove events

The code below lets the user drag and drop nodes of the WinForms Tree Grid

private void flex_MouseDown(object sender MouseEventArgs e) m_DragInfocheckDrag = false 左ボタンを押すと移動しません ドラッグするマウスの追跡を開始します if (eButton = MouseButtonsLeft) return if (chkDragChecked || m_DragInfodragging) return if (flexMouseRow lt flexRowsFixed || flexMouseCol = 0) return 現在の行とマウスの位置を保存します m_DragInforow = flexRow m_DragInfomouseDown = new Point(eX eY) チェックを開始します m_DragInfocheckDrag = true

private void flex_MouseMove(object sender MouseEventArgs e) チェックしてユーザーが許容範囲を超えた場合はドラッグを開始します if (m_DragInfocheckDrag || eButton = MouseButtonsLeft) return if (MathAbs(eX - m_DragInfomouseDownX) + MathAbs(eY - m_DragInfomouseDownY) lt= DRAGTOL) return フラグを更新します m_DragInfodragging = true Sets cursor and highlight node CellStyle cs = flexStyles[SourceNode] flexCursor = CursorsNoMove2D flexSetCellStyle(m_DragInforow 0 cs) ここにドロップできるかどうかを確認します Cursor c = (NoDropHere()) CursorsNo CursorsNoMove2D if (c = flexCursor) flexCursor = c private bool NoDropHere() カーソルの下の行は無効です if (flexMouseRow lt flexRowsFixed) return true カーソルの下の列が無効です if (flexMouseCol lt flexColsFixed) return true if (flexGetDataDisplay(flexRow 0) == SKU) return true return false private void flex_MouseUp(object sender MouseEventArgs e) マウスが再び下がるまでチェックしないでください m_DragInfocheckDrag = false Not dragging were done if (m_DragInfodragging) return ドラッグを停止します m_DragInfodragging = false flexSetCellStyle(m_DragInforow 0 (CellStyle)null) flexCursor = CursorsDefault ドロップが許可されているかどうかをテストします

C

FlexGrid for WinForms

177 Copyright copy GrapeCity Inc All rights reserved

if (NoDropHere()) return ノードを新しい親ノードに移動します Node ndSrc = flexRows[m_DragInforow]Node Node ndDst = flexRows[flexRow]Node ndSrcMove(NodeMoveEnumChildOf ndDst) ndSrcSelect()

internal struct DRAGINFO public bool dragging 現在ドラッグ中 public bool checkDrag 現在マウスをチェックしてドラッグを開始しています public int row ドラッグされている行のインデックス public Point mouseDown マウスダウンの位置

Private Sub flex_MouseDown(ByVal sender As Object ByVal e As MouseEventArgs) m_DragInfocheckDrag = False 左ボタンを押すと移動しません ドラッグするマウスの追跡を開始します If eButton IsNot MouseButtonsLeft Then Return If Not chkDragChecked OrElse m_DragInfodragging Then Return If flexMouseRow lt flexRowsFixed OrElse flexMouseCol ltgt 0 Then Return 現在の行とマウスの位置を保存します m_DragInforow = flexRow m_DragInfomouseDown = New Point(eX eY) チェックを開始します m_DragInfocheckDrag = True End Sub

Private Sub flex_MouseMove(ByVal sender As Object ByVal e As MouseEventArgs) チェックしてユーザーが許容範囲を超えた場合はドラッグを開始します If Not m_DragInfocheckDrag OrElse eButton IsNot MouseButtonsLeft Then Return If MathAbs(eX - m_DragInfomouseDownX) + MathAbs(eY - m_DragInfomouseDownY) lt= DRAGTOL Then Return フラグを更新します m_DragInfodragging = True カーソルを設定しノードを強調表示します Dim cs As CellStyle = flexStyles(SourceNode) flexCursor = CursorsNoMove2D flexSetCellStyle(m_DragInforow 0 cs) ここにドロップできるかどうかを確認します Dim c As Cursor = If((NoDropHere()) CursorsNo CursorsNoMove2D) If c IsNot flexCursor Then flexCursor = c End Sub

Private Function NoDropHere() As Boolean カーソルの下の行は無効です If flexMouseRow lt flexRowsFixed Then Return True カーソルの下の列が無効です If flexMouseCol lt flexColsFixed Then Return True If flexGetDataDisplay(flexRow 0) Is SKU Then Return True Return False End Function

Private Sub flex_MouseUp(ByVal sender As Object ByVal e As MouseEventArgs) マウスが再び下がるまでチェックしないでください m_DragInfocheckDrag = False If Not m_DragInfodragging Then Return ドラッグを停止します m_DragInfodragging = False

VBNET

FlexGrid for WinForms

178 Copyright copy GrapeCity Inc All rights reserved

flexSetCellStyle(m_DragInforow 0 CType(Nothing CellStyle)) flexCursor = Cursors[Default] ドロップが許可されているかどうかをテストします If NoDropHere() Then Return ノードを新しい親ノードに移動します Dim ndSrc As Node = flexRows(m_DragInforow)Node Dim ndDst As Node = flexRows(flexRow)Node ndSrcMove(NodeMoveEnumChildOf ndDst) ndSrc[Select]() End Sub

Friend Structure DRAGINFO Public dragging As Boolean 現在ドラッグ中 Public checkDrag As Boolean 現在マウスをチェックしてドラッグを開始しています Public row As Integer ドラッグされている行のインデックス Public mouseDown As Point マウスダウンの位置 End Structure

データの操作

In Tree Grid just like a usual grid you can also perform various operations at data level such as sorting and retainingthe changes

SortingTo apply sorting in Tree Grid you can select the parent node and sort the child nodes using Sort Method of the NodeClass You can specify the sorting order by using the SortFlags enumeration

Following code applies sorting on the WinForms Tree Grid

FlexGrid for WinForms

179 Copyright copy GrapeCity Inc All rights reserved

Retain the ChangesSo far we have discussed how to create trees and totals using the high-level Subtotal method as well as lower-level InsertNode and Aggregate methods

At this point it is important to remember that the Tree Grid is created based on the data but is not bound to it in anyway and is not automatically maintained when there are changes to the grid or to the data

For example if the user modifies a value in the column the subtotals will not be automatically updated If the usersorts the grid it refreshes the data and the subtotals disappear

There are two common ways to maintain the Tree Grid

1 Prevent the user from making any changes that would invalidate the tree This is the easiest option You can setthe grids AllowEditing AllowDragging and AllowSorting properties to false and prevent any changes thatwould affect the tree

2 Update the tree when there are changes to the data or to the grid You can attach handlers to thegrids AfterDataRefresh AfterSort and AfterEdit events and re-generate the outline appropriately

The second option is usually more interesting as it provides a quick and simple tool for dynamic data analysis Thisapproach is illustrated by a product sample Analyze shipped with the FlexGrid control The sample creates an initialoutline and allows users to reorder the columns When the column order changes the sample automatically re-sortsthe data and re-creates the outline

Note The abovementioned product sample is located at DocumentsComponentOneSamplesWinFormsvxxxC1FlexGridCS on your system if you have installed the samples while installing

private void btnSort_Click(object sender SystemEventArgs e) 現在のノードを取得します Node nd = flexRows[flexRow]Node ユーザーが選択した並べ替えを適用します (これにより選択したノードの子が並べ替えられます) if (sender == btnSortAscending) ndSort(SortFlagsAscending) else ndSort(SortFlagsDescending) 完了 flexFocus()

C

Private Sub btnSort_Click(ByVal sender As Object ByVal e As EventArgs) 現在のノードを取得します Dim nd As Node = flexRows(flexRow)Node

ユーザーが選択した並べ替えを適用します (これにより選択したノードの子が並べ替えられます) If sender Is btnSortAscending Then ndSort(SortFlagsAscending) Else ndSort(SortFlagsDescending) End If

完了 flexFocus()End Sub

VBNET

FlexGrid for WinForms

180 Copyright copy GrapeCity Inc All rights reserved

WinForms Edition using ComponentOneControlPanelexe

In Create Nodes section we also learnt about implementing GroupBy method that inserts node rows groupingidentical values on a given column The code scans all the columns skipping existing node rows so it can be called toadd several levels of nodes and keeps track of the current value for the column being grouped on When the currentvalue changes a node row is inserted showing the new group name in the first scrollable column

However there are some challenges to maintain the grouping like the method assumes that data is sorted accordingto the outline structure Also the GroupBy method may insert rows which would cause the grid to flicker To avoidthis you would normally set the Redraw property to false before making the updates and set it back to true whendone

The DeferRefresh class is a simple utility that sets the grids Redraw property to false and restores its original valuewhen it is disposed This ensures that Redraw is properly restored even when exceptions happen during the updatesThe BindGrid method ensures that the grid is sorted in the order required by our outline structure

ツリーグリッドのカスタマイズ

FlexGrid allows you to customize Tree Grid by styling as well as by using various elements like checkboxes toexpandcollapse nodes or images as node icons A customized Tree Grid can make the outline tree nodes look moredistinctive and structured making it visually appealing and more understandable

Style Tree GridStyling a Tree Grid is similar to styling the FlexGrid control The Tree property returns a reference to a GridTree objectthat exposes several methods and properties used to customize the Tree Grid Following is the list of some commonlyused properties

Column Gets or sets the index of the column that contains the outline tree Setting this property to -1 causesthe outline tree to be hidden from the usersIndent Gets or sets the indent in pixels between adjacent node levels Higher indent levels cause the tree tobecome widerStyle Gets or sets the type of outline tree to display Use this property to determine whether the tree shouldinclude a button bar at the top to allow users to collapseexpand the entire tree whether lines andor symbolsshould be displayed and whether lines should be displayed connecting the tree to data rows as well as noderowsLineColor Gets or sets the color of the connecting linesLineStyle Gets or sets the style of the connecting lines

For more information on styling the tree grid see Styling and Appearance topic in FlexGrid documentation

Display Tree with CheckBoxesTo create a custom Tree Grid with checkbox and images you need to first initialize FlexGrid for creating Tree Grid andthen add nodes to the tree by using AddNode method of the RowCollection class

Now to implement checkboxes in Tree Grid you need to maintain the checkboxes in parent and child nodes Thismethod uses Checked property of the Node class which defines whether to show a checkbox for the node or not

FlexGrid for WinForms

181 Copyright copy GrapeCity Inc All rights reserved

The code below shows how to display checkboxes on tree nodes of the WinForms Tree Grid

void c1FlexGrid1_CellChecked(object sender C1WinC1FlexGridRowColEventArgs e) すべての子にチェック値を適用します var node = thisc1FlexGrid1Rows[eRow]Node UpdateCheckChildren(node) 親にチェック値を適用します UpdateCheckParent(node)

void UpdateCheckChildren(C1WinC1FlexGridNode node) var checkState = nodeChecked foreach (C1WinC1FlexGridNode child in nodeNodes) childChecked = checkState UpdateCheckChildren(child)

void UpdateCheckParent(C1WinC1FlexGridNode node) このノードの親を取得します var parent = nodeParent if (parent = null)

C

FlexGrid for WinForms

182 Copyright copy GrapeCity Inc All rights reserved

チェックされたチェックされていない子をカウントします int cntChecked = 0 int cntUnchecked = 0 int cntGrayed = 0 foreach (C1WinC1FlexGridNode child in parentNodes) switch (childChecked) case C1WinC1FlexGridCheckEnumChecked cntChecked++ break case C1WinC1FlexGridCheckEnumUnchecked cntUnchecked++ break case C1WinC1FlexGridCheckEnumGrayed cntGrayed++ break 親のチェック状態を更新します if (cntGrayed gt 0 || (cntChecked gt 0 ampamp cntUnchecked gt 0)) parentChecked = C1WinC1FlexGridCheckEnumGrayed else if (cntChecked gt 0 ampamp cntUnchecked == 0) parentChecked = C1WinC1FlexGridCheckEnumChecked else if (cntUnchecked gt 0 ampamp cntChecked == 0) parentChecked = C1WinC1FlexGridCheckEnumUnchecked 祖父も更新します UpdateCheckParent(parent)

Private Sub c1FlexGrid1_CellChecked(ByVal sender As Object ByVal e As C1WinC1FlexGridRowColEventArgs) すべての子にチェック値を適用します Dim node = Mec1FlexGrid1Rows(eRow)Node UpdateCheckChildren(node) 親にチェック値を適用します UpdateCheckParent(node) End Sub

Private Sub UpdateCheckChildren(ByVal node As C1WinC1FlexGridNode) Dim checkState = nodeChecked

For Each child As C1WinC1FlexGridNode In nodeNodes childChecked = checkState MeUpdateCheckChildren(child) Next End Sub

Private Sub UpdateCheckParent(ByVal node As C1WinC1FlexGridNode) このノードの親を取得します Dim parent = nodeParent

If parent IsNot Nothing Then チェックされたチェックされていない子をカウントします

VBNET

FlexGrid for WinForms

183 Copyright copy GrapeCity Inc All rights reserved

Display Tree with ImagesTo add the images as your Tree Grid node icons you can use the AddImageFolder method for creating nodes relatedto files and assigning images to the nodes

Dim cntChecked As Integer = 0 Dim cntUnchecked As Integer = 0 Dim cntGrayed As Integer = 0

For Each child As C1WinC1FlexGridNode In parentNodes

Select Case childChecked Case C1WinC1FlexGridCheckEnumChecked cntChecked += 1 Case C1WinC1FlexGridCheckEnumUnchecked cntUnchecked += 1 Case C1WinC1FlexGridCheckEnumGrayed cntGrayed += 1 End Select Next

親のチェック状態を更新します If cntGrayed gt 0 OrElse cntChecked gt 0 AndAlso cntUnchecked gt 0 Then parentChecked = C1WinC1FlexGridCheckEnumGrayed ElseIf cntChecked gt 0 AndAlso cntUnchecked = 0 Then parentChecked = C1WinC1FlexGridCheckEnumChecked ElseIf cntUnchecked gt 0 AndAlso cntChecked = 0 Then parentChecked = C1WinC1FlexGridCheckEnumUnchecked End If

祖父も更新します UpdateCheckParent(parent) End If End Sub

FlexGrid for WinForms

184 Copyright copy GrapeCity Inc All rights reserved

Use the code below to display images or icons along with nodes of the WinForms Tree Grid

void AddImageFolder(string path int level) int cnt = 0 try ディレクトリ内のすべてのファイルをループします foreach (string file in DirectoryGetFiles(path)) ファイルごとにノードを作成しFlexGridに追加します var node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(file) 画像をノードに割り当てるためのコード ShowImage(node file) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt++ if (cnt gt 20) break catch try パスのすべてのサブディレクトリをループします foreach (string subPath in DirectoryGetDirectories(path))

C

FlexGrid for WinForms

185 Copyright copy GrapeCity Inc All rights reserved

ファイルごとにノードを作成しFlexGridに追加します var node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(subPath) 画像をノードに割り当てるためのコード ShowImage(node subPath) 現在のディレクトリのサブディレクトリファイルをトラバースします AddImageFolder(subPath level + 1) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt++ if (cnt gt 20) break catch

Private Sub AddImageFolder(ByVal path As String ByVal level As Integer) Dim cnt As Integer = 0

Try

ディレクトリ内のすべてのファイルをループします For Each file As String In DirectoryGetFiles(path) ファイルごとにノードを作成しFlexGridに追加します Dim node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(file)

画像をノードに割り当てるためのコード ShowImage(node file) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt += 1 If cnt gt 20 Then Exit For Next

Catch End Try

Try

パスのすべてのサブディレクトリをループします For Each subPath As String In DirectoryGetDirectories(path) ファイルごとにノードを作成しFlexGridに追加します Dim node = c1FlexGrid2RowsAddNode(level) 作成されたノードのデータを設定します nodeData = PathGetFileName(subPath) 画像をノードに割り当てるためのコード ShowImage(node subPath) 現在のディレクトリのサブディレクトリファイルをトラバースします AddImageFolder(subPath level + 1) 各ディレクトリから(最大で)20個のファイルのみを表示します cnt += 1 If cnt gt 20 Then Exit For Next

Catch End TryEnd Sub

VBNET

FlexGrid for WinForms

186 Copyright copy GrapeCity Inc All rights reserved

The above code uses a custom method called ShowImage to set the image for nodes based on its file extensions

public void ShowImage(C1WinC1FlexGridNode node string path) パスからファイル拡張子を取得します string extension = PathGetExtension(path) パスがファイルに属している場合 if (extension = ) ファイル拡張子に基づいてノードの画像を設定します switch (extension) case txt nodeImage = PropertiesResourcesTxt break case resx nodeImage = PropertiesResourcesTxt break case licx nodeImage = PropertiesResourcesTxt break case cs nodeImage = PropertiesResourcesTxt break case vb nodeImage = PropertiesResourcesTxt break case exe nodeImage = PropertiesResourcesExe break case dll nodeImage = PropertiesResourcesDll break case sln nodeImage = PropertiesResourcesVS break case csproj nodeImage = PropertiesResourcesVS break case bmp nodeImage = PropertiesResourcesImg break case png nodeImage = PropertiesResourcesImg break case gif nodeImage = PropertiesResourcesVideo break case accdb nodeImage = PropertiesResourcesAccess break default nodeImage = PropertiesResourcesUnknown break それ以外のパスはディレクトリフォルダに属しています else nodeImage = PropertiesResourcesFolder

C

FlexGrid for WinForms

187 Copyright copy GrapeCity Inc All rights reserved

Public Sub ShowImage(ByVal node As C1WinC1FlexGridNode ByVal path As String) パスからファイル拡張子を取得します Dim extension As String = PathGetExtension(path)

パスがファイルに属している場合 If Not Equals(extension ) Then

ファイル拡張子に基づいてノードの画像を設定します Select Case extension Case txt nodeImage = PropertiesResourcesTxt Case resx nodeImage = PropertiesResourcesTxt Case licx nodeImage = PropertiesResourcesTxt Case cs nodeImage = PropertiesResourcesTxt Case vb nodeImage = PropertiesResourcesTxt Case exe nodeImage = PropertiesResourcesExe Case dll nodeImage = PropertiesResourcesDll Case sln nodeImage = PropertiesResourcesVS Case csproj nodeImage = PropertiesResourcesVS Case bmp nodeImage = PropertiesResourcesImg Case png nodeImage = PropertiesResourcesImg Case gif nodeImage = PropertiesResourcesVideo Case accdb nodeImage = PropertiesResourcesAccess Case Else nodeImage = PropertiesResourcesUnknown それ以外のパスはディレクトリフォルダに属しています End Select Else nodeImage = PropertiesResourcesFolder End IfEnd Sub

VBNET

FlexGrid for WinForms

188 Copyright copy GrapeCity Inc All rights reserved

クリップボード

FlexGrid provides flexibility to perform various clipboard operations such as cut copy and paste on the editable griddata To enable automatic handling of common clipboard keys you need to set the AutoClipboard property to trueThe property handles following clipboard operations and their corresponding keys

Copy CTRL+C Ctrl+INS

Cut CTRL+X SHIFT+DEL

Paste CTRL+V SHIFT+INS

Delete DEL

The abovementioned clipboard operations do not have any affect on the styles and images and only work on gridheaders and data You can choose which part of the selected content to copy out of row header column headerand data by using the ClipboardCopyMode property When a datamap or multicolumn combobox exists in thecopied range only the display value is copied Also note that hidden cells are also copied when copying a cellrange To exclude hidden cells from copying see Exclude Hidden Cells

The code below demonstrates how to enable clipboard operations in the WinForms FlexGrid

Clipboard Operations through CodeYou can also perform clipboard operations through code The example below shows how to perform copying andpasting operations on button click

Use the code below to perform the clipboard operations through code in the WinForms FlexGrid

キーボードからクリップボード操作を有効にします c1FlexGrid1AutoClipboard = true データとすべてのヘッダーをコピーするようにコピーモードを設定します c1FlexGrid1ClipboardCopyMode = C1WinC1FlexGridClipboardCopyModeEnumDataAndAllHeaders

C

キーボードからクリップボード操作を有効にしますc1FlexGrid1AutoClipboard = True

データとすべてのヘッダーをコピーするようにコピーモードを設定しますc1FlexGrid1ClipboardCopyMode = C1WinC1FlexGridClipboardCopyModeEnumDataAndAllHeaders

VBNET

private void CopyButton_Click(object sender EventArgs e) クリップボードにコピーするグリッドのデータのみをコピーできるようにします c1FlexGrid1ClipboardCopyMode = ClipboardCopyModeEnumDataOnly

Clipプロパティに改行コードを追加しクリップボードに設定します ClipboardSetDataObject(c1FlexGrid1Clip + r) MessageBoxShow($Copied Range [c1FlexGrid1Rowc1FlexGrid1Col]-[c1FlexGrid1RowSelc1FlexGrid1ColSel])

C

FlexGrid for WinForms

189 Copyright copy GrapeCity Inc All rights reserved

Exclude Hidden CellsIn FlexGrid by default hidden cells are also copied when copying a cell range through keyboard operations enabledusing the AutoClipboard property However you can exclude the hidden rows and columns by using the code below

Following code shows how you can exclude the hidden cells from clipboard operations performed on the WinFormsTree Grid

private void PasteButton_Click(object sender EventArgs e) クリップボードのテキストを取得します IDataObject data = ClipboardGetDataObject() if (dataGetDataPresent(DataFormatsText)) string str1 str2 クリップボードからデータを取得します str1 = (string)dataGetData(DataFormatsText)

クリップボードから最後の行のフィードコードを削除します str2 = str1Remove(str1Length - 1 1)

範囲を選択してデータを貼り付けます c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col c1FlexGrid1RowsCount - 1 c1FlexGrid1ColsCount - 1 true) c1FlexGrid1Clip = str2 c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col)

Private Sub CopyButton_Click(ByVal sender As Object ByVal e As EventArgs) クリップボードにコピーするグリッドのデータのみをコピーできるようにします c1FlexGrid1ClipboardCopyMode = ClipboardCopyModeEnumDataOnly

Clipプロパティに改行コードを追加しクリップボードに設定します ClipboardSetDataObject(c1FlexGrid1Clip amp MicrosoftVisualBasicConstantsvbCr) MessageBoxShow($Copied Range [c1FlexGrid1Rowc1FlexGrid1Col]-[c1FlexGrid1RowSelc1FlexGrid1ColSel])End Sub

Private Sub PasteButton_Click(ByVal sender As Object ByVal e As EventArgs) クリップボードのテキストを取得します Dim data As IDataObject = ClipboardGetDataObject()

If dataGetDataPresent(DataFormatsText) Then Dim str1 str2 As String クリップボードからデータを取得します str1 = CStr(dataGetData(DataFormatsText))

クリップボードから最後の行のフィードコードを削除します str2 = str1Remove(str1Length - 1 1)

範囲を選択してデータを貼り付けます c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col c1FlexGrid1RowsCount - 1 c1FlexGrid1ColsCount - 1 True) c1FlexGrid1Clip = str2 c1FlexGrid1Select(c1FlexGrid1Row c1FlexGrid1Col) End If

VBNET

C

FlexGrid for WinForms

190 Copyright copy GrapeCity Inc All rights reserved

列を非表示にしますc1FlexGrid1Cols[2]Visible = falsec1FlexGrid1AutoClipboard = true

次にCtrl + Cを押す前に非表示の列を含むいくつかのセルを選択しますprivate void c1FlexGrid1_KeyDown_1(object sender KeyEventArgs e) [Ctrl + C]でコピーします if ((eControl == true) ampamp (eKeyCode == KeysC)) 自動処理が行われないためキー入力を無効にします eHandled = true 選択したセル範囲のCellRangeオブジェクトを取得します C1WinC1FlexGridCellRange cr cr = c1FlexGrid1Selection

string StrCopy = for (int i = crr1 i lt= crr2 i++) if (c1FlexGrid1Rows[i]Visible == true) for (int j = crc1 j lt= crc2 j++) if (c1FlexGrid1Cols[j]Visible == true) StrCopy = StrCopy + c1FlexGrid1[i j]ToString() if (j = crc2) StrCopy = StrCopy + t StrCopy = StrCopy + n クリップボードに設定します ClipboardSetDataObject(StrCopy) MessageBoxShow(Copied data n + StrCopy)

列を非表示にします c1FlexGrid1Cols(2)Visible = False c1FlexGrid1AutoClipboard = True

次にCtrl + Cを押す前に非表示の列を含むいくつかのセルを選択しますPrivate Sub c1FlexGrid1_KeyDown_1(ByVal sender As Object ByVal e As KeyEventArgs)

[Ctrl + C]でコピーします If eControl = True AndAlso eKeyCode = KeysC Then 自動処理が行われないためキー入力を無効にします eHandled = True 選択したセル範囲のCellRangeオブジェクトを取得します Dim cr As C1WinC1FlexGridCellRange cr = c1FlexGrid1Selection Dim StrCopy =

VBNET

FlexGrid for WinForms

191 Copyright copy GrapeCity Inc All rights reserved

For i = crr1 To crr2

If c1FlexGrid1Rows(i)Visible = True Then For j = crc1 To crc2

If c1FlexGrid1Cols(j)Visible = True Then StrCopy = StrCopy amp c1FlexGrid1(i j)ToString()

If j ltgt crc2 Then StrCopy = StrCopy amp MicrosoftVisualBasicConstantsvbTab End If End If Next

StrCopy = StrCopy amp MicrosoftVisualBasicConstantsvbLf End If Next クリップボードに設定します ClipboardSetDataObject(StrCopy) MessageBoxShow(Copied data amp MicrosoftVisualBasicConstantsvbLf amp StrCopy) End IfEnd Sub

FlexGrid for WinForms

192 Copyright copy GrapeCity Inc All rights reserved

保存ロードと印刷

FlexGrid provides various built-in options so that you can easily save a grid and its content in a text excel or an XML file You can even load these saved filesto another grid or can save it as backup of a particular state of the grid You can also save the grid image in your desired format Not just this you can alsoprint the grid or selected areas of the grid if you need to have a hard copy This topic discusses various options related save load and print available in thegrid

Topic Content

Save Discusses about how to save the grid and its contents in different formats

Save as Text FileSave as Excel FileSave as XMLSave as Image

Load Discusses about how to load grid content from various file formats

Load from Text FileLoad from Excel FileLoad from DatabaseLoad from XML

Print Discusses about how to print the grid and other print related options

Print GridPrint OptionsCustomize Print Preview Dialog

保存

FlexGrid provides various methods to save the grid in the desired format such as text excel xml and image formatsThis feature is enabled through an assembly named C1WinC1FlexGridImportExportdll hence you need to addreference to this assembly to save the grid

Save as Text FileTo save grid content as a text file you can use the SaveGrid method of the Extensions class The method hasparameters that let you choose delimiter encoding and also lets you specify which portion of grid should be savedThe resulting text files can later be loaded back into the control or into other applications that support comma or tab-delimited files such as Microsoft Excel

Following code shows how to save content of the WinForms FlexGrid as a text file

private void btnSaveTxt_Click(object sender EventArgs e) c1FlexGrid1SaveGrid(ExportedGridtxt FileFormatEnumTextComma FileFlagsAsDisplayed | FileFlagsIncludeFixedCells)

C

Private Sub btnSaveTxt_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1SaveGrid(ExportedGridtxt FileFormatEnumTextComma FileFlagsAsDisplayed Or FileFlagsIncludeFixedCells)End Sub

VBNET

FlexGrid for WinForms

193 Copyright copy GrapeCity Inc All rights reserved

Save as Excel FileTo save grid as an excel file you can use the abovementioned SaveGrid method and simply set the format parameterto FileFormatEnumExcel You dont need to have Microsoft Excel installed on your computer However SaveGridmethod can only save the data in a workbook with single worksheet

To get an additional control over how you save your data to an excel file you can use the SaveExcel method insteadIn this case the process of saving excel files converts most data types and formatting information including row andcolumn dimensions fonts colors formats and cell alignment However some other features such as frozen andmerged cells images data maps and cell borders are not translated while converting to an excel file

Use the code below to save the WinForms FlexGrid as an Excel file

Save as XMLTo serialize grid contents into an XML document you can simply call WriteXML method of the C1FlexGrid class andparse path of the XML document as a parameter The method serializes all grid contents into the Xml documentincluding the data stored in the cells row and column properties styles and images Objects of custom types storedin the grid are also serialized as long as they have an associated SystemComponentModelTypeConverter thatprovides conversions to and from string

Below code demonstrates how to save contents of the WinForms FlexGrid to an XML document

Save as ImageTo save a grid as an image you can create the grid image using CreateImage method of the C1FlexGrid class andsave that image object at the specified path You can also specify a cell range or pass a cell range object as itsparameter to save a specific portion of the grid as an image

Use the code below to save the WinForms FlexGrid as an image

private void btnSaveExcl_Click(object sender EventArgs e) c1FlexGrid1SaveExcel(ExportedGridxlsx FileFlagsAsDisplayed | FileFlagsIncludeFixedCells)

C

Private Sub btnSaveExcl_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1SaveExcel(ExportedGridxlsx FileFlagsAsDisplayed Or FileFlagsIncludeFixedCells)End Sub

VBNET

private void btnSaveXML_Click(object sender EventArgs e) c1FlexGrid1WriteXml(ExportedGridxml)

C

Private Sub btnSaveXML_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1WriteXml(ExportedGridxml)End Sub

VBNET

FlexGrid for WinForms

194 Copyright copy GrapeCity Inc All rights reserved

private void btnSaveImg_Click(object sender EventArgs e) Image gridImage = c1FlexGrid1CreateImage() gridImageSave(ExportedGridpng)

C

Private Sub btnSaveImg_Click(ByVal sender As Object ByVal e As EventArgs) Dim gridImaage As Image = c1FlexGrid1CreateImage() gridImaageSave(ExportedGridpng)End Sub

VBNET

ロード

FlexGrid not only lets you save the grid to various formats but also lets you load data from various formats such textexcel XML or databases This feature is enabled through an assembly named C1WinC1FlexGridImportExportdllhence you need to add reference to this assembly to load the grid with data from these sources

Load from Text FileTo load data from a text file FlexGrid provides LoadGrid method of the Extensions class The method has parametersthat let you choose delimiter encoding etc You can also load text files saved using SaveGrid method When loadingtext files rows and columns are added to the grid if needed to accommodate the file contents The method supportsformats such as comma-delimited text files (CSV format) tab-delimited text files and even MS Excel files (xls)

Following code shows how to populate data in the WinForms FlexGrid by loading it from a text file

Load from Excel FileTo load grid from an excel file you can use the abovementioned LoadGrid method and simply set the formatparameter to FileFormatEnumExcel You dont need to have Microsoft Excel installed on your computer However theLoadGrid method can only load the data from first worksheet of a workbook

To get an additional control over how you load your data from an excel file you can use the LoadExcel methodinstead In this case the process of loading excel files converts most data types and formatting information includingrow and column dimensions fonts colors formats and cell alignment However there are still some exceptions Forexample the grid loads the values in excel cells but cannot load the underlying formulas Other features such asfrozen and merged cells images data maps and cell borders are not translated either

Use the code below to load contents in the WinForms FlexGrid from an excel file

private void btnLoadTxt_Click(object sender EventArgs e) c1FlexGrid1LoadGrid(ExportedGridtxt FileFormatEnumTextComma )

C

Private Sub btnLoadTxt_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1LoadGrid(ExportedGridtxt FileFormatEnumTextComma)End Sub

VBNET

FlexGrid for WinForms

195 Copyright copy GrapeCity Inc All rights reserved

Load from DatabaseTo load grid data from a database you can use the DataReader objects This process is different from data bindingwhich keeps a live connection between one or more controls and the underlying data source

Below code demonstrates how to load contents in the WinForms FlexGrid from the database

private void btnLoadExcl_Click(object sender EventArgs e) c1FlexGrid1LoadExcel(ExportedGridxlsx)

C

Private Sub btnLoadExcl_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1LoadExcel(ExportedGridxlsx)End Sub

VBNET

private void btnLoadDB_Click(object sender EventArgs e) DataReaderを準備します string strConn = data source=MYMACHINEinitial catalog=Northwind SystemDataSqlClientSqlConnection myConn = new SystemDataSqlClientSqlConnection(strConn) SystemDataSqlClientSqlCommand myCMD = new SystemDataSqlClientSqlCommand(SELECT FROM Employees myConn) myConnOpen() SystemDataSqlClientSqlDataReader myReader = myCMDExecuteReader()

DBスキーマからグリッド構造を構築します DataTable dt = myReaderGetSchemaTable() c1FlexGrid1ColsCount = 1 foreach (DataRow dr in dtRows) Column c =c1FlexGrid1ColsAdd() cCaption = cName = (string)dr[ColumnName] cDataType = (Type)dr[DataType]

グリッドにデータを入力します c1FlexGrid1RowsCount = 1 int row = 1 int cols = dtColumnsCount object[] v = (object[])ArrayCreateInstance(typeof(object) cols) while (myReaderRead()) myReaderGetValues(v) c1FlexGrid1AddItem(v row++ 1)

クリーンアップします c1FlexGrid1AutoSizeCols() myReaderClose() myConnClose()

C

FlexGrid for WinForms

196 Copyright copy GrapeCity Inc All rights reserved

Load from XMLTo deserialize grid contents from an XML document you can simply call ReadXML method of the C1FlexGrid classand parse path of the XML document as a parameter

Use the code below to load contents for the WinForms FlexGrid from an XML document

Private Sub btnLoadDB_Click(ByVal sender As Object ByVal e As EventArgs) DataReaderを準備します Dim strConn As String = data source=MYMACHINEinitial catalog=Northwind Dim myConn As New SqlClientSqlConnection(strConn) Dim myCMD As New SqlClientSqlCommand(SELECT FROM Employees myConn) myConnOpen() Dim myReader As SqlClientSqlDataReader = myCMDExecuteReader() DBスキーマからグリッド構造を構築します Dim dt As DataTable = myReaderGetSchemaTable() _flexColsCount = 1 Dim dr As DataRow For Each dr In dtRows Dim c As C1WinC1FlexGridColumn = _flexColsAdd() cCaption =(cName lt= CStr(dr(ColumnName))) cDataType = CType(dr(DataType) Type) Next dr グリッドにデータを入力します _flexRowsCount = 1 Dim row As Integer = 1 Dim cols As Integer = dtColumnsCount Dim v As Object() = CType(ArrayCreateInstance(GetType(Object) cols) Object()) While myReaderRead() myReaderGetValues(v) _flexAddItem(v row + 1 1) End While クリーンアップします _flexAutoSizeCols() myReaderClose() myConnClose()End Sub

VBNET

private void btnLoadXML_Click(object sender EventArgs e) c1FlexGrid1ReadXml(ExportedGridxml)

C

Private Sub btnLoadXML_Click(ByVal sender As Object ByVal e As EventArgs) c1FlexGrid1ReadXml(ExportedGridxml)End Sub

VBNET

FlexGrid for WinForms

197 Copyright copy GrapeCity Inc All rights reserved

印刷

FlexGrid lets you print the grid and perform various basic and advanced print settings using its built-in methods andproperties

Print GridFlexGrid provides PrintGrid method of the C1FlexGrid class which lets you print the grid contents with some basicprinting options The method has an optional parameter PrintGridFlags that allows you to specify how to print thegrid such as its scaling mode and whether to display various print related dialog boxes You can also set text in headerand footer of the printed grid using this method

Following code shows how to use PrintGrid method to print the WinForms FlexGrid

Print OptionsTo set advanced printing options such as header and footer fonts page margins and page orientation you can usePrintParameter property of the C1FlexGrid class

Use the code below to print the WinForms FlexGrid with advanced print options

プレビューダイアログを表示し指定したヘッダとフッターでグリッドを印刷しますc1FlexGrid1PrintGrid(C1FlexGrid PrintGridFlagsFitToPageWidth | PrintGridFlagsShowPreviewDialog C1FlexGridtt + StringFormat(DateTimeNowToString() d) ttPage 0 of 1)

C

プレビューダイアログを表示し指定したヘッダとフッターでグリッドを印刷しますc1FlexGrid1PrintGrid(C1FlexGrid PrintGridFlagsFitToPageWidth Or PrintGridFlagsShowPreviewDialog C1FlexGrid amp vbTab amp vbTab amp StringFormat(DateNowToString() d) vbTab amp vbTab amp Page 0 of 1)

VBNET

FlexGrid for WinForms

198 Copyright copy GrapeCity Inc All rights reserved

Customize Print Preview DialogYou can customize the print preview dialog by using PrintPreviewDialog property of the GridPrinter class Theproperty can be accessed through PrintParameter property of the C1FlexGrid class The code below uses thePrintPreviewDialog property to display a maximized preview dialog with a custom caption

Below code demonstrates how to customize the print preview dialog of the WinForms FlexGrid

グリッドのPrintDocumentオブジェクトを取得しますSystemDrawingPrintingPrintDocument pd = c1FlexGrid1PrintParametersPrintDocument

ページを設定します(横向き15 左マージン)pdDefaultPageSettingsLandscape = truepdDefaultPageSettingsMarginsLeft = 150

ヘッダとフッタのフォントを設定しますc1FlexGrid1PrintParametersHeaderFont = new Font(Arial Black 14 FontStyleBold)c1FlexGrid1PrintParametersFooterFont = new Font(Arial Narrow 8 FontStyleItalic)

C

グリッドのPrintDocumentオブジェクトを取得しますDim pd As DrawingPrintingPrintDocument = c1FlexGrid1PrintParametersPrintDocument

ページを設定します(横向き15 左マージン)pdDefaultPageSettingsLandscape = TruepdDefaultPageSettingsMarginsLeft = 150

ヘッダとフッタのフォントを設定しますc1FlexGrid1PrintParametersHeaderFont = New Font(Arial Black 14 FontStyleBold)c1FlexGrid1PrintParametersFooterFont = New Font(Arial Narrow 8 FontStyleItalic)

VBNET

Form dlg = c1FlexGrid1PrintParametersPrintPreviewDialog as Form dlgText = Order Details dlgStartPosition = FormStartPositionCenterParent dlgWindowState = FormWindowStateMaximized c1FlexGrid1PrintGrid(Orders PrintGridFlagsShowPreviewDialog)

C

Dim dlg As Form = TryCast(c1FlexGrid1PrintParametersPrintPreviewDialog Form) dlgText = Order Details dlgStartPosition = FormStartPositionCenterParent dlgWindowState = FormWindowStateMaximized c1FlexGrid1PrintGrid(Orders PrintGridFlagsShowPreviewDialog)

VBNET

FlexGrid for WinForms

199 Copyright copy GrapeCity Inc All rights reserved

外観とスタイル設定

FlexGrid provides built-in visual styles as well as various design time and run time options so that you can style the grid and its elements as per the needsand appearance of your application The grid also provides style editors to let you customize appearance of your grid without writing a single line of codeFor more information about these editors and design time styling see Editors

This section discusses the built-in options provided by FlexGrid as well as various other ways to customize the appearance of grid and its elements

Topic Snapshot Content

Built-in Options Discusses about the available visual styles and built-in collection of styles

Visual StylesStyles Collection

Custom Styles Discusses how to create and apply the custom styles

Approach 1 Style an ObjectApproach 2 Create Re-usable Style

Customize Grid Discusses about customization at grid level

Set Alternate RowSet Background Image

Customize Border Discusses about customization of cell borders at row column or grid level

Customize Grid BorderCustomize RowColumn BorderCustomize Cell Border

Customize Text Discusses about various aspects of styling the grid text

Change FontSet MarginSet Vertical TextWrap TextDisplay Trimmed TextAlign TextApply Text Effect

Custom Glyphs Discusses about applying custom glyphs in the grid

組み込みオプション

Visual StylesFlexGrid provides six built-in visual styles so that you can easily customize the appearance of FlexGrid based on any ofthe Microsoft Office 2007 and 2010 themes These visual styles can be accessed through VisualStyle property ofthe C1FlexGrid class Apart from MS Office based visual styles you can also set this property to Custom and SystemWhen set to Custom the grid does not apply any visual styles and uses the grid properties for rendering When theproperty is set to System the grid renders its appearance based on current system settings

FlexGrid for WinForms

200 Copyright copy GrapeCity Inc All rights reserved

The property can be set using designer as well as through code To set the property at design time click smart tag toopen the C1FlexGrid Tasks menu and select a visual style from the VisualStyle combobox To apply visual style in theWinForms FlexGrid through code use the code below

Styles CollectionFlexGrid provides built-in collection of styles for predefined cell types and states such as normal cells fixed cellsfocused cells and so on You can use these built-in styles at design time as well as through code In design view youcan access these styles through the C1FlexGrid Style Editor which can be opened by clicking Styles option in Tasksmenu This collection of styles is represented by the CellStyleCollection class which can be accessed through Stylesproperty of the C1FlexGrid class Each built-in style is an object of the CellStyle class and holds various propertiessuch as BackColor DataType and Format

Following code shows how to use the styles from Styles collection of the WinForms FlexGrid

視覚スタイルをOffice2010Blueスキームに設定しますc1FlexGrid1VisualStyle = VisualStyleOffice2010Blue

C

視覚スタイルをOffice2010Blueスキームに設定しますc1FlexGrid1VisualStyle = VisualStyleOffice2010Blue

VBNET

組み込みセルスタイルNormalのプロパティを設定しますc1FlexGrid1Styles[Normal]BackColor = ColorAzurec1FlexGrid1Styles[Normal]ForeColor = ColorBlueViolet

固定セルの背景色を設定しますc1FlexGrid1Styles[Fixed]BackColor = ColorAqua

C

FlexGrid for WinForms

201 Copyright copy GrapeCity Inc All rights reserved

You can also add your own custom styles to Styles collection by using the Add method For more information abouthow to create and apply custom styles to grid cells see Custom Styles

組み込みセルスタイルNormalのプロパティを設定しますc1FlexGrid1Styles(Normal)BackColor = ColorAzurec1FlexGrid1Styles(Normal)ForeColor = ColorBlueViolet

固定セルの背景色を設定しますc1FlexGrid1Styles(Fixed)BackColor = ColorAqua

VBNET

カスタムのスタイル

Approach 1 Style an ObjectTo style a specific row column or a cell range of the WinForms FlexGrid you can use StyleNew property of the rowcolumn or cell range object

This approach is useful for styling a particular object when style is not expected to be reused To reuse a particularstyle you must create a style using the CellStyle object as discussed in the section below

Approach 2 Create Re-usable StyleIn this approach you can create a custom style as an object of CellStyle class and add it to the Styles collection usingthe Add method Then define its properties and apply it to a row column or cell range whenever required Asmentioned above this approach is very useful when you need to repeatedly use a particular style

Use the code below to create re-usable custom styles for your WinForms FlexGrid

特定の行にカスタムスタイルを適用しますc1FlexGrid1Rows[1]StyleNewBackColor = ColorAzurec1FlexGrid1Rows[1]StyleNewForeColor = ColorBlueViolet

C

特定の行にカスタムスタイルを適用しますc1FlexGrid1Rows(1)StyleNewBackColor = ColorAzurec1FlexGrid1Rows(1)StyleNewForeColor = ColorBlueViolet

VBNET

新しいスタイルを作成しスタイルコレクションに追加しますCellStyle cs = thisc1FlexGrid1StylesAdd(Custom) 新しいカスタムスタイルのプロパティを定義しますcsBackColor = ColorAzurecsForeColor = ColorBlueViolet

行にカスタムスタイルを適用しますc1FlexGrid1Rows[1]Style = cs

C

VBNET

FlexGrid for WinForms

202 Copyright copy GrapeCity Inc All rights reserved

新しいスタイルを作成しスタイルコレクションに追加しますDim cs As CellStyle = Mec1FlexGrid1StylesAdd(Custom)

新しいカスタムスタイルのプロパティを定義しますcsBackColor = ColorAzurecsForeColor = ColorBlueViolet

行にカスタムスタイルを適用しますc1FlexGrid1Rows(1)Style = cs

グリッドのカスタマイズ

FlexGrid also lets you customize overall look of the grid not to just increase its aesthetic value but also increases itsreadability You can add the alternate rows which make the grid more readable Also you can set image for instance awatermark or a company logo in background of the grid

Set Alternate RowTo set the alternate row color and styles in the grid you can use the built-in style Alternate either at design time orat runtime To apply style at design time you need to access the FlexGrid Style Editor and set properties for Alternatestyle

To apply alternate row style in the WinForms FlexGrid through code you need to use the CellStyle item Alternate ofthe CellStyleCollection class and set various properties for setting the alternate style

代替行の前色を設定します c1FlexGrid1Styles[Alternate]ForeColor = ColorWhite

代替行の背景色を設定します c1FlexGrid1Styles[Alternate]BackColor = ColorCadetBlue

C

FlexGrid for WinForms

203 Copyright copy GrapeCity Inc All rights reserved

Set Background Image in GridTo set the background image on a grid you can use the BackgroundImage property and assign the path of the imagefile to it Another property called BackgroundImageLayout property lets you choose whether and how to renderimage on the grid

Use the code below to set the background image on the WinForms FlexGrid

代替行の前色を設定しますc1FlexGrid1Styles(Alternate)ForeColor = ColorWhite

代替行の背景色を設定しますc1FlexGrid1Styles(Alternate)BackColor = ColorCadetBlue

VBNET

背景画像をグリッドに設定しますc1FlexGrid1BackgroundImage = ImageFromFile(CIMG-20190524-WA0037png)c1FlexGrid1BackgroundImageLayout = ImageLayoutStretch

C

背景画像をグリッドに設定しますc1FlexGrid1BackgroundImage = ImageFromFile(CIMG-20190524-WA0037png)c1FlexGrid1BackgroundImageLayout = ImageLayoutStretch

VBNET

境界線のカスタマイズ

The FlexGrid control lets you customize the border of grid row column and even cells by changing its style colordirection and so on

FlexGrid for WinForms

204 Copyright copy GrapeCity Inc All rights reserved

Customize Grid BorderTo customize border of the grid control you can use the BorderStyle property which accepts valuesfrom BorderStyleEnum provided by the C1WinFlexGridUtilBaseControls namespace

Following code shows how to customize border of the WinForms FlexGrid control

Customize RowColumn BorderTo customize the border style of a particular row or column you must access the Border item of CellStyle classusing StyleNew property and set its properties such as border style direction and color The grid controlprovides BorderStyleEnum as well as BorderDirEnum to set the border style and direction respectively

Use the below code to change border of rows or columns of the WinForms FlexGrid

Customize Cell BorderTo customize border of every cell in the grid you can access the built-in style Normal and set its border propertiesSimilarly you can change the style of specific types of cells such fixed or frozen by accessing their correspondingstyles from Styles collection

Below code lets you customize the border of normal cells of the WinForms FlexGrid

グリッドの境界線を3次元の境界線に変更しますc1FlexGrid1BorderStyle = C1WinC1FlexGridUtilBaseControlsBorderStyleEnumFixed3D

C

グリッドの境界線を3次元の境界線に変更しますc1FlexGrid1BorderStyle = C1WinC1FlexGridUtilBaseControlsBorderStyleEnumFixed3D

VBNET

最初の列の境界線スタイルを設定しますc1FlexGrid1Cols[1]StyleNewBorderStyle = BorderStyleEnumGroovec1FlexGrid1Cols[1]StyleNewBorderColor = ColorRedc1FlexGrid1Cols[1]StyleNewBorderDirection = BorderDirEnumVertical

最初の行の境界線スタイルを設定しますc1FlexGrid1Rows[1]StyleNewBorderStyle = BorderStyleEnumRaisedc1FlexGrid1Rows[1]StyleNewBorderColor = ColorBlue

C

最初の列の境界線スタイルを設定しますc1FlexGrid1Cols(1)StyleNewBorderStyle = BorderStyleEnumGroovec1FlexGrid1Cols(1)StyleNewBorderColor = ColorRedc1FlexGrid1Cols(1)StyleNewBorderDirection = BorderDirEnumVertical

最初の行の境界線スタイルを設定しますc1FlexGrid1Rows(1)StyleNewBorderStyle = BorderStyleEnumRaisedc1FlexGrid1Rows(1)StyleNewBorderColor = ColorBlue

VBNET

FlexGrid for WinForms

205 Copyright copy GrapeCity Inc All rights reserved

すべてのグリッドセルの境界線スタイルを設定しますc1FlexGrid1StylesNormalBorderStyle = BorderStyleEnumDouble

C

すべてのグリッドセルの境界線スタイルを設定しますc1FlexGrid1StylesNormalBorderStyle = BorderStyleEnumDouble

VBNET

テキストのカスタマイズ

FlexGrid lets you customize text in various ways such as changing its font margin orientation alignment effects and soon This topic caters to various aspects of text styling by taking a particular row object However if you wish to use anexisting built-in style or want to create your own custom style to re-use it see the corresponding topics

Change FontTo change font of text in a particular row or column object you can use Font property of its CellStyle Following codeshows how to change font of the WinForms FlexGrid row

カスタムスタイルを特定の行に適用しますc1FlexGrid1Rows[1]StyleNewFont = new Font(verdana 10 FontStyleUnderline)c1FlexGrid1Rows[0]StyleNewFont = new Font(verdana 10 FontStyleBold)

C

カスタムスタイルを特定の行に適用しますc1FlexGrid1Rows(1)StyleNewFont = new Font(verdana 10 FontStyleUnderline)c1FlexGrid1Rows(0)StyleNewFont = new Font(verdana 10 FontStyleBold)

VBNET

FlexGrid for WinForms

206 Copyright copy GrapeCity Inc All rights reserved

However if you want to change font of the whole grid you can set Font property of the C1FlexGrid class Followingcode shows how to change font of the entire WinForms FlexGrid

Set MarginTo set margin on text of a particular row or column you can set Margins property of the CellStyle Use the code belowto change margins in WinForms FlexGrid row

Set Vertical TextTo change the orientation and display a text as vertical text you can set TextDirection property of CellStyle of theobject Also to display the vertical text properly you may have to adjust height of the target cells depending upon thetext length Below code lets you set vertical text in the WinForms FlexGrid row

Wrap TextTo wrap a text which is longer than the available cell width you can set the WordWrap property of its CellStyle to trueFollowing code demonstrates how to apply text wrap in the WinForms FlexGrid row

グリッドの内容全体のフォントを変更しますc1FlexGrid1Font = new Font(verdana 10 FontStyleItalic)

C

グリッドの内容全体のフォントを変更しますc1FlexGrid1Font = New Font(verdana 10 FontStyleItalic)

VBNET

右側のマージンを設定しますc1FlexGrid1Rows[1]StyleNewMarginsRight = 10

C

右側のマージンを設定しますc1FlexGrid1Rows(1)StyleNewMarginsRight = 10

VBNET

行の内容のテキスト方向を設定しますc1FlexGrid1Rows[1]StyleNewTextDirection = TextDirectionEnumDown 行の高さを設定して垂直方向のテキストを表示しますc1FlexGrid1Rows[1]Height = 60

C

行の内容のテキスト方向を設定しますc1FlexGrid1Rows(1)StyleNewTextDirection = TextDirectionEnumDown

行の高さを設定して垂直方向のテキストを表示しますc1FlexGrid1Rows(1)Height = 60

VBNET

C

FlexGrid for WinForms

207 Copyright copy GrapeCity Inc All rights reserved

Display Trimmed TextTo display trimmed text when text is longer than the cell width set Trimming property of the style which takes its valuesfrom StringTrimming enumeration Use the code below to trim the long text to display ellipsis character in theWinForms FlexGrid row

Align TextYou can set the text alignment or position of the text with respect to cell by using the TextAlign property The propertyaccepts values from the TextAlignEnum enumeration

Use the code below to apply text alignment on the WinForms FlexGrid row

Apply Text EffectTo set various effects on the text you can use the TextEffect property which accepts its values from TextEffectEnumenumeration

Apply text on the WinForms FlexGrid row using the following code

セルの幅に応じて特定の行のテキストを折り返しますc1FlexGrid1Rows[1]StyleNewWordWrap = true

セルの幅に応じて特定の行のテキストを折り返しますc1FlexGrid1Rows(1)StyleNewWordWrap = True

VBNET

長いテキストをトリミングして最後に省略記号を表示しますc1FlexGrid1Rows[1]StyleNewTrimming = StringTrimmingEllipsisCharacter

C

長いテキストをトリミングして最後に省略記号を表示しますc1FlexGrid1Rows(1)StyleNewTrimming = StringTrimmingEllipsisCharacter

VBNET

テキストの配置を設定しますc1FlexGrid1Rows[1]StyleNewTextAlign = TextAlignEnumLeftCenter

C

テキストの配置を設定しますc1FlexGrid1Rows(1)StyleNewTextAlign = TextAlignEnumLeftCenter

VBNET

上げ表示するテキストを設定しますc1FlexGrid1Rows[1]StyleNewTextEffect = TextEffectEnumRaised

C

上げ表示するテキストを設定します c1FlexGrid1Rows(1)StyleNewTextAlign = TextAlignEnumLeftCenter

VBNET

FlexGrid for WinForms

208 Copyright copy GrapeCity Inc All rights reserved

カスタムのグリフ

FlexGrid lets you change the default glyph images used in the grid to indicate various actions such as column filteringand sorting This behavior of grid is exposed through GridGlyphs class which is a collection of images used by the gridto represent filtered state sorting order checkbox states and so on These images can be accessed through Glyphsproperty of the C1FlexGrid class which accepts values from GlyphEnum enumeration

Change the default glyphs used for filter editor and filtered column in the WinForms FlexGrid to a custom image usingthe code below

Note that setting this property to null restores the default glyph In order to hide a glyph you can set the Glyphproperty to a blank image

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilterEditor] = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs[GlyphEnumFilteredColumn] = ImageFromFile(filterico)

C

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilterEditor) = ImageFromFile(custom-filter-iconpng)

フィルタアイコンのグリフをカスタマイズしますc1FlexGrid1Glyphs(GlyphEnumFilteredColumn) = ImageFromFile(filterico)

VBNET

FlexGrid for WinForms

209 Copyright copy GrapeCity Inc All rights reserved

永続的な状態

Grid persistence refers to saving the current state of the grid for later use and then restoring it back when needed Forinstance the user may apply grouping sorting filtering or some styling to the grid which he wants to use after fewmore operations or on opening the application again This behavior can be achieved by persisting the grids state

There are two steps to implement persistence of the grid state First we have to serialize the grid state and then werestore it In this topic we discuss how to persist the filtered sorted and grouped state of the FlexGrid control

You can implement persisting grid states by using XMLWriter and XMLReader class of the SystemXML namespace Tosave the grid state you can use the WriteStartElement method to write the specified start tag andWriteAttributeString method to write the filter sort and group attributes Finally call WriteEndElement method toclose the WriteStartElement method and save the state in the form of stream string or a file

Use the code below to serialize the state of WinForms FlexGrid to an XML file for later use

フィルタグループ並べ替えの定義をファイルに書き込みますprivate void WriteStateToXML(string filePath) using (XmlWriter writer = XmlWriterCreate(filePath)) writerWriteStartElement(FlexGrid) writerWriteStartElement(Definition ) writerWriteAttributeString(Filter flexGridFilterDefinition) writerWriteAttributeString(Sort flexGridSortDefinition) writerWriteAttributeString(Group flexGridGroupDefinition) writerWriteEndElement() writerWriteEndElement() writerFlush()

C

フィルタグループ並べ替えの定義をファイルに書き込みますPrivate Sub WriteStateToXML(ByVal filePath As String)

VBNET

FlexGrid for WinForms

210 Copyright copy GrapeCity Inc All rights reserved

To load the saved state back into the grid you can use the GetAttribute method of the object to read the filter sortand group attributes Then assign them to the FilterDefinition SortDefinition or GroupDefinition properties of theFlexGrid respectively

Use the code below to load saved state of the WinForms FlexGrid

Using writer = XmlWriterCreate(filePath) writerWriteStartElement(FlexGrid) writerWriteStartElement(Definition ) writerWriteAttributeString(Filter flexGridFilterDefinition) writerWriteAttributeString(Sort flexGridSortDefinition) writerWriteAttributeString(Group flexGridGroupDefinition) writerWriteEndElement() writerWriteEndElement() writerFlush() End UsingEnd Sub

保存したファイルからフィルタ並べ替えグループの定義を読み取りFlexGridに適用しますprivate void ReadStateXML(string filePath)

using (XmlReader reader = XmlReaderCreate(filePath)) readerReadToFollowing(Definition) flexGridSortDefinition = readerGetAttribute(Sort) flexGridFilterDefinition = readerGetAttribute(Filter) flexGridGroupDefinition = readerGetAttribute(Group) readerClose()

C

保存したファイルからフィルタ並べ替えグループの定義を読み取りFlexGridに適用しますPrivate Sub ReadStateXML(ByVal filePath As String) Using reader = XmlReaderCreate(filePath) readerReadToFollowing(Definition) flexGridSortDefinition = readerGetAttribute(Sort) flexGridFilterDefinition = readerGetAttribute(Filter) flexGridGroupDefinition = readerGetAttribute(Group) readerClose() End Using

VBNET

FlexGrid for WinForms

211 Copyright copy GrapeCity Inc All rights reserved

NET 5 リファレンス

FlexGrid for WinForms

212 Copyright copy GrapeCity Inc All rights reserved

NET 452 リファレンス

FlexGrid for WinForms

213 Copyright copy GrapeCity Inc All rights reserved

  • 目次
  • FlexGrid for WinForms
  • 主な特長
  • 機能比較
    • FlexGrid の比較
    • WinFormsグリッドの比較
      • クイックスタート
      • 設計時サポート
        • タスクメニュー
        • エディタ
          • データ
            • 非連結モード
            • 連結モード
              • 連結モードでの操作
                    • 基本操作
                    • ユーザー操作
                    • エディタ
                      • チェックボックス
                      • 数値
                      • 日付
                      • コンボボックス
                      • マスク
                      • マップリスト
                      • セルボタン
                        • 検証
                        • データ注釈
                        • スパークライン
                        • ヘッダとフッタ
                        • サイズ変更
                            • 基本操作
                            • ユーザー操作
                            • ヘッダ
                            • 行の詳細
                            • サイズ変更
                              • セル
                                • 基本操作
                                • セルの書式設定
                                  • グリッド
                                    • 基本操作
                                    • キーボードによる移動
                                    • パフォーマンスの向上
                                      • スクロールバー
                                      • 選択
                                      • 編集
                                        • 編集モード
                                        • 編集の無効化
                                          • 並べ替え
                                            • 並べ替えの操作
                                            • 並べ替えのインジケータ
                                              • フィルタ
                                                • フィルタの操作
                                                  • フィルタの種類
                                                    • フィルタUI
                                                      • 検索
                                                      • マージ
                                                        • 自動マージ
                                                        • はみ出して表示されるセルの処理
                                                        • カスタムのマージ
                                                          • グループ
                                                          • 集計
                                                          • ツリーグリッド
                                                            • ノードの操作
                                                            • データの操作
                                                            • ツリーグリッドのカスタマイズ
                                                              • クリップボード
                                                              • 保存ロードと印刷
                                                                • 保存
                                                                • ロード
                                                                • 印刷
                                                                  • 外観とスタイル設定
                                                                    • 組み込みオプション
                                                                    • カスタムのスタイル
                                                                    • グリッドのカスタマイズ
                                                                    • 境界線のカスタマイズ
                                                                    • テキストのカスタマイズ
                                                                    • カスタムのグリフ
                                                                      • 永続的な状態
                                                                      • NET 5 リファレンス
                                                                      • NET 452 リファレンス
Page 7: FlexGrid for WinForms
Page 8: FlexGrid for WinForms
Page 9: FlexGrid for WinForms
Page 10: FlexGrid for WinForms
Page 11: FlexGrid for WinForms
Page 12: FlexGrid for WinForms
Page 13: FlexGrid for WinForms
Page 14: FlexGrid for WinForms
Page 15: FlexGrid for WinForms
Page 16: FlexGrid for WinForms
Page 17: FlexGrid for WinForms
Page 18: FlexGrid for WinForms
Page 19: FlexGrid for WinForms
Page 20: FlexGrid for WinForms
Page 21: FlexGrid for WinForms
Page 22: FlexGrid for WinForms
Page 23: FlexGrid for WinForms
Page 24: FlexGrid for WinForms
Page 25: FlexGrid for WinForms
Page 26: FlexGrid for WinForms
Page 27: FlexGrid for WinForms
Page 28: FlexGrid for WinForms
Page 29: FlexGrid for WinForms
Page 30: FlexGrid for WinForms
Page 31: FlexGrid for WinForms
Page 32: FlexGrid for WinForms
Page 33: FlexGrid for WinForms
Page 34: FlexGrid for WinForms
Page 35: FlexGrid for WinForms
Page 36: FlexGrid for WinForms
Page 37: FlexGrid for WinForms
Page 38: FlexGrid for WinForms
Page 39: FlexGrid for WinForms
Page 40: FlexGrid for WinForms
Page 41: FlexGrid for WinForms
Page 42: FlexGrid for WinForms
Page 43: FlexGrid for WinForms
Page 44: FlexGrid for WinForms
Page 45: FlexGrid for WinForms
Page 46: FlexGrid for WinForms
Page 47: FlexGrid for WinForms
Page 48: FlexGrid for WinForms
Page 49: FlexGrid for WinForms
Page 50: FlexGrid for WinForms
Page 51: FlexGrid for WinForms
Page 52: FlexGrid for WinForms
Page 53: FlexGrid for WinForms
Page 54: FlexGrid for WinForms
Page 55: FlexGrid for WinForms
Page 56: FlexGrid for WinForms
Page 57: FlexGrid for WinForms
Page 58: FlexGrid for WinForms
Page 59: FlexGrid for WinForms
Page 60: FlexGrid for WinForms
Page 61: FlexGrid for WinForms
Page 62: FlexGrid for WinForms
Page 63: FlexGrid for WinForms
Page 64: FlexGrid for WinForms
Page 65: FlexGrid for WinForms
Page 66: FlexGrid for WinForms
Page 67: FlexGrid for WinForms
Page 68: FlexGrid for WinForms
Page 69: FlexGrid for WinForms
Page 70: FlexGrid for WinForms
Page 71: FlexGrid for WinForms
Page 72: FlexGrid for WinForms
Page 73: FlexGrid for WinForms
Page 74: FlexGrid for WinForms
Page 75: FlexGrid for WinForms
Page 76: FlexGrid for WinForms
Page 77: FlexGrid for WinForms
Page 78: FlexGrid for WinForms
Page 79: FlexGrid for WinForms
Page 80: FlexGrid for WinForms
Page 81: FlexGrid for WinForms
Page 82: FlexGrid for WinForms
Page 83: FlexGrid for WinForms
Page 84: FlexGrid for WinForms
Page 85: FlexGrid for WinForms
Page 86: FlexGrid for WinForms
Page 87: FlexGrid for WinForms
Page 88: FlexGrid for WinForms
Page 89: FlexGrid for WinForms
Page 90: FlexGrid for WinForms
Page 91: FlexGrid for WinForms
Page 92: FlexGrid for WinForms
Page 93: FlexGrid for WinForms
Page 94: FlexGrid for WinForms
Page 95: FlexGrid for WinForms
Page 96: FlexGrid for WinForms
Page 97: FlexGrid for WinForms
Page 98: FlexGrid for WinForms
Page 99: FlexGrid for WinForms
Page 100: FlexGrid for WinForms
Page 101: FlexGrid for WinForms
Page 102: FlexGrid for WinForms
Page 103: FlexGrid for WinForms
Page 104: FlexGrid for WinForms
Page 105: FlexGrid for WinForms
Page 106: FlexGrid for WinForms
Page 107: FlexGrid for WinForms
Page 108: FlexGrid for WinForms
Page 109: FlexGrid for WinForms
Page 110: FlexGrid for WinForms
Page 111: FlexGrid for WinForms
Page 112: FlexGrid for WinForms
Page 113: FlexGrid for WinForms
Page 114: FlexGrid for WinForms
Page 115: FlexGrid for WinForms
Page 116: FlexGrid for WinForms
Page 117: FlexGrid for WinForms
Page 118: FlexGrid for WinForms
Page 119: FlexGrid for WinForms
Page 120: FlexGrid for WinForms
Page 121: FlexGrid for WinForms
Page 122: FlexGrid for WinForms
Page 123: FlexGrid for WinForms
Page 124: FlexGrid for WinForms
Page 125: FlexGrid for WinForms
Page 126: FlexGrid for WinForms
Page 127: FlexGrid for WinForms
Page 128: FlexGrid for WinForms
Page 129: FlexGrid for WinForms
Page 130: FlexGrid for WinForms
Page 131: FlexGrid for WinForms
Page 132: FlexGrid for WinForms
Page 133: FlexGrid for WinForms
Page 134: FlexGrid for WinForms
Page 135: FlexGrid for WinForms
Page 136: FlexGrid for WinForms
Page 137: FlexGrid for WinForms
Page 138: FlexGrid for WinForms
Page 139: FlexGrid for WinForms
Page 140: FlexGrid for WinForms
Page 141: FlexGrid for WinForms
Page 142: FlexGrid for WinForms
Page 143: FlexGrid for WinForms
Page 144: FlexGrid for WinForms
Page 145: FlexGrid for WinForms
Page 146: FlexGrid for WinForms
Page 147: FlexGrid for WinForms
Page 148: FlexGrid for WinForms
Page 149: FlexGrid for WinForms
Page 150: FlexGrid for WinForms
Page 151: FlexGrid for WinForms
Page 152: FlexGrid for WinForms
Page 153: FlexGrid for WinForms
Page 154: FlexGrid for WinForms
Page 155: FlexGrid for WinForms
Page 156: FlexGrid for WinForms
Page 157: FlexGrid for WinForms
Page 158: FlexGrid for WinForms
Page 159: FlexGrid for WinForms
Page 160: FlexGrid for WinForms
Page 161: FlexGrid for WinForms
Page 162: FlexGrid for WinForms
Page 163: FlexGrid for WinForms
Page 164: FlexGrid for WinForms
Page 165: FlexGrid for WinForms
Page 166: FlexGrid for WinForms
Page 167: FlexGrid for WinForms
Page 168: FlexGrid for WinForms
Page 169: FlexGrid for WinForms
Page 170: FlexGrid for WinForms
Page 171: FlexGrid for WinForms
Page 172: FlexGrid for WinForms
Page 173: FlexGrid for WinForms
Page 174: FlexGrid for WinForms
Page 175: FlexGrid for WinForms
Page 176: FlexGrid for WinForms
Page 177: FlexGrid for WinForms
Page 178: FlexGrid for WinForms
Page 179: FlexGrid for WinForms
Page 180: FlexGrid for WinForms
Page 181: FlexGrid for WinForms
Page 182: FlexGrid for WinForms
Page 183: FlexGrid for WinForms
Page 184: FlexGrid for WinForms
Page 185: FlexGrid for WinForms
Page 186: FlexGrid for WinForms
Page 187: FlexGrid for WinForms
Page 188: FlexGrid for WinForms
Page 189: FlexGrid for WinForms
Page 190: FlexGrid for WinForms
Page 191: FlexGrid for WinForms
Page 192: FlexGrid for WinForms
Page 193: FlexGrid for WinForms
Page 194: FlexGrid for WinForms
Page 195: FlexGrid for WinForms
Page 196: FlexGrid for WinForms
Page 197: FlexGrid for WinForms
Page 198: FlexGrid for WinForms
Page 199: FlexGrid for WinForms
Page 200: FlexGrid for WinForms
Page 201: FlexGrid for WinForms
Page 202: FlexGrid for WinForms
Page 203: FlexGrid for WinForms
Page 204: FlexGrid for WinForms
Page 205: FlexGrid for WinForms
Page 206: FlexGrid for WinForms
Page 207: FlexGrid for WinForms
Page 208: FlexGrid for WinForms
Page 209: FlexGrid for WinForms
Page 210: FlexGrid for WinForms
Page 211: FlexGrid for WinForms
Page 212: FlexGrid for WinForms
Page 213: FlexGrid for WinForms
Page 214: FlexGrid for WinForms