WinForms.Flexgrid

March 25, 2018 | Author: danielalmaral | Category: Data Type, Trademark, Windows Vista, Interface (Computing), Microsoft Windows


Comments



Description

ComponentOneFlexGrid for WinForms Copyright  2011 ComponentOne LLC. All rights reserved. Corporate Headquarters ComponentOne LLC 201 South Highland Avenue 3rd Floor Pittsburgh, PA 15206 ∙ USA Internet: Web site: Sales E-mail: [email protected] Telephone: 1.800.858.2739 or 1.412.681.4343 (Pittsburgh, PA USA Office) [email protected] http://www.componentone.com Trademarks The ComponentOne product name is a trademark and ComponentOne is a registered trademark of ComponentOne LLC. All other trademarks used herein are the properties of their respective owners. Warranty ComponentOne warrants that the original CD (or diskettes) are free from defects in material and workmanship, assuming normal use, for a period of 90 days from the date of purchase. If a defect occurs during this time, you may return the defective CD (or disk) to ComponentOne, along with a dated proof of purchase, and ComponentOne will replace it at no charge. After 90 days, you can obtain a replacement for a defective CD (or disk) by sending it and a check for $25 (to cover postage and handling) to ComponentOne. Except for the express warranty of the original CD (or disks) set forth here, ComponentOne makes no other warranties, express or implied. Every attempt has been made to ensure that the information contained in this manual is correct as of the time it was written. We are not responsible for any errors or omissions. ComponentOne’s liability is limited to the amount you paid for the product. ComponentOne is not liable for any special, consequential, or other damages for any reason. Copying and Distribution While you are welcome to make backup copies of the software for your own use and protection, you are not permitted to make copies for the use of anyone else. We put a lot of time and effort into creating this product, and we appreciate your support in seeing that it is used by licensed users only. This manual was produced using ComponentOne Doc-To-Help™. Table of Contents ComponentOne FlexGrid for WinForms Overview ............................................................................................ 1 Differences Between the .NET and ActiveX Versions of C1FlexGrid ............................................................. 1 Differences Between the .NET and Mobile Versions of ComponentOne FlexGrid for WinForms .............. 3 Differences Between ComponentOne FlexGrid for WinForms and ComponentOne True DBGrid for WinForms ............................................................................................................................................................. 5 What's New in ComponentOne FlexGrid for WinForms ................................................................................. 5 Revision History ................................................................................................................................................... 6 What's New in 2010 v3 .......................................................................................................................... 6 What's New in 2010 v2 .......................................................................................................................... 7 What’s New in 2010 v1 .......................................................................................................................... 7 Installation ........................................................................................................................................................... 11 FlexGrid for WinForms Setup Files ................................................................................................... 11 System Requirements ........................................................................................................................... 12 Installing Demonstration Versions ...................................................................................................... 13 Uninstalling FlexGrid for WinForms ................................................................................................. 13 Licensing FAQs .................................................................................................................................................. 13 What is Licensing? ............................................................................................................................... 13 How does Licensing Work? ................................................................................................................. 13 Common Scenarios .............................................................................................................................. 14 Common Scenarios in Mobile Applications ...................................................................................... 16 Troubleshooting .................................................................................................................................... 17 Technical Support ............................................................................................................................................... 19 Redistributable Files ........................................................................................................................................... 19 About This Documentation ............................................................................................................................... 20 Namespaces ......................................................................................................................................................... 20 Creating a .NET Project ..................................................................................................................................... 21 Creating a Mobile Device Application .............................................................................................................. 22 Adding the C1FlexGrid Components to a Project ........................................................................................... 22 Migrating a C1FlexGrid Project to Visual Studio 2005 ................................................................................... 24 Key Features .................................................................................................................................................... 25 FlexGrid for WinForms Quick Start ................................................................................................................. 27 iii Step 1 of 3: Creating the FlexGrid for WinForms Application ....................................................................... 27 Step 2 of 3: Binding C1FlexGrid to a Data Source .......................................................................................... 27 Step 3 of 3: Customizing C1FlexGrid Settings ................................................................................................. 28 Design-Time Support ....................................................................................................................................... 31 C1FlexGrid Editors ............................................................................................................................................ 31 C1FlexGrid Column Editor ................................................................................................................. 31 C1FlexGrid Style Editor ...................................................................................................................... 33 Caption Style and Column Style ......................................................................................................... 35 C1FlexGrid Smart Tag ....................................................................................................................................... 39 C1FlexGrid Tasks Menu ..................................................................................................................... 40 Column Tasks Menu ............................................................................................................................ 42 Using the C1FlexGrid Control ......................................................................................................................... 45 Rows and Columns ............................................................................................................................................ 47 Column Sizing ...................................................................................................................................... 48 Cell Selection....................................................................................................................................................... 49 Cell Ranges.......................................................................................................................................................... 51 Cell Images .......................................................................................................................................................... 51 Formatting Cells ................................................................................................................................................. 52 Cell Content .......................................................................................................................................... 52 Cell Appearance ................................................................................................................................... 53 Conditional Formatting ....................................................................................................................... 54 Owner-Drawn Cells.............................................................................................................................. 55 Editing Cells ........................................................................................................................................................ 57 Lists and Combos ................................................................................................................................. 58 Checkboxes ........................................................................................................................................... 59 Value-Mapped Lists ............................................................................................................................. 60 Cell Buttons........................................................................................................................................... 62 Masks..................................................................................................................................................... 64 Validation .............................................................................................................................................. 65 Custom Editors ..................................................................................................................................... 66 Edit Mode ............................................................................................................................................. 67 Merging Cells ...................................................................................................................................................... 68 Merged Table Headers ......................................................................................................................... 69 Merged Data Views .............................................................................................................................. 70 Spilling Text .......................................................................................................................................... 71 Custom Merging ................................................................................................................................... 72 iv ...................................................................................................................................................... 79 Outline Tree .................................................. 87 Outline Maintenance ......................................................................... 93 Managing filters programmatically ... 89 Saving........................................ 113 Step 1 of 6: Create the C1FlexGrid Control for the Edit Tutorial ......................... 114 Step 2 of 6: Set Column Types and Formats ...... 98 C1FlexGrid Property Groups ........... 123 Outline Tutorial .................................................................................................................................................................................................................................................................................................................................. 113 Edit Tutorial ................................................................................................................................................................................................................................................................................................................................................................ and Printing ................................ 88 Using the Node class ...................................................................................... 73 Creating Custom Trees ...... 92 C1FlexGrid Filtering .................................. 127 Step 2 of 5: Read the Data and Build the Outline .............................................................................................. 75 Creating Outlines and Trees with the C1FlexGrid Control . 126 Step 1 of 5: Create the Controls ............................... 123 Step 6 of 6: Include Custom Editors ................................................................................................................................................................................................................................................................................................................................................... 95 Applying filters programmatically ........................................................................................................................ 83 Adding Subtotals ....................................................... 84 Using the Subtotal Method ............................................................................................................................................................................................................................................................................................................................................................. Loading................................................................................................... 121 Step 5 of 6: Add Clipboard Support ..................................... 101 Binding to a Data Source ............................... 90 Saving and Loading Microsoft Excel Files .................................................................................... 96 Customizing filter behavior ...................................... 117 Step 3 of 6: Incorporate Drop-Down Lists ............................................................................................................ 90 Printing Grids ............................................................................................................................................................................................. 97 Customizing the Filtering UI .......................................................................................................................................................................... 130 v .............................................................................................................................................. 103 FlexGrid for WinForms Samples .......................................... 73 Creating Subtotals ....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................... 99 Data Binding.......................................................................... 105 FlexGrid for WinForms Tutorials ................................... 93 AllowFiltering property ....... 90 Loading Grids from Databases.................................. 101 Storing and Retrieving Data .......................... 118 Step 4 of 6: Add Data Validation ....................Outlining and Summarizing Data ............................................................................................................................................................................................................... 90 Saving and Loading Grids to Text Files ............. ....... 163 Filtering by Value .................................................................................... and UserData ............................ 153 Adding ToolTips That Display UserData ............................................................ 164 Filtering by Condition ........................................................................... 137 Step 1 of 4: Create the C1FlexGrid Control for the Data Analysis Tutorial ..................................................................................................................................................................................................................................................................... 159 UserData ToolTips for a Single Cell .................................................................... 168 Clearing Styles ............................................................................................. 154 UserData ToolTips for a Cell Range ................................................................ 166 Clearing a Tree View .......................... 151 Adding Three-Dimensional Text to a Header Row ...........................Step 3 of 5: Add Custom Mouse and Keyboard Handling . 150 Adding Row Numbers in a Fixed Column ....................................................................... 136 Data Analysis Tutorial ........................................................................................................................................... 169 Clearing UserData ........................... 170 Converting Column Letters to Uppercase .................................................................................. 144 Step 4 of 4: Include Subtotals and Outline Tree ..................................................... 161 Changing the Column Order in the Grid ............................................. 168 Clearing Content ....................................................... 155 UserData ToolTips for a Cell Style ................................................................................................................................................................................................. 154 UserData ToolTips for a Column .................................................................................................................................................................................................................................................... 138 Step 3 of 4: Allow Automatic Sorting ....................................................................................... 171 Entering Only Numbers in a Cell ................................................. 149 Adding Pictures and Text to a Cell ........................ 174 Formatting Cells ........................................................................................................................................ 138 Step 2 of 4: Initialize and Populate the Grid ..................................................... 149 Accessing the C1FlexGrid Style Editor ...................................................................................................................................................... 170 Clearing Content....................................................................................................................... 175 vi .................................................................................................................................................................... 165 Changing the Filter Language ................................................................................................................................................................................................................................. 157 UserData ToolTips for a Row ........................................................................................................................ Styles.................................................... 145 FlexGrid for WinForms Task-Based Help ...................................... 171 Customizing Appearance Using Visual Styles............................................................ 160 Applying a Gradient Background to a CellRange ........ 134 Step 4 of 5: Allow/Prevent Editing .................................................................................................................................................. 167 Clearing C1FlexGrid ................................................................................................................................ 149 Accessing the C1FlexGrid Editors ................................................................................ 149 Accessing the C1FlexGrid Column Editor ................................................................................................................................................................................................................................................................................................................................................................................... 152 Adding Three-Dimensional Text to a Header Row Using Built-In Styles .......................................................................... 135 Step 5 of 5: Implement ToolTips ................................... .................................................................. 205 Using Password Entries in C1FlexGrid .............................................................................. 202 Setting the Text Delimiting Character in C1FlexGrid ....................................................................................... 208 FlexGrid for WinForms Top Tips ................................................................................................................................................................... 176 Formatting Cells Based on the Contents ......... 179 Formatting the Border Style of the Grid ................................................................................................................................................. 182 Freezing Rows and Columns .................................................................................................................................................................................................................................................................................. 197 Setting the Background Color of Columns and Rows .................................................................................................. 204 Sorting Multiple Columns .................................. 196 Setting a Cell's Value to Zero When Users Press the Delete Key ...................... 199 Setting the Background Color of Rows and Columns in a Single Statement .................................................................. 179 Formatting the Border Style of the Control ................................................................................ 211 vii ................................................................... 193 Disable Editing for the Entire Grid .......... 192 Populating a Row with Data ................................................ 191 Populating a Range of Cells with Data ......................................................................................................................................................................................................................................................................................................... 191 Populating a Column with Data ............................................. 195 Searching for Entries in a Column ......................................................................................................................................................................................................................................................................................................................................................................................................................................................... 177 Formatting the Border Style ................................................................Formatting a Cell as Read-Only ..................................................... 196 Setting Rows As Headers ................ 193 Restricting Sorting for a Specific Column ................................................................................................................................................................................................ 206 Hiding Characters Already Entered .................................................. 189 Populating an Unbound Grid with Data .............................................................................................................................................................................................. 192 Populating a Single Cell with Data ................................................................................................................................................................................................................... 201 Setting the Font of a Single Cell ....... 193 Disable Editing for a Specific Column ................................... 187 Loading and Saving Open XML Files ............ 192 Restricting Grid Editing ................................................... 193 Disable Editing for a Specific Row ........ 194 Scaling Images in the Entire Grid ..... 175 Formatting a Cell with Decimal Content ......................................................................................................... 207 Word Wrapping in a Header or Fixed Row ...................................................................................................................................................................................................................................................................................... 194 Scaling an Image .................................................. 204 Undoing a Sort ..................................................... . C1FlexGrid is not a simple port of the ActiveX control. and to make the learning curve as smooth as possible for VSFlexGrid users.FlexGrid for WinForms Samples (page 105) . summarize. review the following topics: .FlexGrid for WinForms Quick Start (page 27) . or in unbound mode. It will read and write grids from and to compressed binary files or text files (compatible with Microsoft Access and Excel). It is a brand new grid control.ComponentOne FlexGrid for WinForms Overview ComponentOne FlexGrid™ for WinForms incorporates the latest in data-binding technology and integrates seamlessly with the Microsoft. The ComponentOne FlexGrid for WinForms package consists of two controls:  C1FlexGrid Control The C1FlexGrid control is a powerful. clean. We supply the source code to C1FlexGridClassic so you can see exactly how to use the new object model. Unicode. we supplied several versions of the FlexGrid control (ADO. you should use the C1FlexGrid control. You can also use it as an example and create your own grid using the C1FlexGrid as a base class. As a result. and powerful than the one in the ActiveX control. full-featured grid.  Getting Started To get started. If you are writing new applications. DAO. we also offer the C1FlexGridClassic control.NET data sources or used in unbound mode. C1FlexGrid can be used in bound mode. The source code for C1FlexGridClassic is provided as a sample. The C1FlexGrid control can be bound to ADO. flexible grid control for creating user-friendly interfaces that display.FlexGrid for WinForms Top Tips (page 211) C1FlexGridClassic Control The C1FlexGridClassic control is a control that derives from C1FlexGrid and provides an object model that is virtually 100% identical to the VSFlexGrid ActiveX control. C1FlexGrid provides all the basics plus advanced features such as outline trees. where the grid itself manages the data. where it displays data from any . masked editing. sorting. and so on). C1FlexGridClassic is a control that uses C1FlexGrid as a base class and exposes an object model that is virtually identical to the one in VSFlexGrid.NET data source. with the same design principles but with a new object model that is more modern. edit. If you are porting existing applications that use the VSFlexGrid ActiveX control and want to change as little code as possible. You can use it as a reference that shows how to use the C1FlexGrid control as a base class in the development of custom grid controls. including ADO. you get an easy-to-use. C1FlexGridClassic was developed to allow easy migration of existing VSFlexGrid projects. unbound. translated combo and image lists.NET product.NET and ActiveX Versions of C1FlexGrid In the ActiveX product. there are two versions: C1FlexGrid and C1FlexGridClassic. organize. Differences Between the . To keep the highest level of source-code compatibility with existing applications.NET and ComponentOne DataObjects for WinForms. 1 . then use the C1FlexGridClassic control. cell merging. and print tabular data.NET Framework. and automatic data aggregation.Key Features (page 25) . format. written from the ground up in C#. In the . to give the second row a red background. For example.Fixed To _flex.FixedRows To _flex.Rows(2). CellStyle objects are used consistently throughout the control.Rows.TextMatrix(r. Using the ActiveX control.Highlight.NET and ActiveX versions of C1FlexGrid: VSFlexGrid (ActiveX) Rows.Cell(flexcpBac kColor. In the C1FlexGrid control. then changing those.Cell(flexcpPicture.Red _flex. 0. c% c = 1 For r = _flex. This is probably the most visible change between the controls. To make the second row red.White _flex. 10.NET) Using the C1FlexGrid control.Print _flex(r. CellRange The Cell property is one of the most powerful elements of the VSFlexGrid object model. you would write: Dim redStyle As CellStyle = _flex. FontStyle.Style = redStyle But this requires three lines of code instead of one! What's the advantage? The main advantage of the new approach is that the new style is an object that can be changed or assigned to new ranges.Count . you can customize the appearance of individual cells or cell ranges using the Cell property. instead of writing: _flex. The collections have read/write properties that return the number of elements and fixed elements in each collection.c ) Next C1FlexGrid (.1 Debug. It allows you to get or set any property of any cell or cell range with a single The C1FlexGrid replaces the Cell property with a CellRange object that exposes type-safe properties and methods used to access the properties of a cell range.Bold) This will change the appearance of all cells that use the "Red" style. The previous approach would require either (1) clearing all styles and setting everything up again from scratch or (2) scanning all cells in the grid to detect which cells are red. For example. For example.Rows. c% c = 1 For r = _flex.Styles("Red"). these properties return row and column collections.Font = new Font("Arial". you would write: _flex.The following table lists the differences between the .Styles. Styles In the ActiveX control.Fixed.Add("Red") redStyle. 10) = theImage 2 .ForeColor.Print _flex.Cols-1) = vbRed Uses indexers. The C1FlexGrid control uses a CellStyle object to customize cell appearance.ForeColor = Color. 9. Cols Collections The ActiveX control has Rows and Cols properties that are used to get or set the number of rows and columns on the grid.BackColor and Styles. 2.1 Debug. so instead of BackColorFixed and ForeColorSel you can now write Styles.Rows . 5.c) Next Uses the TextMatrix property. you can write: _flex. if you decide to give the red cells a white forecolor and a bold font. _flex. you would write: Dim r%.BackColor = Color. 2.Styles("Red"). this becomes: Dim r%. 5. 2.2). so if the variable theImage contained a string instead of an image.NET) C1FlexGrid Editors C1FlexGrid Column Editor C1FlexGrid Style Editor C1FlexGrid (Mobile) N/A N/A 3 . // Bad value.GetCellRange(5. _flex[2. It provides the C1FlexGrid control. If you want to store values of mixed types in a column.Cols[2]. handling colors. you have two options: 1. and print tabular data. a full-featured grid to display. // Value will be set to 12.10) rg. the ColDataType allowed you to set the type of data that each column contained. 2] = "hello". You would write: Dim rg As CellRange rg = _flex. This information was used mainly for sorting columns that contained dates or numbers.NET version has a Cols[i]. Use the SetData method with the coerce parameter set to False to store a value or object without checking the data type. which means you can store anything in any column. and so on. and this prevents the compiler from catching many subtle problems in case you make mistakes.DataType = typeof(int).  Typed columns In the ActiveX version. The . text. the DataType for all columns is "object".NET and . such as personal digital assistants (PDAs).Image = theImage The new approach has two significant advantages:  It is type-safe. The following table lists the differences between the . format. Using a single property means using Variants. summarize. _flex[1. however. Set the column's DataType property to "object".10. mobile phones and more. you would get a compiler error instead of a runtime error. Fire the GridError event and ignore. edit.2) would retain its original value.NET and Mobile Versions of ComponentOne FlexGrid for WinForms The mobile version of ComponentOne FlexGrid for WinForms allows you to quickly develop Microsoft. This code would assign the integer 12 to cell (1. and the grid will try to coerce any data stored in the grid to the proper type. You get command-completion when writing the code because the types for each property are known. You can set the data type to specific types. By default. Cell (2. values. Differences Between the .5. 2] = "12". but with a compacted version of the FlexGrid for WinForms object model and feature set. For example: _flex. However.DataType property that determines the type of data the column holds.NET Compact Framework versions of C1FlexGrid: C1FlexGrid (. organize. because the string "hello" cannot be converted to an integer.NET Compact Framework-based applications for your mobile devices.command. bmp") C1FlexGrid1. myimage)  C# { Bitmap myimage = new Bitmap("c:\\myimage. c1FlexGrid1.From File(c:\myimage.From File(@"c:\myimage. but you can load and set the image as in the following example:  Visual Basic Dim myimage As New Bitmap("c:\myimage.NET Framework. columns can be resized using the Width property which can be set directly in the grid by clicking and dragging the horizontal double arrow that appears at the right edge of a column's header.Image. you can use the . When binding to a data source.1. You can access the Data Source Configuration Wizard to bind to a data source either through the Properties window or the C1FlexGrid Tasks menu. Please see Microsoft's documentation for more information. 4 .FromFile is not supported by the . Data Binding You can access the Data Source Configuration Wizard to bind to a data source through the Properties window. Image Support Use the SetCellImage method to add an image to a cell. See the CustomMerge samples provided with C1FlexGrid and on ComponentOne HelpCentral. For example.SetCellImage(1.NET Compact Framework.NET Framework Data Provider for SQL Server Mobile Edition. or programmatically. The DataSource property can be set at run time only. myimage). you must use a data provider that is supported by the . Custom Merging You can use the Custom option in the AllowMerging property. 1.Caption Style Column Style C1FlexGrid Smart Tag C1FlexGrid Tasks Menu Column Tasks Menu Column Sizing At design time.SetCellImage(1. N/A At design time.bmp"). Use the SetCellImage method to add an image to a cell. The DataSource property can be set at design time or run time. through the C1FlexGrid Column Editor. More information is available on custom merging in the Custom Merging (page 72) topic.bmp")).SetCellImage(1. } Note: The Image class is unrelated to C1FlexGrid.1. providing your own custom merging logic. Image. You can create a new class that derives from the C1FlexGrid and override the GetMergedRange virtual method.bmp"))  C# c1FlexGrid1.NET Compact Framework. N/A N/A About C1FlexGrid is the only option available on this menu. 1. columns can be resized using the Width property in the Properties window or programmatically. For example:  Visual Basic C1FlexGrid1. but custom merging can still be performed in the mobile version of C1FlexGrid. You can bind to a data source using any data provider supported by the .SetCellImage(1.Image. The Custom option is not available in the AllowMerging property. See Binding to a Data Source (page 101) for more information. including split views and built-in hierarchical binding and grouping. and the glyphs should be column-specific. Dutch. therefore.GlyphRow = 0. offers more features in that area.  5 .c1FlexGrid2. C1FlexGrid is a better choice. if you plan to work with your grids in unbound mode or need to customize the grid beyond what the object model offers.AllowFiltering = true. Czech.componentone.Rows. Danish.Rows. When grids have multiple fixed rows. easy-to-use grid controls that allow you to browse.AllowFiltering = true. there are several reasons why you may want to use one over the other. French. Japanese. Polish.c1FlexGrid1. please visit our Web site at http://www. However.Differences Between ComponentOne FlexGrid for WinForms and ComponentOne True DBGrid for WinForms Many customers ask what the difference is between our grid components. this property is set to -1. edit.com. // show glyphs on the default position (last fixed row) this. the sorting and filter glyphs are shown on the last fixed column by default. Russian. delete. add. This property allows you to select the row that will contain the sort and filter glyphs. If you have additional questions about ComponentOne FlexGrid for WinForms and ComponentOne True DBGrid for WinForms. Arabic.  The GlyphRow property has been added. this. this. this. The following enhancements were made to FlexGrid for WinForms in the 2011 v1 release of the ComponentOne Studios. and Hebrew. The built-in filter now supports the following cultures: English. The reason for this is that the last fixed row is usually not merged. You can also derive from it to create customized grids. What's New in ComponentOne FlexGrid for WinForms This documentation was last revised for 2011 v1.Rows.  A C1FlexGridBase. Portuguese.c1FlexGrid2. Greek.c1FlexGrid2.c1FlexGrid1. the application may require showing the sort and filter glyphs on the first fixed row (or on any other fixed row). Norwegian. By default. which causes the glyphs to be displayed on the last fixed row (the original default behavior). Italian. Swedish. See the AllowFiltering property (page 93) and Changing the Filter Language (page 166) topics for more information.Fixed = 3. For example: // show glyphs on the first fixed row this.DataSource = myDataTable. German. If you plan to use your grids mainly in bound mode and require advanced features such as splits and hierarchical views. Support has been added for the Polish and Chinese cultures.DataSource = myDataTable. Spanish. Both components can be used in bound or unbound mode.Fixed = 3.Language Property has been added to allow control over localization. however.c1FlexGrid1. but C1FlexGrid allows you to work more easily in unbound mode. True DBGrid for WinForms is the right choice.c1FlexGrid1. Finnish. ComponentOne True DBGrid for WinForms is better suited for data binding and. this. Chinese. With C1FlexGrid you can customize trees and take advantage of its cell merging capabilities. and manipulate tabular data. In some cases. Slovak. While both are robust. this. and FirstVisibleChild. The VisualStyle property has three new settings that match the look of Excel 2010: Office2010Blue. The FirstVisibleChild. The following new members have been added to the NodeTypeEnum Enumeration: FirstVisibleSibling. Pastes the content of the clipboard onto the current selection. Added Microsoft Office 2010 visual styles. Paste().  Methods for clipboard support were added: Cut(). Finnish. improvements. Czech.Cut Method C1FlexGridBase. Office2010Silver.Copy Method C1FlexGridBase. Spanish. Greek. Gets or sets the index of the row used to display the sorting and filtering glyphs.aspx.componentone. Cuts the content of the current selection to the clipboard. has been widened to better accommodate localization in certain cultures. NextVisibleNode. Arabic. Revision History The revision history provides recent enhancements to ComponentOne FlexGrid for WinForms. Swedish. Edits the filter associated with a given column.GlyphRow Property Description Gets or sets the language to use when localizing the column filters. and PrevVisibleNode properties were added to the Node class to reflect the new NodeTypeEnum settings.    Class Members Member IgnoreDiacritics Property Description This property determines whether the grid should ignore diacritics 6 . What's New in 2010 v3 The following enhancements were made to FlexGrid for WinForms in the 2010 v3 release of the ComponentOne Studios. NextVisibleSilbling. and changes for each product is available in HelpCentral at http://helpcentral. Class Members Member C1FlexGridBase. fixes. and Office2010Black. and Hebrew cultures. Arabic. Norwegian. Italian. Copies the current selection to the clipboard. Copy(). Dutch. Norwegian.Language Property C1FlexGridBase.  Support has been added for the Greek. German.com/VersionHistory. Finnish. Russian. which allows users to filter columns. French. PreviousVisibleSibling. The built-in filter now supports the following cultures: English. Tip: A version history containing a list of new features. Portuguese. and Hebrew. Slovak. Clears the filter associated with a given column. The ValueFilter drop-down editor. LastVisibleSibling. Japanese. Danish. Danish.Paste Method EditFilter Method ClearFilter Method RowCollection. Swedish. What's New in 2010 v2 There were no new features added to FlexGrid for WinForms for the 2010 v2 release of the ComponentOne Studios. Gets or sets a value that determines the position of the sort glyphs within column header cells. The data filtering feature follows the pattern used by Microsoft in Windows 7/Vista. such as French. When users move the mouse over column headers. the C1FlexGrid control will allow users to apply filters to each column on the grid. which allows users to select specific values for display. FirstVisibleChild Property NextVisibleNode Property PrevVisibleNode Property FilterDefinition Property ShowSortPosition Property Gets the first visible child node. 7 . and rows must pass all filters in order to be displayed. Every column has a filter. Gets the next visible sibling node. It is especially important in cultures that use accents extensively. What’s New in 2010 v1 The following enhancements have been made to FlexGrid for WinForms in the 2010 v1 release of the ComponentOne Studios:  Built-in data filtering This is the most important new feature in version 2010/v1. If you set the new AllowFiltering property to true. Developers may also create custom specialized filters and assign them to columns. The built-in filters include a ValueFilter. the grid displays a filter icon on the header. Clicking the icon invokes the filter editor which selects the data that should be displayed. which allows them to specify conditions such as "Greater than" or "Contains". The images below show the filtering feature in action. Gets or sets an XML string containing the current filter state. as well as a ConditionFilter. Gets the previous visible sibling node. This image shows the ValueFilter editor being used to select a few products. Spanish. and Portuguese.(accents) when filtering data. Picture 2: ConditionFilter editor 8 .Picture 1: ValueFilter editor This image shows the ConditionFilter editor selecting a range of order quantities. Picture 3: VisualStyle=System Notice how the grid fully utilizes the system themes for row and column headers. Vista. Checked. where the ProductName and Quantity column headers show the filter icon. The Checked property in the Node object supports three check states (checked.  Improved object model for Trees and Node objects The Node object in version 2010/v1 has additional properties that make it much easier to create and manipulate trees. so migrating code is easy and there is no learning curve. The following image shows the appearance of the C1FlexGrid control under Windows 7. You can see this in the images. The new properties in the Node object include Parent. This new behavior mimics the one found in native Windows 7/Vista lists. By contrast. Italian. French. and Windows 7. The built-in filters support automatic localization in the following languages: English. See C1FlexGrid Filtering (page 93) for more information. and Japanese. PrevNode. Dutch. and visually unobtrusive.  Improved rendering Version 2010/v1 has enhanced theme support that works under Windows XP. and undefined). and NextNode. the standard TreeView control only supports checked and unchecked. The new properties were designed for compatibility with the standard TreeView control. The VisualStyle property is set to System. flexible. German. Spanish. The localization is built-in and does not require satellite dlls. The new filtering feature is extremely powerful. Russian. unchecked. Portuguese. This makes it possible to create trees where the parent nodes reflect the checked state of their children. Nodes. 9 . and how the sort indicator now appears at the top of the column headers instead of on the right.Columns that have filters applied display the filter icon on their headers even when the mouse is not over them. 000 items). which incurred a performance penalty that many users were not aware of. you had to use a generic AfterEdit event. this will save C1FlexGrid developers from having to adjust the width of the fixed column with the mouse every time they drop the grid on a form. version 2010/v1 will scroll the grid when the mouse is stationary off the control. Warning: This is a breaking change for some existing applications. Applications that want auto-sizing must opt in and explicitly set the AutoResize property to True. Fires after the column filters are applied to the grid.  Improved control updates Version 2010/v1 has new BeginUpdate and EndUpdate methods to suspend and restore repainting.ApplyFilters Method C1FlexGridBase. Gets or sets this type of filter to use for this column. Please refer to the TreeCheck sample for details on how to build trees with the C1FlexGrid control that support three-state checkboxes.The improvements to the Node object model make programming C1FlexGrid-based trees similar to regular TreeView control trees. The auto-sizing process takes a significant amount of time when the grid is bound to large data sources (say over 10. Even though adjusting the column widths is easy. Interface implemented by column filter editor controls.AllowFiltering Property Column. These methods replace the Redraw property (now deprecated) for improved object-model compatibility with the standard . The default value for the AutoResize property used to be True.AfterFilter Event IC1ColumnFilter Interface IC1ColumnFilterEditor Interface Description Gets or sets whether the user is allowed to filter the data. If you have applications that require auto column sizing.Filter Property C1FlexGridBase. the default value for the AutoResize property was changed to False. Applies all column filters to the data on the grid. In this version.  Easier column setup When you drop a C1FlexGrid on the form. Fires before the column filters are applied to the grid. 10 .AllowFiltering Property Column. the default fixed column is now narrower than the other columns.BeforeFilter Event C1FlexGridBase. In previous versions. Interface implemented by column filter objects.  Improved selection behavior When extending the selection with the mouse.NET controls.  Improved CheckBox support Version 2010/v1 has a new CellChecked event that makes it easier to handle check boxes in cells and tree nodes.  Better startup performance The C1FlexGrid has an AutoResize property that causes the grid to automatically auto-size the columns when the grid is bound to a data source. you will have to set AutoResize to True (this can be done at design time using the Visual Studio designer or at run time using code). Class Members Member C1FlexGridBase. Gets or sets the IC1ColumnFilter responsible for filtering this column. 11 .DataMemberChanged Event C1FlexGridBase.DataSourceChanged Event C1FlexGridBase. It also explains how to install demonstration versions of ComponentOne products and uninstall FlexGrid for WinForms. Fires when the value of the DataMember property changes.Nodes Property Node. Gets the parent node of this node.DataBindingComplete Event C1FlexGridBase. Gets the next sibling node. Resumes updating the control after calls to the BeginUpdate() method. Installation This section describes the setup files and system requirements for FlexGrid for WinForms. Gets or sets the checkbox value associated with this node. This directory contains the following subdirectories: bin Contains copies of all ComponentOne binaries (DLLs. Represents a filter based on one or two logical conditions. FlexGrid for WinForms Setup Files The ComponentOne Studio for WinForms installation program will create the following directory: C:\Program Files\ComponentOne\Studio for WinForms. The sample shows how you can control and customize the grid's built-in filters using the AllowFiltering property and the AfterFilter event.Checked Property C1FlexGridBase.Prevnode Property Node. Represents a filter that contains a ValueFilter and a ConditionFilter. EXEs). Gets the previous sibling node. Fires after a checkbox in a cell is checked or unchecked by the user.CellChecked Event Represents a filter based on a set of values. Gets an array containing the children of this node.NextNode Property Node. Fires after a data-binding operation has finished. Fires when the value of the DataSource property changes. CustomFilters This sample shows how to implement custom filters for the C1FlexGrid. New Samples Member ColumnFilters Description Shows how to use the new filtering feature in C1FlexGrid 2010.ValueFilter Class ConditionFilter Class ColumnFilter Class Node.BeginUpdate Method C1FlexGridBase. Maintains performance by preventing the control from updating itself until the EndUpdate() method is called.EndUpdate Method C1FlexGridBase.Parent Property Node. Samples can be accessed from the ComponentOne Sample Explorer.0 or later C# .0 integrated documentation for all Studio components.NET Visual Basic . Contains samples and tutorials for FlexGrid for WinForms.C1FlexGrid Contains files (at least a readme. on your desktop. click the Start button and then click All Programs | ComponentOne | Studio for WinForms | Samples | FlexGrid Samples.NET Disc Drive: CD or DVD-ROM drive if installing from CD 12 . The path of the ComponentOne Samples directory is slightly different on Windows XP and Windows 7/Vista machines: Windows XP path: C:\Documents and Settings\<username>\My Documents\ComponentOne Samples Windows 7/Vista path: C:\Users\<username>\Documents\ComponentOne Samples The ComponentOne Samples folder contains the following subdirectories: Common C1FlexGrid Contains support and data files that are used by many of the demo programs. Contains Microsoft Help Viewer Visual Studio 2010 integrated documentation for all Studio components.txt) related to the FlexGrid for WinForms product. System Requirements System requirements include the following: Operating Systems: Windows 2000 Windows Server 2003 Windows Server 2008 Windows XP SP2 Windows Vista Windows 7 Environments: NET Framework 2. The ComponentOne Studio for WinForms Help Setup program installs integrated Microsoft Help 2. To view samples. H2Help HelpViewer Samples Samples for the product are installed in the ComponentOne Samples folder by default.0 and Microsoft Help Viewer help to the C:\Program Files\ComponentOne\Studio for WinForms directory in the following folders: Contains Microsoft Help 2. Licensing is not only used to prevent illegal distribution of software products. Open the Control Panel application and select Add or Remove Programs (Programs and Features in Windows 7/Vista). How does Licensing Work? ComponentOne uses a licensing model based on the standard set by Microsoft. 1. Open the Control Panel and select Add or Remove Programs (Programs and Features in Windows 7/Vista). or by rerunning the installation and entering the serial number in the licensing dialog. 1. Visual Studio obtains version and licensing information from the newly created component. It may help the user to understand and resolve licensing problems he may experience when using ComponentOne . 2. this type of distribution would not be practical for the vendor or convenient for the user. Select ComponentOne Studio for WinForms Help and click the Remove button. To uninstall ComponentOne FlexGrid for WinForms integrated help: Licensing FAQs This section describes the main technical aspects of licensing. When a user decides to purchase a product. When queried by Visual Studio. if available. The only difference between unregistered (demonstration) and registered (purchased) versions of our products is that registered versions will stamp every application you compile so a ComponentOne banner will not appear when your users run the applications. who could easily forget that the software being used is an evaluation version and has not been purchased.NET and ASP. 3. which works with all types of components. During the installation process. Click Yes to remove the program. What is Licensing? Licensing is a mechanism used to protect intellectual property by ensuring that users are authorized to use software products. the user is prompted for the serial number that is saved on the system. Without licensing.Installing Demonstration Versions If you wish to try FlexGrid for WinForms and do not have a serial number. Select ComponentOne Studio for WinForms and click the Remove button. Note: The Compact Framework components use a slightly different mechanism for run-time licensing than the other ComponentOne components due to platform differences. use licensing to allow potential users to test products before they decide to purchase them. Uninstalling FlexGrid for WinForms To uninstall FlexGrid for WinForms: 1. install the product as usual but do not provide a serial number. (Users can also enter the serial number by clicking the License button on the About Box of any ComponentOne product.) When a licensed component is added to a form or Web page.NET products. Vendors would either have to distribute evaluation software with limited functionality. or shift the burden of managing software licenses to customers. he receives an installation program and a Serial Number. including ComponentOne. 2. the component looks for 13 . Click Yes to remove the integrated help. Many software vendors. the run-time license may also be stored as an embedded resource in the App_Licenses.dll assembly. the licensing information is stored in the licenses. add an instance of the component to a form in the project. the run-time license is stored as an embedded resource in the assembly hosting the component or control by Visual Studio.licx file and things will then work as expected. you can do this manually using notepad or Visual Studio itself by opening the file and adding the text.licx file. Thus. it obtains the run-time license from the appropriate assembly resource that was created at design time and can decide whether to simply accept the run-time license. this file is read and used as a list of components to query for run-time licenses to be embedded in the appropriate assembly resource.licensing information stored in the system and generates a run-time license and version information. the component will be queried and its run-time license added to the appropriate assembly resource.licx file. (The component can be removed from the form after the licenses. select Show All Files on the Project menu. If desired.NET) projects.licx file (or the file will not contain an appropriate run-time license for the component) and therefore licensing will fail. Creating components at design time This is the most common scenario and also the simplest: the user adds one or more controls to the form. then removing that component. or to display some information reminding the user that the software has not been licensed. the project will not contain a licenses. which is used to store all run-time licenses for all components directly hosted by WebForms in the application. to throw an exception and fail altogether.dll must always be deployed with the application. it appears if you press the Show All Files button in the Solution Explorer's Toolbox. None will throw licensing exceptions and prevent applications from running.NET 1. the App_licenses. All ComponentOne products are designed to display licensing information if the product is not licensed. To fix this problem. which Visual Studio saves in the following two files:   An assembly resource file which contains the actual run-time license A "licenses.licx file is a simple text file that contains strong names and version information for each of the licensed components used in the application. Common Scenarios The following topics describe some of the licensing scenarios you may encounter.licx file is usually not shown in the Solution Explorer. In WinForms and ASP.licx" file that contains the licensed component strong name and version information These files are automatically added to the project. Adding an instance of the component to a form. You do not need an instance of the component on the form. Note that editing or adding an appropriate line to this file can force Visual Studio to add run-time licenses of other controls as well. when the component is created at run time. In this case. This will create the licenses. or from Visual Studio's main menu.x applications. but would like to create one or more instances at run time. 14 . In ASP. Creating components at run time This is also a fairly common scenario. and the component works. When Visual Studio recreates the application resources. Whenever Visual Studio is called upon to rebuild the application resources.licx file has been created). Later. is just a simple way of adding a line with the component strong name to the licenses. The licenses.x applications. Note that the licenses. Note that the mechanism is exactly the same for Windows Forms and Web Forms (ASP.NET 2. Enter the following: /ASSEMBLYRESOURCE:Debug\MyApp. For example: [LicenseProvider(typeof(LicenseProvider))] class MyGrid: C1. When the component is added to a form.licx /i:C1.exe file and also a licenses. 2. In the Properties window. 4.licx file into the console application project. The command line should look like this: c1lc /target:MyApp.dll Link the licenses into the project.licx file. extra steps must be taken to compile the licensing resources and link them to the project. the licensing information to be stored in the form is still needed.Win.licx file from the app directory to the target folder (Debug or Release). 3. To fix this problem. Then close the Windows Forms application and copy the licenses.licx file in the Solution Explorer window and select Properties.licx file is configured as an embedded resource. and go to the Linker/Command Line option. it has bugs.C1FlexGrid { // . you will need to take one of the actions previously described create a component at run time. Build the C++ project as usual.licx file as in the previous scenario. This should create an . go back to Visual Studio. As before. Copy the licenses. Using licensed components in Visual C++ applications There is an issue in VC++ 2003 where the licenses. This will embed the licensing information into the licenses.exe utility and the licensed dlls to the target folder.licx is ignored during the build process.) Use C1Lc. This can be done in two ways:  Add a LicenseProvider attribute to the component.C1FlexGrid.Win. select properties.exe /complist:licenses.licx file has been created. To do this.C1FlexGrid. To do this.licx file with licensing information in it. right-click the project. This will mark the derived component class as licensed. and the assembly is a DLL. In these cases. and therefore Visual Studio won't create a licenses. Copy the C1Lc.. Make sure the licenses. the licensing information is not included in VC++ applications. This restriction is necessary to prevent a derived control class assembly from being used in other applications without a design-time license. that C1 licensing will not accept a run-time license for a derived control if the run-time license is embedded in the same assembly as the derived class definition. Using licensed components in console applications When building console applications.. and the base component will find it and use it. Visual Studio will create and manage the licenses.exe. (Don't use the standard lc. and the base class will handle the licensing process as usual.licx file.licenses 15 . Note the following: 1.licx file. No additional work is needed. If you create such an assembly. there are no forms to add components to. 5.exe. set the Build Action property to Embedded Resource. right-click the licenses. create a temporary Windows Forms application and add all the desired licensed components to a form. }  Add an instance of the base component to the form.exe to compile the licenses. Please note. the extra instance can be deleted after the licenses.Inheriting from licensed components If a component that inherits from a licensed component is created. therefore. It requires a designtime license to be installed on the testing machine. This can be avoided by adding the string "C1CheckForDesignLicenseAtRuntime" to the AssemblyConfiguration attribute of the assembly that contains or derives from ComponentOne controls. Licensing 2. and the install is running in Maintenance Mode. Updating or renewing a license If you renew your subscription. For example: [AssemblyConfiguration("C1CheckForDesignLicenseAtRuntime.. remove the old license and 16 . For example: #if AUTOMATED_TESTING [AssemblyConfiguration("C1CheckForDesignLicenseAtRuntime")] #endif public class MyDerivedControl : C1LicensedControl { // . you must have a valid license in the registry on your machine. Follow the instructions in the setup.. then open the About Box of the 1. the 2. and there is no easy way to add it. then open the About Box of either an ASP. Run the ComponentOne Studio for Mobile Devices 2.0 setup.6. 2. If you still need to install a new serial number. If you have a valid license installed already. follow these steps: 1.0 setup. Common Scenarios in Mobile Applications The following topics describe some of the licensing scenarios you may encounter when working with Mobile components. Using licensed components with automated testing products Automated testing products that load assemblies dynamically may cause them to display license dialog boxes. This is the expected behavior since the test application typically does not contain the necessary licensing information. run the install again. There are cases where the setup may not prompt you. If you need to enter your serial number for an install. } Note that the AssemblyConfiguration string may contain additional text before or after the given string. the new license must be installed. If the Mobile controls are licensed through a Studio Enterprise subscription.NET control or a . you will not be prompted to enter your serial number. Distributing or installing the license on other computers is a violation of the EULA. and enter the serial number when prompted.BetaVersion")] THIS METHOD SHOULD ONLY BE USED UNDER THE SCENARIO DESCRIBED.x Mobile Controls through the Setup To enter the serial number (license) through the Studio for Mobile Devices 2. or if you are installing a version of the controls that has already been installed (Maintenance Mode). If you are still not prompted for a serial number by the time you get to the install screen. This attribute value directs the ComponentOne controls to use design-time licenses at run time.x version of a Mobile control or run the setup again to enter your serial number. If the Mobile controls are licensed through a Studio for Mobile Devices subscription. therefore. Once you uninstall.x versions of the Mobile controls do not have the option to license or register from the About Box. Rebuild the executable to include the licensing information in the application. Presently. it is necessary to license through another component or the setup. you will need to uninstall first. so the AssemblyConfiguration attribute can be used for other purposes as well.NET Windows forms control and update the license by clicking the License button and entering your serial number. There is a utility available that will remove the old license for you. Now you can close the program and run your Studio for Mobile Devices setup again to enter your new serial number. To do this. To remove a Studio for Mobile Devices license with the license remover. click OK when you get the dialog box. 17 . Unzip and run the C1LicBomb. I have a licensed version of a ComponentOne product but I still get the splash screen when I run my project. you will need to enter your Studio Enterprise serial number again. follow these steps: 1. include at least one instance of the control on a form in the assembly that is instantiated BEFORE the dynamically created instance is created. 4. but it forces the IDE to update SupportInfo and embed the new run-time license. 3.exe. and then toggle it back to its original value. To accomplish this. 2. It either doesn't exist. Instantiating a Mobile control at run time The Mobile controls behave the same way as other ComponentOne controls when they are created at run time and not placed on the form at design time. If the new serial number that you wish to enter for Studio for Mobile Devices is not a Studio Enterprise serial number. 5. 6. You will be asked if you are sure that you want to delete each key. which can be found below. If this happens. Because the IDE does not have an opportunity to obtain a run-time license on its own in this case. There will also be a dialog box to let you know that a particular key was removed successfully.then run the setup again. it is necessary to force Visual Studio to update the control properties stored in the form. Once a control of the same type is licensed. enter your serial number when prompted. click OK for that one also. Studio for Mobile Devices. and individual Studio Mobile product licenses. It is necessary for the control to regenerate the license embedded in its SupportInfo property. Updating a project after renewing a license Once you have installed a new license. Below is a description of the most common problems and their solutions. otherwise. This results in no changes or side effects in the control configuration. Follow through with the setup. select both for removal. each project must be updated in order to use the new control. If you see both Studio Enterprise and Studio for Mobile devices listed.licx file in the project. it is necessary to force the IDE to include a run-time license. then click the Remove Selected Licenses button. or is not configured correctly. contains wrong information. The simplest choice is to toggle a Boolean property such as the Visible property. but problems may occur for a number of reasons. Troubleshooting We try very hard to make the licensing mechanism as unobtrusive as possible. The easiest way to do this is to simply modify a property. Select any other licenses you wish to remove. rebuilding the control is not sufficient. but this can be done through any of the About Boxes for C1 controls with the exception of the Mobile Studio About Boxes. and ComponentOne Studio for Mobile Devices will be licensed on your machine. there may be a problem with the licenses. License Remover The license remover will search for the following licenses on your system: Studio Enterprise. select the one that you see. You will see an application with a list of the installed licenses on your machine. all others on the form are accepted as licensed. Any licenses that are found will be populated into a list so that you can select the ones that you would like to remove. 1.exe or .licx file or follow the alternate procedure following. Check the Solution Explorer window. I downloaded a new build of a component that I have purchased. This will usually rebuild the correct licensing resources. Select the Rebuild Licenses option (this will rebuild the App_Licenses. For ASP.licx tab.NET 2. 2. Click the Show All Files button on the top of the window. 4. Find the licenses. 2. Click the Show All Files button on the top of the window.licx file and open it.x applications. 4. 3. follow these steps: For ASP. 5. Rebuild the project using the Rebuild All option (not just Rebuild). Rebuild the project using the Rebuild All option (not just Rebuild). and now I'm getting the splash screen when I build my projects.licx file and delete it. you must be sure to rebuild and update the user control whenever the licensed embedded controls are updated. The components must be licensed on the development machine. 18 . 1. obtain the appropriate data from another licenses.NET application uses WinForms user controls with constituent licensed controls. After that. the application can be deployed on any machine. 5. including Web servers. 3. In this case. Open the project and go to the Solution Explorer window. Rebuild the project using the Rebuild All option (not just Rebuild). Find the licenses. Open the project and go to the Solution Explorer window. 6. Find the licenses. your subscription may have expired.dll assembly created during development of the application is deployed to the bin application bin directory on the Web server. you have two options: Option 1 – Renew your subscription to get a new serial number.licx file and right-click it. 7. Make sure that the serial number is still valid.licx file). the run-time license is embedded in the WinForms user control assembly. Save the file. follow these steps: I have a licensed version of a ComponentOne product on my Web server but the components still behave as unlicensed. In this case. If that fails follow these steps: 1.licx file there. 3. 6. continue to open the file. If prompted. Open the project and go to the Solution Explorer window. try a full rebuild (Rebuild All from the Visual Studio Build menu).First. be sure that the App_Licenses. Alternatively. If you licensed the component over a year ago. If the component does not appear in the file. there should be a licenses.NET 2.dll) when the project is built. Change the version number of each component to the appropriate value. Open the main form and add an instance of each licensed control. If your ASP. therefore the licensing information will be saved into the executable (. then close the licenses. 4.x applications. There is no need to install any licenses on machines used as servers and not used for development. Close the project and reopen it. 2. visit the ComponentOne Web site at http://www.4738). This email will provide you with an Issue Reference ID and will provide you with a set of possible answers to your question from our Knowledgebase.If you choose this option. Version Release History. You can continue to use the components you received or downloaded while your subscription was valid. While ComponentOne does not provide direct support in the forums and newsgroups. you'll immediately receive a response via e-mail confirming that you've successfully created an incident. Technical Support ComponentOne offers various support options.com/SuperProducts/SupportServices/. When you submit an incident. Option 2 – Continue to use the components you have.componentone. You may use it to develop applications in conjunction with Microsoft Visual Studio or any other programming environment that enables the user to use and integrate the control(s). Please note that e-mail sent to the Documentation team is for documentation feedback only. please email the Documentation team.componentone. we periodically monitor them to ensure accuracy of information and provide comments when appropriate. products do not. Redistributable Files ComponentOne FlexGrid for WinForms is developed and published by ComponentOne LLC. ComponentOne sponsors these areas as a forum for users to share information. Documentation Microsoft integrated ComponentOne documentation can be installed with each of our products. tips. Peer-to-Peer Product Forums ComponentOne peer-to-peer product forums are available to exchange information. You may also distribute. If you have suggestions on how we can improve our documentation. Please note that this does not include issues related to distributing a product to end-users in an application. Contact technical support by using the online incident submission form or by phone (412. Subscriptions expire. You will receive a response from one of the ComponentOne staff members via e-mail in 2 business days or less. searchable Online Help and more. For a complete list and a description of each. searchable Knowledge base. Some methods for obtaining technical support include:  Online Resources ComponentOne provides customers with a comprehensive set of technical resources in the form of FAQs.681. the following 19 .com/. Please note that a ComponentOne User Account is required to participate in the ComponentOne Product Forums. Online Support via our Incident Submission Form This online support service provides you with direct access to our Technical Support staff via an online incident submission form. We recommend this as the first place to look for answers to your technical questions. Installation Issues Registered users can obtain help with problems installing ComponentOne products. Technical Support and Sales issues should be sent directly to their respective departments. and techniques regarding ComponentOne products. samples and videos. The new subscription will entitle you to a full year of upgrades and to download the latest maintenance builds directly from http://prerelease. and documentation is also available online.     Note: You must create a ComponentOne Account and register your product with a valid serial number to obtain support using some of the above methods. free of royalties. you will receive a new serial number that you can use to license the new components (from the installation utility or directly from the About Box). Design.C1FlexGrid.4343 412. Windows.dll C1.dll C1. The namespace for the C1FlexGrid control is C1.2.CF.componentone.Classic. Assemblies can contain multiple namespaces.Win.CF.C1FlexGrid.C1FlexGrid 20 .Designer.Win.4384 (Fax) http://www. The general namespace for ComponentOne Windows products is C1.Win.com for details.C1FlexGrid.dll Site licenses are available for groups of multiple developers. The following code fragment shows how to declare a C1FlexGrid control using the fully qualified name for this class:  Visual Basic Dim flex As C1.CF. Windows Vista.Designer.Redistributable Files with any such application you develop to the extent that they are used separately on a single CPU on the client/workstation side of the network:      C1.C1FlexGrid.4.CF.dll C1.3.C1FlexGrid. please call us or write: Corporate Headquarters ComponentOne LLC 201 South Highland Avenue 3rd Floor Pittsburgh.dll C1.2. and Visual Studio are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.Win.dll The following Redistributable Files apply to ComponentOne FlexGrid for Mobile Devices and ComponentOne MaskEdit for Mobile Devices:     C1.C1FlexGrid. Office. PA 15206 • USA 412.dll C1Win.Win.C1FlexGrid.Classic.681.3.C1FlexGrid. Please contact [email protected]. Namespaces prevent ambiguity and simplify references when using large groups of objects such as class libraries. which can in turn contain other namespaces.C1FlexGrid.2.C1FlexGrid. About This Documentation Acknowledgements Microsoft. Access. Windows Server.com/ ComponentOne Doc-To-Help This documentation was produced using ComponentOne Doc-To-Help® Enterprise. Namespaces Namespaces organize the objects defined in an assembly.Win. ComponentOne If you have any suggestions or ideas for new features or controls.dll C1.681.dll C1.Win. Excel. You can use objects defined in other projects if you create a reference to the class (by choosing Add Reference from the Project menu) and then use the fully qualified name for the object in your code.Win. in which the developer of a class library is hampered by the use of similar names in another library.C1FlexGrid flex.Column  C# // Define a new Column object (custom Column class). The New Project dialog box opens. Namespaces address a problem sometimes known as namespace pollution. From the File menu in Microsoft Visual Studio .Win.Column Imports MyColumn = MyProject. However.Column Dim c1 As C1Column Dim c2 As MyColumn  C# using C1Column = C1.C1FlexGrid.Column. So. complete the following steps: 1. MyColumn c2.C1FlexGrid. Dim FlexCol as C1. using MyColumn = MyProject. For example.NET.C1FlexGrid.Win. The following code snippet demonstrates how to declare these objects:  Visual Basic ' Define a new Column object (custom Column class).C1FlexGrid. Column MyCol. you can use the Imports statement (import in C#) to define an alias — an abbreviated name you can use in place of a fully qualified name. Visual Studio . select New Project.NET Project To create a new . and uses these aliases to define two objects:  Visual Basic Imports C1Column = C1. Dim MyCol as Column ' Define a new C1FlexGrid.Column. Fully qualified names are object references that are prefixed with the name of the namespace where the object is defined. These conflicts with existing components are sometimes called name collisions.Win. you must use a fully qualified reference to make the reference unique. C1Column c1.Column object.Win. To get around this. the C1FlexGrid assembly also implements a class called Column. if you create a new class named Column.C1FlexGrid. If you use the Imports statement without an alias.Column object. C1. 21 . the names themselves can get long and cumbersome. Creating a . if you want to use the C1FlexGrid class in the same project. For example.NET project. you can use it inside your project without qualification. // Define a new C1FlexGrid.NET produces an error stating that the name is ambiguous. you can use all the names in that namespace without qualification provided they are unique to the project. the following code snippet creates aliases for two fully qualified names. If the reference is not unique. C# C1. Fully qualified names prevent naming conflicts because the compiler can always determine which object is being used. However.Column FlexCol. 4. see Adding the C1FlexGrid Components to a Project (page 22). Expand the Smart Device node and select one of the smart devices listed. ComponentOne FlexGrid for WinForms provides the following controls:   C1FlexGrid C1FlexGridClassic To use C1FlexGrid. and select Windows Application from the list of Templates in the right pane. and a new Form1 is displayed in the Designer view. Under Project Types. A new Microsoft Visual Studio . Creating a Mobile Device Application To create a new . the Create a ComponentOne Visual Studio Toolbox Tab checkbox is checked. If you decide to uncheck the Create a ComponentOne Visual Studio Toolbox Tab checkbox during installation. Enter a name for your application in the Name field and click OK. Make sure the Toolbox is visible (select Toolbox in the View menu if necessary) and right-click it to open the context menu. you can manually add ComponentOne controls to the Toolbox at a later time.C1FlexGrid assembly to your project. choose either Visual Basic or Visual C#. Double-click the desired component from the Toolbox to add it to Form1. When you open Visual Studio. Enter a name in the Name textbox and click OK. 2.NET project is created and a new Form1 is displayed in the Designer view. 3.Win. For information on adding a component to the Toolbox. by default.NET. Note that one of these options may be located under Other Languages. Select Device Application from the list of Templates in the right pane.0 device application project. 1.NET 2. expand the Visual Basic or Visual C# node. C1FlexGrid C1FlexGridClassic Open the Visual Studio IDE (Microsoft Development Environment). see Adding the C1FlexGrid Components to a Project (page 22). Adding the C1FlexGrid Components to a Project When you install ComponentOne Studio for WinForms.NET 2. Under Project Types. add these controls to the form or add a reference to the C1. The New Project dialog box opens.0 tab containing the ComponentOne controls has automatically been added to the Toolbox. From the File menu in Microsoft Visual Studio . select New Project. complete the following steps.2. For information on adding a component to the Toolbox. To manually add the C1FlexGrid control to the Visual Studio Toolbox: 22 . Double-click the C1FlexGrid components from the Toolbox to add them to Form1. you will notice a ComponentOne Studio for . the following C1FlexGrid components will appear in the Visual Studio Toolbox customization dialog box:   1. 3. Manually Adding C1FlexGrid to the Toolbox When you install C1FlexGrid. A new project is created. in the installation wizard. 4. 5. 6. 2.dll file and click OK.Win. Sort the list by Namespace (click the Namespace column header) and check the check boxes for all components belonging to namespace C1. 3. Select the ComponentOne C1FlexGrid assembly from the list on the . select Add Tab from the context menu and type in the tab name.NET tab or browse to find the C1.2.NET Framework Components tab. 3. C1FlexGrid. See Namespaces (page 20) for more information. 2.C1FlexGrid. At the top of the file. add the following Imports statements (using in C#): Imports C1. for example.Win. The Choose Toolbox Items dialog box opens. Adding C1FlexGrid to the Form To add C1FlexGrid to a form: 1.C1FlexGrid Note: This makes the objects defined in the C1FlexGrid assembly visible to the project.C1FlexGrid. Double-click the form caption area to open the code window. Add it to the Visual Studio Toolbox. Right-click the tab where the component is to appear and select Choose Items from the context menu. 4. select the . 23 . 2. In the dialog box. Adding a Reference to the Assembly To add a reference to the C1FlexGrid assembly: 1. Note that there may be more than one component for each namespace.Win. Double-click the control or drag it onto your form. Select the Add Reference option from the Project menu of your project. To make C1FlexGrid and C1FlexGridClassic component appear on its own tab in the Toolbox. C1FlexGrid the same way.licx file.vb or Form. Right-click the References node and select Add Reference. In the Solution Explorer. First. the .cs file in the Solution Explorer to reopen it. The project opens. Go to the Solution Explorer (View | Solution Explorer) and click the Show All Files button. 24 . Also remove C1. right-click C1. Click Next. you must convert your project to Visual Studio 2005. Close to close the form and then double-click the Form. which includes removing any references to a previous assembly and adding a reference to the new assembly.licx file appears in the list of files. Select File. 4. Secondly. Open Visual Studio 2005 and select File. The Conversion Complete window appears.licx. 10.Common and select Remove. 3.C1FlexGrid. 4. 9. Locate and select C1. 6. updated version of the . Select Yes. create a backup before converting to create a backup of your current project and click Next.licx file and select Delete. right-click the licenses. Note: The Show All Files button does not appear in the Solution Explorer toolbar if the Solution project node is selected. 7.Migrating a C1FlexGrid Project to Visual Studio 2005 To migrate a project using ComponentOne components to Visual Studio 2005. 2. The new . The new licenses. 2. 8.Win. must be updated in order for the project to run correctly. Click OK to permanently delete licenses. Click OK to add it to the project. To update the .licx file: 1.licx file may not be visible in the Solution Explorer. Click Close. 3. The project must be rebuilt to create a new. Locate the .Win. Select it and click Open. Open Project. Click Show the conversion log when the wizard is closed if you want to view the conversion log.2.dlls and add references to the new ones. The Visual Studio Conversion Wizard appears. To convert the project: 1.sln file for the project that you wish to convert to Visual Studio 2005. Now you must remove references to any of the previous ComponentOne . 5. Expand the References node. 11. there are two main steps that must be performed. Click the Start Debugging button to compile and run the project.dll.licx file. Click Finish to convert your project to Visual Studio 2005. The migration process is complete. or licensing file. margins.  Make it a Tree By setting the IsNode property for certain rows you can transform FlexGrid into a TreeView. When bound.  Enhance Your UI with Microsoft Office 2007 and 2010 Styling FlexGrid supports Visual Styles that mimic the styles available in Office 2007 and 2010. Silver. cell buttons. and footer text.NET. and more. including ADO. and Black.NET data source.  Display Images and Data in Cells Each grid cell can display images in addition to data. drop-down lists and combo lists. or you can show a dialog box to let your users select and set up the printer. where the grid itself manages the data. You can also scale images and add transparency. and advanced data validation to control the editing process. 25 . add repeating header rows.  Add Special Drawing Effects Make the grid look the way you want it to by painting special effects such as lines.  Hierarchical Styles View data the way that's best for you and your users with powerful properties and methods. or in unbound mode. bitmaps. For example.Key Features Some of the key features of ComponentOne FlexGrid for WinForms that you may find useful include:  Code-free Development Set up columns and styles at design time with easy-to-use editors accessible from the SmartTag. Completely manage your grid without writing any code!  Enhanced Cell Editing Use simple text editing. Printing events allow you to control page breaks. each master record can be expanded/collapsed to show/hide the details in child grids. which may in turn contain more details. where it displays data from any .  Flexible Data Binding Use the grid in bound mode.  Integrated Printing Print your grid with a single statement! You have control over paper orientation. you can summarize data and add aggregate values with the C1FlexGrid. reorder columns. you can use an input mask to provide a template that automatically validates data as your users type. an easy and efficient way to display database information graphically. the control detects subordinate data sources and creates additional instances of itself to display child tables.NET and ComponentOne DataObjects for . The column editor allows you to insert and remove columns. masks.  Child Tables for Displaying Hierarchical Data When FlexGrid is bound to a hierarchical data source. or add custom elements to each page. Modify existing styles and add custom styles with the style editor. including Blue. For example. The result is a "data tree" similar to the type of grid presented by Microsoft Access when displaying hierarchical data. and icons in appropriate grid cells. This is accomplished by deriving a control (C1FlexDataTree) from the C1FlexGrid control. You can even bind grid columns to image lists. adjust column widths. or choose to prevent users from editing specific columns altogether.Subtotal method or use the Tree property to display hierarchical views of the data. You get a TreeView that has all the features of a rich datagrid. You can later refer to a column using a ColIndex(ColKey) syntax.   Range Aggregates Calculate totals.xls. Column keys are automatically assigned to field names when the grid is data-bound.  Built-in Data Filtering Allow users to apply filters to each column on the grid by setting the AllowFiltering property. if desired. Assign Field Names to Columns Refer to columns by name instead of position. making them span multiple rows or columns to enhance appearance or clarity. averages.xlsx (OpenXml format) files. . You can also load grid data from a database using DataReader objects. 26 . . which will retrieve the column you want even if your user has moved it to a different position on the grid. or you may assign them with code.  Merged Cells Merge contiguous like-valued cells. or Open XML files with other extensions. and other statistics for ranges of cells with a single statement! Multiple File Formats for Saving/Loading Data Load from and save grid contents to text. For more in-depth tutorials. 5. A simple grid application will appear. Add a C1FlexGrid control to the form. 2. This sets the grid's Dock property to Fill so the grid will fill the form. see C1FlexGrid Tasks Menu (page 40). Run the program. Create a new project. click the Test Connection button to make sure that you have successfully connected to the database or server and click OK. Leave the default setting. 1. Click OK again to close the Add Connection dialog box. In the Add Connection dialog box. see C1FlexGrid Tasks Menu (page 40). Congratulations! You have successfully created a simple grid application. 3. 8. 1. click Dock in parent container. For more information on how to create a new project. The Data Source Configuration Wizard appears. but rather provide a quick start and highlight some general approaches to using the product. 4. This section is not supposed to be a comprehensive tutorial on all features of C1FlexGrid. When you click New Connection.FlexGrid for WinForms Quick Start In this section you will learn how to use the basic C1FlexGrid functionality to create a simple grid application. 4. For more information on accessing the C1FlexGrid Tasks menu. In the Select Microsoft Access Database File dialog box. 2. and click Next.mdb database in the C:\Documents and Settings\<username>\My Documents\ComponentOne Samples\Common (Windows XP) or C:\Users\<username>\Documents\ComponentOne Samples\Common (Vista) directory. Step 1 of 3: Creating the FlexGrid for WinForms Application The following steps will walk you through creating a simple grid application.mdb file and click Open. the Add Connection dialog box appears. Leave Microsoft Access Database File as the Data source. 27 . see Creating a . 3. In the next topic. the steps may be slightly different in other versions of Visual Studio. click the Choose Data Source drop-down arrow and select the Add Project Data Source link from the drop-down box. For more information on accessing the C1FlexGrid Tasks menu. 6. Click the Browse button under Database file name. see the FlexGrid for WinForms Tutorials (page 113). leave Dataset selected and click Next. Visual Studio 2010 was used in this example. Select the NWind. you will learn how to bind the C1FlexGrid control to a data source. Step 2 of 3: Binding C1FlexGrid to a Data Source The following steps will walk you through binding a data source to the grid application you created in the Step 1 of 3: Creating the FlexGrid for WinForms Application (page 27) topic. selected on the Choose a Data Source Type page.NET Project (page 21). Open the C1FlexGrid Tasks menu. browse to the NWind. In the C1FlexGrid Tasks menu. 7. 5. Click the New Connection button to create a new connection or choose one from the drop-down list. Open the C1FlexGrid Tasks menu. In the C1FlexGrid Tasks menu. 9. On the Choose a Database Model page. Database. Additionally. A DataSet and connection string are added to your project. Enter ProductsDS in the DataSet name box and click Finish to exit the wizard.ProductsTableAdapter.Fill(this. Visual Studio automatically creates the following code to fill the DataSet:   Visual Basic Me. Run the program and observe the following: Notice that the data from the Products table is reflected in the grid.Products). expand the Tables node.10. 11. and built-in styles. In the next topic. 1. Save the connection string in the application configuration file by checking the Yes. and built-in styles for the grid. Visual Style. click No. Visual Styles. and select the Products table.productsDS. Congratulations! You have successfully bound the grid application to a data source.productsTableAdapter. Since it is not necessary to copy the database to your project. you will learn how to customize format strings. On the Choose Your Database Objects page. save the connection as box and entering a name. Click the Next button to continue. A dialog box will appear asking if you would like to add the data file to your project and modify the connection string. 12.ProductsDS. Click the Next button to continue. 13.Products) C# this. Resize the first column in the grid by dragging the horizontal double arrow that appears at the right edge of the first column's header to the left until the UnitPrice column is visible: 28 .Fill(Me. Step 3 of 3: Customizing C1FlexGrid Settings The following steps will walk you through setting a format string. 2. Click the UnitPrice column to open the Column Tasks menu. 3. 4. 5. Click the ellipsis button next to the Format String text box to open the Format String dialog box. In the Format String dialog box, select Currency under Format type and click OK. In the Properties window, locate the VisualStyle property and set it to Office2007Blue. 29 6. 7. 8. 9. Open the C1FlexGrid Tasks menu. The Column Tasks menu will appear since we last edited a column using the Tasks menu. Select C1FlexGrid Tasks to return to the C1FlexGrid Tasks menu. On the C1FlexGrid Tasks menu, select Styles to open the C1FlexGrid Style Editor (page 33). In the C1FlexGrid Style Editor under Built-In Styles, select Fixed. Expand the Font node in the right pane and set the Bold property to True. 10. Set the ForeColor property to CornflowerBlue on the Web tab and click OK to close the dialog box. Run the program and observe the following: The grid application displays a the Products table using a format string, Visual Style, and built-in styles. You have successfully set the format string, Visual Style, and built-in styles for the grid. This concludes the Quick Start. 30 Design-Time Support You can easily configure ComponentOne FlexGrid for WinForms at design time using the property grid, menus, and designers in Visual Studio. The following sections describe how to use C1FlexGrid's design-time environment to configure the C1FlexGrid control. C1FlexGrid Editors There two are design-time editors that allow you to control the layout and appearance of C1FlexGrid, C1FlexGrid Column Editor and C1FlexGrid Style Editor. Additionally, Caption Style and Column Style are two design-time editors that allow you to change the appearance of a specific caption or column. C1FlexGrid Column Editor If you prefer, you can set up the grid columns at design time instead of writing code to do it. The designer can be accessed in one of three ways:    Select the grid in Design view, go to the Properties window and click the ellipsis button (…) next to the Cols property. Right-click the control and select Designer from the context menu. Click on the smart tag ( Tasks menu. ) in the upper right corner of the grid and select Designer from the C1FlexGrid This will bring up the Column Editor shown below: In bound mode, the editor can be used to select which fields in the DataSource should be displayed, their order, column captions, widths, and alignment. In unbound mode, the editor is also used to select column data types. The editor allows you to perform the following actions: 31   Reorder Columns: You can move columns to new positions by dragging them by the header cells with the mouse. Adjust Column Widths: You can adjust column widths with the mouse, by dragging the right edge of the header cells with the mouse. You can also select multiple columns by SHIFT-clicking the header cells, and then set all column widths at once using the property window. Setting the column width to –1 restores the default width. Set Column Properties: Whenever one or more columns are selected, you can see and edit their properties in the property grid on the left of the editor. Insert or Remove Columns: Use the toolbar to insert columns before or after the selection (useful mostly in unbound mode), or to remove columns. Use the Toolbar to Perform Common Tasks: The table below describes the function of the buttons on the toolbar:    Button Description Font: Sets the selected font in the drop-down list. Font Size: Sets the selected font size in the drop-down list. Font Formatting: Applies bold, italics or underline to the font. Justification: Sets the font alignment to left, center, right or general. Alignment: Aligns column content to the top, center, or bottom. These buttons only affect the scrollable area of the grid. To set the alignment for the header columns, select the columns and set the TextAlignFixed property. BackColor: Sets the backcolor of the selected column. ForeColor: Sets the forecolor of the selected column. Apply to Fixed Rows: Applies the settings to fixed rows. Help: Displays or hides the description for the selected property. Undo: Cancels all changes and reverts the grid columns to their original state. AutoResize: Determines whether the grid should automatically resize all columns to fit their contents when the grid is bound to a data source. Reload from Datasource: Resets all columns with information from the current DataSource. This button is useful when the grid is bound to a data source and you want to start editing from scratch. The button is disabled when the grid is not bound to a data source. 32 it will be hidden. Click on the smart tag ( ) in the upper right corner of the grid and select Styles from the C1FlexGrid Tasks menu. Toggle Visibility: Displays or hides a column. Right-click the grid and select Styles from the context menu. go to the Properties window and click the ellipsis button next to the Styles property. You can see how your new style appears in the preview area above the style properties. rows. Insert Column: Inserts columns to the left or right of the selection. The grid will display the C1FlexGrid Style Editor dialog box. C1FlexGrid Style Editor If you prefer. The style editor lets you modify existing styles and add new custom ones. Show Hidden Columns: Shows hidden columns. 33 . and therefore you won't be able to select it with the mouse. Delete Column: Removes the selected column. Unhide All Columns: Makes all columns visible.Selected Column: Selects the current column from the drop-down list. Use this button to show all hidden columns so you can select and edit them. Column Width: Sets the column width of all selected columns to the same width. and columns. which may later be assigned to cells. wider or narrower. Determine whether the properties for the selected columns should be displayed in categorized or alphabetical order. you can set up styles at design time instead of writing code to do it. Use the Add button to add a custom style. The C1FlexGrid Style Editor can be accessed in one of three ways:    Select the grid. If you change the Visible property of a column to False. The Remove button removes the selected custom style. The AutoFormat button brings up a secondary dialog box that allows you to select a complete set of predefined styles. The Clear button removes all custom styles and restores the built-in styles to their default values. Here's what the AutoFormat dialog box looks like: 34 . You can rename custom styles by selecting them on the list and typing the new name. as well as alignment. The Caption Style and Column Style editors have four tabs: Text. Background. respectively. background. see Column Tasks Menu (page 42). Text The Text tab sets the font and formatting of the caption. The Caption Style and Column Style editors can only be accessed in the Column Tasks menu. Alignment.Caption Style and Column Style The Caption Style editor and the Column Style editor for a selected column allow you to specify the properties for the caption text and column text. For more information on the Column Tasks menu. and borders. and Borders. 35 . The Preview area allows you to view your settings before applying them to the grid. The following options are available in the Formatting area: 36 . Effect: Choose from Flat.The following options are available in the Font area:           Name: Choose a font name. Character. Raised. Font Effects: Use the buttons to toggle bold. see the TextEffectEnum Enumeration. For more details on the text effect options. and underline on or off. For more details on the Input Mask dialog box. Up or Down. italic. or EllipsisPath to set how long strings are trimmed to fit the cell. Word Wrap: Check the box to enable word wrapping for the caption. Trimming: Choose from None. Input Mask: Click the ellipsis button to open the Input Mask dialog box. see Cell Content (page 52). For more details on the Format String dialog box. Format: Click the ellipsis button to open the Format String dialog box. or Inset. Direction: Choose from Normal. EllipsisCharacter. EllipsisWord. Color: Choose a font color. see Masks (page 64). Size: Choose a font size. Word. Stack. Align Right.Alignment The Alignment tab sets the alignment of both text and images in the caption. Vertical: Click the buttons to toggle between Align Top. TileStretch. Overlay. Clip: Click the buttons to toggle between image alignment in the cell or Scale. and Align General. The following options are available in the Text Alignment area:    Horizontal: Click the buttons to toggle between Align Left. Stretch. and Align Bottom. For more details on the image alignment options. ImageOnly. Show Sample Image: Check the Show Sample Image box to display a sample image in the Preview area. The following options are available in the Image Alignment area:    The following options are available in the Display area: 37 . or None. Display: Choose from TextOnly. or Hide the image. Text/Image Spacing: Increase or decrease this value to increase or decrease the amount of space between the text and the image. see the ImageAlignEnum Enumeration. Align Center. Tile. see the DisplayEnum Enumeration. Align Middle. For more details on the display options. The following option is available in the Background Color area:    Borders The Background tab sets the borders and margins. The following options are available in the Background Image area: 38 .Background The Background tab sets the background color and background image. Color: Choose a color for the background of the cell. Layout: Toggle between Scale. Image: Click the Select button to select an image or the Clear button to remove an image. Tile. or Hide. TileStretch. Stretch. see the BorderDirEnum Enumeration.Win. see the C1.C1FlexGrid. For details on the different border direction options.The following options are available in the Borders area:     Style: Choose from None. Bottom: Increase or decrease the value to increase or decrease the bottom margin. or Dotted. Inset. Right: Increase or decrease the value to increase or decrease the right margin. ) represents a short-cut Tasks menu that provides the most commonly used properties in each 39 . Groove. Top: Increase or decrease the value to increase or decrease the top margin. Color: Choose a color for the border. Double. Horizontal. Raised. The following options are available in the Margins area:     C1FlexGrid Smart Tag A smart tag ( control.BorderStyleEnum Enumeration. For details on the different border style options. Flat. Direction: Choose from Both. Width: Increase or decrease the value to increase or decrease the width of the border. or Vertical. Fillet. Left: Increase or decrease the value to increase or decrease the left margin. click Add Project Data Source to open the Data Source Configuration Wizard. as well as set the following properties: AllowAddNew. The default is checked. The default is checked. and allows adding new rows to the grid. To add a new data source to the project. Enable Deleting Rows Selecting the Enable Deleting Rows check box sets the AllowDelete property to True. AllowEditing. you can quickly access the C1FlexGrid Column Editor and the C1FlexGrid Style Editor. To access the C1FlexGrid Tasks menu. Enable Adding Rows Selecting the Enable Adding Rows check box sets the AllowAddNew property to True. ) in the upper right corner of the grid. see Binding to a Data Source (page 101). For more information on how to add a new data source to the project. and allows deleting rows in the grid. AllowDelete. The default is unchecked. Enable Editing Selecting the Enable Editing check box sets the AllowEditing property to True. and AllowDragging.There are two Tasks menus available through the smart tag in C1FlexGrid: C1FlexGrid Tasks Menu (page 40) and Column Tasks Menu (page 42). C1FlexGrid Tasks Menu In the C1FlexGrid Tasks menu. and allows editing in the grid. and allows dragging of columns in the grid. Display Hidden Columns 40 . This will Choose Data Source Clicking the drop-down arrow in the Choose Data Source box opens a list of available data sources and allows you to add a new data source. The default is unchecked. Enable Column Reordering Selecting the Enable Column Reordering check box sets the AllowDragging property to Columns. click on the smart tag ( open the C1FlexGrid Tasks menu. 41 . see C1FlexGrid Column Editor (page 31). Designer Clicking Designer opens the C1FlexGrid Column Editor. Styles Clicking Styles opens the C1FlexGrid Style Editor. For more information on how to edit columns with the C1FlexGrid Column Editor. The default is unchecked.Selecting the Display Hidden Columns check box sets the Visible property to True for hidden columns and displays them. For more information on how to customize cell appearance with the C1FlexGrid Style Editor, see C1FlexGrid Style Editor (page 33). Column Tasks Clicking Column Tasks opens the Column Tasks menu. For details on the Column Tasks menu, see Column Tasks Menu (page 42). About C1FlexGrid Clicking About C1FlexGrid displays the About ComponentOne C1FlexGrid dialog box, which is helpful in finding the version number of C1FlexGrid. Dock in parent container/Undock in parent container Clicking Dock in parent container sets the Dock property for C1FlexGrid to Fill. If C1FlexGrid is docked in the parent container, the option to undock C1FlexGrid from the parent container will be available. Clicking Undock in parent container sets the Dock property for C1FlexGrid to None. Column Tasks Menu The Column Tasks menu allows you to set the column caption, data field, data type, edit mask, format string, and combo list for a column, as well as set the following properties: AllowSorting, AllowEditing, AllowResizing, AllowDragging, AllowMerging, and Visible. 42 To access the Column Tasks menu, either click on a column in the grid or select Column Tasks from the C1FlexGrid Tasks menu. Column Caption Entering a caption into the Column Caption box set the Caption property for the column. Data Field Clicking the drop-down arrow in the Data Field box opens a list of available fields in the data source. Data Type Clicking the drop-down arrow in the Data Type box opens a list of available data types. Edit Mask Clicking the ellipsis button in the Edit Mask box opens the Input Mask dialog box. Format String Clicking the ellipsis button in the Format String box opens the Format String dialog box. Combo List Clicking the ellipsis button in the Combo List box opens the Combo List dialog box. Allow Sorting Selecting the Allow Sorting check box sets the AllowSorting property to True, and allows sorting in the column. The default is checked. Allow Editing Selecting the Allow Editing check box sets the AllowEditing property to True, and allows editing in the column. The default is checked. Allow Resizing Selecting the Allow Resizing check box sets the AllowResizing property to True, and allows resizing the column. The default is checked. Allow Dragging Selecting the Allow Dragging check box sets the AllowDragging property to True, and allows dragging columns in the grid. The default is checked. Allow Merging Selecting the Allow Merging check box sets the AllowMerging property to True, and allows merging in the column. The default is unchecked. Visible Selecting the Visible check box sets the Visible property to True, and allows the column to be visible in the grid. The default is checked. Caption Style Clicking Caption Style opens the Caption Style editor for the selected column, which allows you to specify the properties for the caption text, including alignment, background, and borders. Column Style Clicking Column Style opens the Column Style editor for the selected column, which allows you to specify properties for the column, including text, alignment, background, and borders. C1FlexGrid Tasks 43 Clicking C1FlexGrid Tasks returns you to the C1FlexGrid Tasks menu. For details on the C1FlexGrid Tasks menu, see C1FlexGrid Tasks Menu (page 40). Dock in parent container/Undock in parent container Clicking Dock in parent container sets the Dock property for C1FlexGrid to Fill. If C1FlexGrid is docked in the parent container, the option to undock C1FlexGrid from the parent container will be available. Clicking Undock in parent container sets the Dock property for C1FlexGrid to None. 44 Using the C1FlexGrid Control The C1FlexGrid control allows you to display, edit, group and summarize data in a grid format. The grid can be bound to a data source or it can manage its own data. The C1FlexGrid control has a rich object model with the following elements: 45 The following topics walk you through the main features in the C1FlexGrid control: 46 . ) Fixed rows remain on the top of the grid when the user scrolls the grid vertically. or exchange grid data with other applications such as Microsoft Access and Excel. Cell Images (page 51) Describes how to display images in a cell. C1FlexGrid Property Groups (page 99) Presents a map of the main C1FlexGrid properties cross-referenced by function.Rows.  There are two basic types of rows and columns: fixed and scrollable. or by changing fonts. _flex. When the grid is bound to a data source. Saving. Outlining and Summarizing Data (page 73) Describes how to add subtotals to grids and how to build outline trees. Rows and Columns A C1FlexGrid control consists of rows and columns. Loading. and pictures for individual cells or ranges. the number of rows and columns is determined by how much data is available in the data source. creating "grouped" views that highlight relationships in the data.Rows and Columns (page 47) Describes how to set up the grid dimensions and layout. and Boolean values.Count = 500 _flex.Count = 500. Cell Selection (page 49) Describes the concepts of "current cell" and "selection". dates. and data validation.Cols. In unbound mode. cell buttons. This section also shows how you can print grids. Editing Cells (page 57) Describes how to implement simple text editing.Cols. and fixed columns remain on the left of the grid when the user scrolls the grid horizontally. drop-down lists and combo lists. the code below sets the grid dimensions to 500 rows by 10 columns:  Visual Basic _flex.Rows. Formatting Cells (page 52) Describes how to customize the appearance of the grid by formatting numbers. For example.Count = 10 C# _flex. editing masks. alignment. The collections of rows and columns is exposed by the Rows and Cols properties. (The counts returned by the Count property include fixed and scrollable cells. Cell Ranges (page 51) Describes how to work with a group of cells as a single unit. and Printing (page 90) Describes how you can save the contents or formatting of a grid and re-load it later. Merging Cells (page 68) Describes how to change the grid display so that cells with similar contents are merged. colors. you can set them to arbitrary values using the Count property in the collections.Count = 10. 47 . You can set the number of fixed rows and columns using the Fixed property in the Rows and Cols collections.Rows. 48 . and moving rows and columns on the grid.Fixed cells are useful for displaying row and column header information. In the grid. see C1FlexGrid Column Editor (page 31). deleting. clicking and dragging the horizontal double arrow that appears at the right edge of a column's header allows the column to be resized.Fixed = 1 _flex.Fixed = 0.Cols. For details on editing columns using the C1FlexGrid Column Editor. _flex.Cols. For example. the code below creates a grid with two fixed rows and no fixed columns:  Visual Basic _flex.  The Rows and Cols collections also contain methods for inserting. At design time. If you prefer.Rows. the Width property can be set directly in the grid or through the C1FlexGrid Column Editor.Fixed = 1. You can use their Item property (an indexer) to access individual elements (rows and columns) in each collection. you can set up the grid columns at design time instead of writing code to do it using the C1FlexGrid Column Editor.Fixed = 0 C# _flex. Column Sizing The width of a column is determined by its Width property. The following code sets the Width property of Column1 to 10:   Visual Basic _flex.The dotted vertical line indicates how the grid will be resized. dragging it to the right makes the column larger. or in code. Cell Selection The grid has a cursor cell. The user may move the cursor with the keyboard or the mouse.Cols(1).Width = 10. The following code sets the AllowResizing property for Column1 to False:   Visual Basic _flex. set the AllowResizing property for the column to False either in the Column Tasks menu or C1FlexGrid Column Editor. see C1FlexGrid Column Editor (page 31).Cols[1].Cols[1]. see Column Tasks Menu (page 42). In the C1FlexGrid Column Editor or in code. To prevent resizing a specific column. and edit the contents of the cell if the grid is editable.Width = 10 C# _flex. For details on the Column Tasks menu. Dragging the pointer to the left makes the column smaller. which displays a focus rectangle while the grid is active.Cols(1). The column's Width property will be adjusted when the resize operation is complete.AllowResizing = false. For details on the C1FlexGrid Column Editor. specify the value of the Width property for a column. 49 .AllowResizing = False C# _flex. the grid supports regular range selections. to select by row. see Customizing Appearance Using Visual Styles (page 171). The grid supports extended selections. the selection is automatically reset. For more information about setting the Visual Style. or by using the Select method.Count .Fixed To _flex. The type of selection available is determined by the SelectionMode property.Rows. HighLight determines when the selection should be highlighted (always.Rows. You can also retrieve a collection of selected rows using the Selected property. You can get or set the current cell in code using the Row and Col properties.Win. "Sales")) > 80000 Then _flex. You can get or set the selection cell in code using the RowSel and ColSel properties. For more information about setting the Visual Style. By default. _flex. HighLight and Focus are cell styles that determine the appearance of the selection (font. For example. To create extended selections in code. Setting either of these properties to –1 hides the cursor.SelectionMode = C1. or in listbox mode (listbox mode allows you to select individual rows).Selected = True End If Next 50 . when the control has the focus. or use the Select method.Rows(index). You can modify this behavior to prevent extended selections. see Customizing Appearance Using Visual Styles (page 171). color.SelectionModeEnum.ListBox Dim index As Integer For index = _flex. the code below selects all rows that satisfy a condition:  Visual Basic 'Selects all rows with more than 8000 sales in the Sales column. When using the listbox selection mode. Note: When the cursor cell changes.Notice that the Office Visual Styles also indicate the location of the cursor cell by highlighting the row and column headers of the cursor cell's position. rectangular ranges of cells defined by two opposing corners: the cursor cell and the cell selection cell. either set Row and Col before RowSel and ColSel. Notice that the Office Visual Styles also indicate the location of the extended selection by highlighting the row and column headers of the selected cells.1 If Val(_flex(index. by column. The appearance of the selection is controlled by the following properties:    FocusRect determines the type of focus rectangle that is drawn to indicate the cursor cell. and border). you can get or set the selection status for individual rows using the Selected property.C1FlexGrid. or never). _flex. } } Console. 10). 10. 10.Styles["MyRangeStyle"]. For example.Rows[index].Rows.StyleNew. 3.CompilerServices. if one exists.Runtime.Red C# CellRange rg = _flex.Style = _flex. you can write:  Visual Basic Dim rg As CellRange = _flex.GetCellRange(3.ListBox. This method allows you to assign arbitrary images to each cell. 10. for (int index = _flex. You can assign an ImageMap to the column and the grid will automatically map the cell data into a corresponding image. rg. if all you want to do is give the range a red background.Styles("MyRangeStyle") C# CellRange rg = _flex. and returns it. 3.  The CellRange object has a StyleNew property that retrieves the range style.Selected. _flex.Rows.Count).Rows.GetCellRange(3.WriteLine("There are now {0} rows selected". index < _flex. or creates a new one. This property is convenient in situations where you don't need full-fledged control over formatting. For example.SelectionMode = SelectionModeEnum.Data = Nothing rg. clears the data in the range.BackColor = Color. "Sales"])) > 80000) { _flex. and assigns it a custom style:  Visual Basic Dim rg As CellRange = _flex. For example. 3.GetObjectValue(_flex[index.Count)  C# // Selects all rows with more than 8000 sales in the Sales column.Fixed .Conversion.Data = null.Rows. rg.Selected.GetCellRange(3. rg.GetCellRange(3. index++) { if (Microsoft.  Cell Images Each grid cell can display images in addition to the data stored in the cell.WriteLine("There are now {0} rows selected".Runti meHelpers.  51 . This method is useful in situations where the image contains a representation of the data.StyleNew.BackColor = Color. 10) rg. 10) rg.VisualBasic.Red. and is useful if the images are not related to the data in the cell.Console. 10). Cell Ranges CellRange objects allow you to work on arbitrary groups of cells as a single unit. the images may contain icons that represent product types.Val(System. This can be done in two ways:  You can assign an Image object to a cell using the SetCellImage method. 10.Selected = true.Count. assigns it to the range.Style = _flex. 3. _flex. you may want to use a picture as an indicator that the data in the cell is invalid. the code below creates a CellRange object. For example. _flex.000. Retrieving Cell Data You can retrieve the raw grid data using the indexers or the GetData method.Cols(2).Cols[2]. 2)) ' Raw value: 10000 ' Display value: $10. _flex.Cols(1).00 52 . _flex.Format = "d" ' Currency.Format = "d". click the ellipsis button in the Format String box. For example.GetDataDisplay(1. The formatting of cell content can also be set at design time using the Format String dialog box. To retrieve the formatted data. You can also use custom formats like the ones used in the Visual Basic Format function (for example. and click the ellipsis button next to it.NET framework. the code below shows short dates on column one and currency values on column two:  Visual Basic ' Short date. In the C1FlexGrid Column Editor. and so on). Cell Content To control how the content of the cells is formatted.Cols(1).Format = "d" ' Currency.Format = "c"  C# // Short date. 2)) Console.Cols(2). _flex(1. Note: The Format String dialog box is column specific and will only change the Format property of the selected column. locate the Format property in the left pane. use the GetDataDisplay method instead. 2) = 10000 Console. _flex. _flex.Formatting Cells One of the main strengths of the C1FlexGrid control is the ability to customize almost every aspect of the appearance of the entire grid and individual cells. "#.WriteLine("Raw value: {0}". // Currency.Format method in the .   In the Column Tasks menu. set the Format property to a format string similar to the ones you use with the String. _flex.WriteLine("Display value: {0}".###".Format = "c" _flex(1. _flex. The Format String dialog box can be accessed through the Column Tasks menu or through the C1FlexGrid Column Editor.Format = "c".Cols[1]. For example:  Visual Basic ' Short date. borders.Count .WriteLine("Raw value: {0}".1. index += 5) { _flex.Red C# CellStyle cs = _flex.Green. and so on. 2]).Rows(idex).Format = "d". cs.ForeColor = Color. the code below creates a custom cell style and assigns it to every fifth row:  Visual Basic Dim cs As CellStyle = _flex.ForeColor = Color. Changing the built-in styles is the simplest way to change the appearance of the grid. For example.Green cs.Style = cs. _flex[1. You can change these styles to modify the way the grid looks. focus cell. or columns.Rows[index]. colors.000. FontStyle. C# // Short date. such as fixed and scrollable cells.Add("Fifth"). rows. index <= _flex.Add("Fifth") cs. selection. and you can also create your own custom styles and assign them to cells.Red.Count .Cols[2].BackColor = Color. cs.Font = new Font(_flex. _flex. FontStyle. and cell ranges: 53 . // Raw value: 10000 // Display value: $10.BackColor = Color. }  Here's an example that shows how you can create custom styles and assign them to columns. rows and columns. Console.Cols[1]. // Currency. the code below displays the selection as bold green characters over a red background:  Visual Basic Dim cs As CellStyle = _flex. cs. font.1 Step 5 _flex. For example.Font = New Font(_flex.Fixed . This collection has some built-in members that define the appearance of grid elements.Gray Dim idex% For idex = _flex.Bold) cs.BackColor = Color. cs. 2] = 10000.Rows. for (int index = _flex.Style = cs Next C# CellStyle cs = _flex.Format = "c".Styles.  You can also create your own styles and assign them to cells.Rows.Bold). and so on) is handled with CellStyle objects.WriteLine("Display value: {0}".Rows. _flex.Highlight cs.Fixed To _flex. Console.GetDataDisplay(1.Styles. The grid has a Styles property that holds the collection of styles used to format the grid.Highlight.Styles. rows.Font. _flex[1.Styles.Gray.BackColor = Color.Font.Rows. 2)). _flex.00 Cell Appearance The appearance of the cells (alignment. For example.Style = _flex.C1FlexGrid. If you prefer.Style = _flex.Win.ForeColor = Color. see C1FlexGrid Style Editor (page 33).Styles.4. // Assign the new style to a cell range.Styles["MyStyle"].EventArgs) Handles MyBase.Load ' Create a custom style for large values. 4. // Assign the new style to a column. ByVal e As System.Add("LargeValue") cs.GetCellRange(4.Add("MyStyle") s.6.6).CellStyle Private Sub Form1_Load(ByVal sender As System. 6.Style = _flex.Styles.Object.Font = New Font(Font. _flex. = Color. FontStyle. _flex.White ' Assign the new style to a column.Style = _flex.Styles.Add("MyStyle"). Dim s As CellStyle = _flex. Conditional Formatting To format cells based on their contents.BackColor s. cs = _flex.Style = _flex.Styles("MyStyle")  C# // Create a CellStyle s s. CellRange rg = _flex. 6) rg. _flex. you can use the CellChanged event to select a style for the cell based on its contents.Rows[3].GetCellRange(4.Red. For details on customizing cell appearance with the C1FlexGrid Style Editor.Styles("MyStyle") ' Assign the new style to a cell range.Cols[3].CellChanged 54 .BackColor = Color. Private Sub _flex_CellChanged(ByVal sender As Object. // Assign the new style to a row.White. ByVal e As RowColEventArgs) Handles _flex.BackColor = Color.Cols(3). Visual Basic ' Create a new custom style.ForeColor new custom style. Dim rg As CellRange = _flex. you can set up styles at design time using the C1FlexGrid Style Editor instead of writing code to do it.Italic) cs.Styles("MyStyle") ' Assign the new style to a row.Rows(3).Red s.Styles["MyStyle"].Gold End Sub ' Format cells based on their content. = _flex.Styles["MyStyle"].Style = _flex. rg. the code below creates a new style for large currency values and applies it to cells based on their contents:  Visual Basic Dim cs As C1. = Color. _flex. or draw some custom graphics directly into a cell.' Mark currency values > 50. You can also change the style that will be used to display the cell by setting the e.DrawCell to display the cell borders and content.Row. For example. instead of setting e. 55 .Col].ToString()) >= 50000) { cs = _flex.Text and e.Row. } // Format cells based on their content. Instead. cs = _flex. FontStyle. and so on). cs). private void Form1_Load(object sender.Gold. assign a new CellStyle object to the Style parameter. You can change the text and image that will be shown in the cell by setting the e.BackColor = Color. if (Microsoft.Style.Col).Row.DrawCell method.Style = _flex.Font = new Font(Font.ForeColor = Color. _flex. The event allows you to override every visual aspect of the cell.Style property. you can use the DrawMode property and the OwnerDrawCell event to gain total control over how each cell is drawn.VisualBasic.Italic).Styles["RedStyle"]. assign a whole new style to the parameter using e. cs) End If End Sub  C# CellStyle cs.Col. You can also use your own drawing code to draw into the cell.SetCellStyle(e. For example.Add("LargeValue"). e. Note that you should not modify the properties of the Style parameter because that might affect other cells. e. or to take over completely and draw whatever you want into the cell. margins. cs. alignment.000 as LargeValues (reset others by setting their Style to Nothing). In these cases. borders.Image parameters in the event handler. The DrawMode property determines whether or not the OwnerDrawCell event is fired. cs. RowColEventArgs e) { // Mark currency values > 50. private void _flex_CellChanged( object sender. the style used to display the data.ToDouble(_flex[e.SetCellStyle(e.Styles("LargeValue") _flex. You may want to use a gradient background. e. sometimes that is not enough.Col. The parameters in the OwnerDrawCell event allow you to change the data that is displayed.Styles.Conversions.ToString >= 50000 Then cs = _flex. and even combine your custom code with calls to the e.CompilerServices. EventArgs e) { // Create a custom style for large values. e.Red. font.Styles["LargeValue"].Row.000 as LargeValues reset others by setting their Style to null). you could paint the cell background using GDI calls and then call e. } } Owner-Drawn Cells Even though the CellStyle objects offer a lot of control over the cell appearance (back and foreground colors. Dim cs As CellStyle If _flex(e. Object.Drawing. The code below shows an example. EventArgs e) { // Brush to use with owner-draw cells.Drawing2D. Color.LinearGradientBrush Private Sub Form1_Load(ByVal sender As System.SteelBlue.DrawMode = DrawModeEnum. ByVal e As System.White. see the RtfGrid sample on ComponentOne HelpCentral.LinearGradientBrush(ClientRectangle. 45) ' Use owner-draw to add gradients.Drawing2D. // Use owner-draw to add gradients.Drawing.EventArgs e) { // Update gradient brush when the control is resized. ByVal e As System.White. Color.Win. private void Form1_Load(object sender.Resize ' Update gradient brush when the control is resized.EventArgs) Handles _flex. System. 45) End Sub  C# System.Drawing2D.C1FlexGrid. First. Color. It uses a gradient brush to paint the background of the selected cells. declares a LinearGradientBrush object and updates the brush whenever the grid is resized:  Visual Basic Dim m_GradientBrush As System. 45).LinearGradientBrush(ClientRectangle.Drawing. Color. 45). the code sets the DrawMode property. m_GradientBrush = New System. Color.LinearGradientBrush m_GradientBrush.LinearGradientBrush(ClientRectangle. Color.EventArgs) Handles MyBase. Color.Drawing2D.DrawModeEnum.Drawing.Drawing2D.Sample Project Available For an example of advanced Owner-Draw Cells.Drawing.SteelBlue. m_GradientBrush = New System.Drawing. _flex. m_GradientBrush = new System.SteelBlue.DrawMode = C1.LinearGradientBrush(ClientRectangle.Load ' Brush to use with owner-draw cells. } 56 . } private void _flex_Resize( object sender.White. Color. m_GradientBrush = new System.SteelBlue.Drawing2D.OwnerDraw.OwnerDraw End Sub Private Sub _flex_Resize(ByVal sender As Object.White. _flex. Handled = True End If End Sub  C# private void _flex_OwnerDrawCell( object sender. the user can:    Start typing into the cell.Selection.Bounds).Col)) { // Draw the background. e. it detects which columns are editable and automatically sets the AllowEditing property. If the user types a value that cannot be converted into the proper data type. This replaces the contents of the cell.C1FlexGrid. but the cursor appears where the cell is clicked. 57 .FillRectangle(m_GradientBrush. e. Double-click a cell. This has the same effect as pressing F2. the C1FlexGrid control allows users to edit cells by typing into them. You can also prevent users from editing specific columns by settings the AllowEditing property to False.Col) Then ' Draw the background.Selection. e. If the column being edited has a specific data type. The basic editing mode allows users to type values into the cells. OwnerDrawCellEventArgs e) { // Draw the selected cell background using gradient brush. Press F2 or ENTER. the grid fires a GridError event and ignores the edits.DrawCell(DrawCellFlags. values entered by the user are converted into the proper data type automatically.Handled = true.Graphics.DrawCell(C1. e.OwnerDrawCellEventArgs) Handles _flex. // Let the grid draw the content. e. e. If _flex.Contains(e.Win. if (_flex.) To start editing a cell.Win. } } Editing Cells By default.DrawCellFlags. e.OwnerDrawCell ' Draw the selected cell background using gradient brush. e.FillRectangle(m_GradientBrush. using the DrawCell method in the event argument:  Visual Basic Private Sub _flex_OwnerDrawCell(ByVal sender As Object.C1FlexGrid. In this example. e. (When the grid is bound to a data source.Bounds) ' Let the grid draw the content.Row. This puts the grid in edit mode and puts the current cell contents in the editor.Graphics.Contains(e. // We're done drawing this cell.Content). You can prevent users from editing the grid by setting the AllowEditing property to False. ByVal e As C1.Row. the foreground is handled by the grid itself.Content) ' We're done drawing this cell.The second step is handling the OwnerDrawCell event and using the custom brush for painting the cell background. e. _flex.Cols[1]. The Combo List dialog box allows you to choose if you want the list to appear as a Dropdown List. Another common situation is where cells have a list of common values. the code below would cause the grid to display a drop-down combolist containing color names on column one. Ellipsis Button. the user can pick a value or type in something else:  Visual Basic ' Drop-down list. To create combos.ComboList = "|Red|Green|Blue|Red|White".Cols[2]. you can let users select the value from a drop-down list.Cols(2).ComboList = "|Red|Green|Blue|Red|White"  C# // Drop-down list.5. or TextBox and Ellipsis Button. "True|False|Don't know") and assign it to the ComboList property. build a string containing all the choices separated by pipe characters (for example. This can be accomplished with drop-down combos. _flex. In these cases. the C1FlexGrid also has built-in support for external editors. but the C1FlexGrid has properties and events that allow you to control the editing process and provide selection lists. editing buttons.ComboList = "Red|Green|Blue|Red|White" ' Drop-down combo. To do this.ComboList = "Red|Green|Blue|Red|White".The basic editing is sufficient for many applications. // Drop-down combo. The user can click the box (or press F2) to display the list of choices available for that cell. These features are described in the following topics. Each column may have a different list. and advanced validation control. When editing column one. Lists and Combos In many applications. then assign it to the ComboList property as before. Dropdown Combo. a combination of text box and dropdown list. but users should be allowed to type something else as well. Setting the ComboList property causes the grid to display a drop-down box next to the cell. _flex. and a drop-down combo on column two. _flex. For example. the user must pick a value from the list. When editing column two. you can now use the C1Input controls as grid editors). The ComboList property can also be set at design time using the Combo List dialog box. This allows you to use any control as a grid editor (for example. Starting with version 2. cells have a well-defined list of possible values.Cols(1). just start the choice list with a pipe character (for example "|True|False|Don't know"). 58 . the grid will automatically select the next value.   In the Column Tasks menu.Cols["bools"]. The ComboList property applies to the whole grid. For example:   Visual Basic _flex. The built-in ComboBox provides an auto-search feature by default. the grid displays values in Boolean columns as checkboxes (the type of the column is determined by the DataType property of the Column object). When you double-click a cell that has a list associated with it. click the ellipsis button in the Combo List box.No". locate the ComboList property in the left pane.No" C# _flex.Format = "Yes. For example.Format = "Yes. The values depend on the property. so valid choices change from one row to the next. The built-in ComboBox also has an auto-cycle feature like the editors in the Visual Studio Properties window.The Combo List dialog box can be accessed through the Column Tasks menu or through the C1FlexGrid Column Editor. Checkboxes By default. In some cases. You can disable this feature using the EditOptions property and control the time before the grid resets the auto-search buffer using the AutoSearchDelay property. 59 . a property list may show properties on the first column and their values on the second. set the column's Format property to a string containing the values that should be displayed for True and False values. In these cases. As the user types a value. If you don't want Boolean values displayed as checkboxes. the selection will move to the next match. You can also disable this feature using the EditOptions property. you should trap the BeforeEdit event and set the ComboList property to the appropriate list for the current cell.Cols("bools"). Note: The Combo List dialog box is column specific and will only change the ComboList property of the selected column. and click the ellipsis button next to it. In the C1FlexGrid Column Editor. cells in the same column may need different lists. The difference is that when they are used in editable columns.DataType = typeof(Color). "Sky"). "Coal") dtMap. "Forest"). "Snow") _flex.Black. _flex. You can disable this feature using the EditOptions property. "Forest") dtMap.Add(Color. This property contains a reference to an IDictionary object that establishes the mapping between what is stored in the grid and what is visible to the user (the IDictionary interface is defined in the System. toggling the value of checkbox with the mouse or keyboard will toggle all selected checkboxes. The colors are stored in the grid.Red. the code below creates a data map that contains color values and their names.DataType = GetType(Color) _flex.Collections namespace.White. and SortedList all provide valid data maps. _flex. Note that the keys in the data map must be of the same type as the cells being edited.TSGrayed.Hashtable().TSUnchecked and CheckEnum.Red.Collections.Cols[1]. dtMap.  Any class that implements IDictionary can be used as a DataMap. dtMap. then any data maps associated with the column should have short integer keys.Add(Color.Add(Color.In unbound mode. In many cases. "Snow").Hashtable dtMap = new System.Collections. Hashtable uses an arbitrary order.Green.Add(Color.White. Hashtable.DataMap = dtMap.Add(Color.Add(Color. but you want to display a user-friendly version of the actual value.Cols[1]. Using regular integers (Int32) as keys would not work.Green. if a column contains product codes. and ListDictionary keeps the order in which items were added to the list. Value-Mapped Lists The ComboList property described above ensures that cell values are selected from a list. The value selected by the user is converted into the appropriate type for the column and stored in the grid. The SortedList class sorts items by key. If the cell has a check box and the AllowEditing property is set to True. the order of the items in the drop down list will depend on the class. Because of this. the user can change the state of the check boxes by clicking them with the mouse or by pressing the SPACE bar or ENTER keys. ListDictionary is usually the best choice for DataMaps. The checkboxes will be displayed along with any text in the cell. ListDictionary. For example. and is implemented by the Hashtable class among others). dtMap. "Apple") dtMap. For example. "Apple"). "Sky") dtMap. "Coal").DataMap = dtMap C# System.TSChecked and CheckEnum. you can use the GetCellCheck and SetCellCheck properties to add checkboxes to any cells. This is accomplished with the DataMap property. if a column contains short integers (Int16).Checked and CheckEnum. Boolean check boxes toggle between the CheckEnum.Add(Color.Add(Color. 60 . There are two types of check boxes: Boolean and tri-state. and their names are displayed to the user:  Visual Basic Dim dtMap As Hashtable = New Hashtable() dtMap. exactly as if the user had typed the value.Unchecked states. For example.Black. cells can assume values from well-defined lists. By default. you may want to store the code but display the product name instead. dtMap. and you can set their position using the column's ImageAlign property. Tri-state check boxes cycle through the settings CheckEnum. dtMap.Add(Color.Blue.Blue.Cols(1). For example.Cols(1).Add(Color. Cols(1).DataMap _flex.Specialized. "One") ht.Load ' Sorts by key. sl. Dim ht As New Hashtable() ht.Collections.Add(1.Add(1.Collections. "One").Add(0. { // Sorts by key. ht. 61 .Add("0". ht. "Three"). ld. Dim ld As New Specialized.Add(3.Cols(1). sl.Add(2.SortedList sl = new System.Add(0. "Two"). "Zero").Hashtable ht = new System. sl.Add("3".Add(2. // Arbitrary order.Add(1. ld.EventArgs) Handles MyBase. "Zero") sl.Add("3". "Two") ld. sl.Collections. System.Collections.Hashtable().Add(3.Add("1".SortedList().Add(2.Add(1. ByVal e As System. "Two"). System. "One"). ld. "Zero") ht. "Two") sl. "Three") _flex.Add("1".ListDictionary() ld.Caption _flex.DataMap _flex. "One"). System.Add("0".Caption _flex.Add(0.Cols(3).ListDictionary(). "Three") ' Keeps Add order. "Two") ht. System.ListDictionary ld = new System. "Zero") ld.Add(3.Add("2".Collections.Object.Add(0.Collections.The example below shows the difference:  Visual Basic Private Sub Form1_Load(ByVal sender As System.Cols(2).Cols(2). // Keeps Add order. "Three") ' Arbitrary order.Caption End Sub  = = = = = = sl "SortedList" ld "ListDictionary" ht "HashTable" C# private void Form1_Load(object sender. ld. "One") sl.Add("2". "Three").Cols(3).EventArgs e). "Zero"). Dim sl As New SortedList() sl. "Zero"). "One") ld.Specialized.DataMap _flex. } = = = = = = sl. and their names are displayed to the user:  Visual Basic Private Enum Countries NewYork Chicago NewOrleans London Paris End Enum Private Sub Form1_Load(ByVal sender As System. You can assign pictures to the cell buttons using the CellButtonImage property.Cols[3]. and update the cell's contents with the user's selection. EventArgs e) { _flex. London. the grid will automatically build and use a data map with the names of each value in the enumeration. if the column's DataType property is set to an enumeration.Cols[3]. ht.Add(2.DataMap _flex. By default. Cell Buttons Certain types of cells may require sophisticated editors other than text boxes or drop-down lists. ht. The country values are stored in the grid. the cell buttons display the ellipsis.EventArgs) Handles MyBase. The control will display a button next to the cell and will fire the CellButtonClick event when the user clicks on it.DataType = GetType(Countries) End Sub  C# private enum Countries { NewYork. "HashTable".Caption } Also.Cols(1). "Three"). In these cases.Add(3. "Two").DataMap _flex.Cols[2]. If you add a pipe character before the ellipsis. you should set the ComboList property to an ellipsis ("…").DataType = typeof(Countries).DataMap _flex. 62 .Caption _flex.Cols[1].Caption _flex. For example. _flex. You can trap the event.Object.Cols[1].Cols[1]. "SortedList". then the user will also be allowed to edit the cell contents by typing into the cell. "ListDictionary". if a column contains file names or a color.Load _flex. ld. the following code creates an enumeration containing countries.Cols[2]. For example. ByVal e As System. it should be edited with a dialog box. show the dialog box. Chicago. NewOrleans. Paris } private void Form1_Load(object sender.ht. If _flex(e.The example below shows how you can use cell buttons to display a color picker dialog box for choosing a color in a column. c.Row.. c.Column = _flex.Col) End If ' Get new color from dialog and assign it to the cell. } } 63 .Col] = clrDlg.Row.DataType = typeof(Color).Cols(1) c. e.Col]. The next step is the code that handles clicks on the cell button:  Visual Basic Private Sub _flex_CellButtonClick(ByVal sender As Object. This code sets up the column so the user can click a button and select a color from a dialog box.Row. Dim c As C1. e.RowColEventArgs) Handles _flex. e.Row. Column c = _flex.Col) = clrDlg.Win.C1FlexGrid.C1FlexGrid.Row.OK Then _flex(e.DialogResult.Color = _flex(e.Row.Col) Is GetType(Color) Then clrDlg. Dim clrDlg As New ColorDialog() ' Initialize the dialog. e.Cols[1].Color End If End Sub  C# private void _flex_CellButtonClick( object sender. If clrDlg.CellButtonClick ' Create color picker dialog.OK) { _flex[e. RowColEventArgs e) { // Create color picker dialog.Col] == typeof(Color)) { clrDlg..Color = (Color)_flex[e.  Visual Basic ' Set up color column. if (clrDlg.. ByVal e As C1. // Initialize the dialog.ComboList = ".ShowDialog() == DialogResult. e."  C# // Set up color column. c. ColorDialog clrDlg = new ColorDialog(). if (_flex[e. // Show cell button.Color.ComboList = ".DataType = GetType(Color) ' Show cell button.".Forms. } // Get new color from dialog and assign it to the cell.Win.ShowDialog() = Windows.. e. _flex.Cols(1).Cols[1]. _flex. which become part of the input.Cols(1). which can be used with regular text fields and with drop-down combo fields. This is especially convenient if you have DateTime columns that hold times only (not dates). Mask strings have two types of characters: literal characters. 64 . _flex. _flex.Cols[1].EditMask = "(999) 999-9999".EditMask = "99:99 LL" C# _flex. even if the column contains date/time values (usually. which holds phone numbers (the digit "9" is a placeholder that stands for any digit):  Visual Basic ' Set up a phone number edit mask.Format = "hh:mm tt".  The EditMask property can also be set at design time using the Input Mask dialog box.Cols[1]. This type of editing uses an input mask to provide a template and automatically validate the input as the user types. and template characters.EditMask = "99:99 LL".Cols(1). For example.Cols(1).EditMask = "(999) 999-9999" C# // Set up a phone number edit mask. a DateTimePicker control is used to edit these columns).Masks The C1FlexGrid control also supports masked editing.DataType = typeof(DateTime). The mask is specified by the EditMask property.DataType = GetType(DateTime) _flex.Format = "hh:mm tt" _flex. In these cases.Cols[1]. you can set the following properties to use a masked editor instead of the DateTimePicker control:  Visual Basic _flex. the code below assigns a "(999) 999-9999" editing mask to column one. digits or alphabetic).  Setting the EditMask property to a non-empty string causes it to use the built-in masked editor. which serve as placeholders for characters belonging to specific categories (for example. Editor.Cancel = True End Try End If End Sub  C# private void _flex_ValidateEdit( object sender. edit masks alone are not enough to ensure that the data enters by the user was valid.Text). If the input is invalid.000 and 10.Show("Value not recognized as a Currency") e.Show("Value must be between 1. if (_flex.000") e.Col]. trap the BeforeEdit event and set the EditMask property to an appropriate value for the current cell.Col).Cols(e. For example.   In the Column Tasks menu. For details on the syntax used to build the mask strings. and click the ellipsis button next to it.Parse(_flex. ValidateEditEventArgs e) { // Validate amounts.C1FlexGrid. ByVal e As C1.Parse(_flex. a mask won't let you specify a range of possible values.DataType Is GetType(Decimal) Then Try Dim dec As Decimal = Decimal.Win. or validate the current cell based on the contents of another cell.Text property is a valid entry for the current cell (at this point.Editor.DataType == typeof(Decimal)) { try { Decimal dec = Decimal. In these cases.Cols[e. trap the ValidateEdit event and see if the value contained in the Editor. In the C1FlexGrid Column Editor. click the ellipsis button in the Edit Mask box. set the Cancel parameter to True and the grid will remain in edit mode until the user types a valid entry. If _flex. if ( dec < 1000 || dec > 10000 ) 65 . locate the EditMask property in the left pane.Cancel = True End If Catch MessageBox. see the EditMask property in the control reference section. If different cells in the same column need different masks.Text()) If (dec < 1000) Or (dec > 10000) Then MessageBox. the cell still has the original value in it).ValidateEdit ' Validate amounts. the code below validates input into a currency column to ensure that values entered are between 1.ValidateEditEventArgs) Handles _flex.000:  Visual Basic Private Sub _flex_ValidateEdit(ByVal sender As Object. For example.The Input Mask dialog box can be accessed through the Column Tasks menu or through the C1FlexGrid Column Editor.000 and 10. Validation In many cases. Note: The Input Mask dialog box is column specific and will only change the EditMask property of the selected column. In the C1FlexGrid Column Editor. 2. Any control that derives from the base Control class can be used as a basic grid editor. For example. follow these steps: 1. For more information on accessing the C1FlexGrid Column Editor. ByVal e As System.Cols(1). 3.{ MessageBox. For details on the IC1EmbeddedEditor interface.Cancel = true. the control will be automatically used by the grid. or a specialized control that you wrote to edit your business objects. Add a C1FlexGrid control to the form. For example. select the first scrollable grid column and set its Editor property to NumericUpDown1.Cancel = true.Show("Value not recognized as a Currency").EventArgs) Handles MyBase. After that. see the Editor property. but in some cases you may want to use external controls as specialized editors.Show("Value must be between 1. Select the columns that should use the custom editor and set their Editor properties to the name of the new editor control. or an editor for selecting from multi-column lists. You can do this in the designer (using the Column Editor) or in code.000 and 10.None ' Assign the custom editor to the grid. e. Notice how the grid positions and initializes the NumericUpDown control so you can edit cell values. You can also assign custom editors to the grid using code:  Visual Basic Private Sub Form1_Load(ByVal sender As System.dll) can provide better integration with the grid and more advanced features.BorderStyle = BorderStyle. Run the project and edit some values in the first column. see Accessing the C1FlexGrid Column Editor (page 149). To use a control as a custom editor. you may want to use the C1NumericInput control that provides a drop-down calculator for entering numbers. add an instance of the editor control to the form. To define custom editors at design time.Load ' Create the custom editor. _flex. } } catch { MessageBox. Add a NumericUpDown control to the form and set its BorderStyle property to None.Editor = editor End Sub 66 . Select Designer from the C1FlexGrid Tasks menu. click a different cell or press the TAB key to move to the next one.Object. all you have to do is associate an instance of the control with a grid column or a style using its Editor property.000").Common. Controls that implement the IC1EmbeddedEditor interface (defined in C1. to use a NumericUpDown control as a grid editor. Dim editor as New NumericUpDown() editor. } } } Custom Editors The built-in editors provide a lot of flexibility and power. 4. e. Notice how the new value is applied to the cell. When you are done editing a cell. then select Designer from the C1FlexGrid Tasks menu to open the C1FlexGrid Column Editor. You can put the grid in edit mode programmatically using the StartEditing method. file names.EventArgs e) { // Create the custom editor. Only implement the ones that make sense to your editor control. _flex. you need a wrapper class that: 1. the grid is not in edit mode. all controls in the C1Input library support IC1EmbeddedEditor and therefore integrate closely with C1FlexGrid (and also C1TrueDBGrid). and finish editing using the FinishEditing method. In these cases. We provide source code for this wrapper class in the CustomEditors sample. Encapsulates the appropriate UITypeEditor.Cols[1]. custom. and UITypeEditor editors with C1FlexGrid. Otherwise. . For example. fonts. In some cases. In many cases this level of support is adequate. } Creating Custom Editors Any control that derives from the Control base class can be used as a grid editor. and events such as Leave and TextChanged. the grid fires the following sequence of events: Event Description 67 . you don't even have to implement all its members. Derives from Control (UITypeEditor doesn't). you may want to use controls that do not follow the base class that closely. For example. editor. System.BorderStyle = BorderStyle. To do this. a DateTimePicker control has a Value property that should be used to retrieve the edited value instead of Text. The IC1EmbeddedEditor interface is fairly simple. If this property returns null. in some cases that is easier than writing a control. You can control the editing process further by handling the editing events fired by the grid. however.None. or other type of control). a ComboBox. 3. NumericUpDown editor = new NumericUpDown(). you can implement one or more methods in the IC1EmbeddedEditor interface to override the default behavior. you can use any UITypeEditors with the C1FlexGrid. see the CustomEditors sample on ComponentOne HelpCentral. Using the UITypeEditor wrapper class.NET provides several UITypeEditors for editing colors. The interface does provide enough flexibility to allow virtually any control to be used as a grid editor. In the process of editing a cell. You can also write your own UITypeEditors. // Assign the custom editor to the grid. This is possible because the grid knows enough about the base class to access properties such as Text and Bounds.Editor = editor. Edit Mode You can determine whether the grid is in edit mode by reading the value of the Editor property. C# private void Form1_Load(object sender. and because the grid binds to it using late binding. and so on. the grid is in edit mode and the property returns a reference to the control that is being used to edit the cell (the control may be a TextBox. 2. Implements the IC1EmbeddedEditor interface. You can even use UITypeEditor classes as grid editors. Sample Project Available For an example of using built-in. Set the grid's AllowMerging property to a value other than None. You can also attach your own event handlers to the editor. Merging Cells The C1FlexGrid control allows you to merge cells. For example. This capability can be used to enhance the appearance and clarity of the data displayed on the grid. Cell merging has several possible uses. You can examine the original value by retrieving it from the grid (the event provides the coordinates of the cell). merged data views. set the AllowMerging property to True for each row that you would like to merge Merging will occur if adjacent cells contain the same non-empty string. Editor. you must do two things: 1. The merging is done automatically based on the cell contents. but before it is displayed. If the new value is not valid for the cell. subtotals or sorting). where values in adjacent rows present repeated data.BeforeEdit This event fires whenever an editable cell is selected. You can change the editor properties at this point (for example. 68 . set the Cancel parameter to True and the grid will remain in edit mode. If instead of keeping the cell in edit mode you would rather restore the original value and leave edit mode. The effect of these settings is similar to the HTML <ROWSPAN> and <COLSPAN> tags. except the user has actually typed a key or clicked the dropdown button in the cell and really is about to start editing. To enable cell merging. (The effect of each setting is explained in the reference section. you can use it to create merged table headers.Text). making them span multiple rows or columns. If you want to merge rows. 2. set Cancel to True and then call the FinishEditing method. You can use this event to update anything that depends on the cell value (for example. Note that the user might not actually start editing after this. You can still cancel the editing at this point.) If you want to merge columns. before the editor value gets copied back into the grid. You can examine the new value about to be assigned to the grid through the Editor properties (for example. SetupEditor This event fires after the editor control has been created and configured to edit the cell. StartEdit This event is similar to BeforeEdit. It allows you to prevent the cell from being edited by setting the event's Cancel parameter to True. This makes it easy to provide merged views of sorted data. ValidateEdit AfterEdit This event fires after the new value has been applied to the cell and the editor has been deactivated. There is no method to force a pair of cells to merge. You can also modify the ComboList property so the appropriate drop-down button gets painted in the cell. because the control hasn't yet determined the type of editor that should be used. This event fires when the user is done editing. or grids where the text spills into adjacent columns. You can assign custom editors to the Editor property at this point. Note that the Editor property is still null at this point. set the AllowMerging property to True for each column that you would like to merge. set the maximum length or password character to be used in a TextBox editor). he could simply move the selection to a different cell or control. EventArgs) Handles MyBase.AllowMerging = True ' Merge the four cells with same contents.Cols.FixedOnly ' Create row headers. 4) rng. _flex. _flex.AutoSizeCols(1.Styles. rng = _flex.Load Dim i% ' Initialize the control. 1. 8) rng. 0.Rows. _flex.AllowMergingEnum.AllowMerging = C1. // Initialize the control.Data = "Sales by Product" ' Align and autosize the cells.GetCellRange(0.Cols(0). System. 69 . Dim rng As C1.CenterCenter _flex.Styles.Count = 9.Win.Cols. The code below shows an example:  Visual Basic Private Sub Form1_Load(ByVal sender As System. i) = "Qtr " & i _flex(1. assign the text to the header cells so that the cells you want to merge have the same contents. _flex.Count = 9 _flex.FixedOnly.C1FlexGrid. 0) rng.Win.GetCellRange(0.WordWrap = True _flex.TextAlignEnum. Finally.Normal.C1FlexGrid.Merged Table Headers To create merged table headers. 10) End Sub  C# private void Form1_Load(System.Data = "South" For i = 1 To 4 _flex(1. _flex.Count .Fixed = 2 _flex.1.object sender.Fixed.Normal. Then. you must start by setting the grid's AllowMerging property to FixedOnly.Fixed = 2. _flex.EventArgs e) { int i. rng = _flex.WordWrap = true.Win.GetCellRange(0.Rows(0).Styles.C1FlexGrid. designate the rows and columns that you want to merge by setting the row and column's AllowMerging properties.TextAlign = C1.Rows. 1. 5.AllowMergingEnum.C1FlexGrid.AllowMerging = True ' Merge the two cells with same contents.Object. _flex. 0. ByVal e As System.AllowMerging = C1.CellRange = _flex.Data = "North" ' Merge the four cells with same contents. 0. _flex. _flex.Cols.Win. i + 4) = "Qtr " & i Next ' Create the column header. 1 _flex. // Merge the two cells with same contents. rng.GetCellRange(0.Count .  Visual Basic Private Sub Form1_Load(ByVal sender As System.Fixed To _flex.AllowMerging = True Next End Sub  C# private void Form1_Load( System.AllowMerging = true.Cols. // Merge the four cells with same contents.Win.Data = "Sales by Product". 1. 0. System.Cols(i).AllowMerging = true.Styles. 0. The code below shows an example for a grid bound to a data source at design time. _flex[1.Cols. see Binding to a Data Source (page 101).Object.Rows[0].TextAlignEnum.// Create row headers. _flex.EventArgs e) 70 .Data = "North".EventArgs) Handles MyBase. } // Create the column header.1.RestrictCols For i = _flex. i <= 4. i] = "Qtr " + i. 0). rng = _flex.C1FlexGrid.AutoSizeCols(1. _flex. 0. for ( i = 1 .C1FlexGrid. // Merge the four cells with same contents.CellRange rng = _flex.GetCellRange(0.Data = "South".CenterCenter. _flex. } This is the result: Merged Data Views Cell merging works the same way when the grid is bound to a data source. // Align and autosize the cells. 5.Win. 10). 1. 8). _flex. rng = _flex.GetCellRange(0. rng.AllowMerging = C1.Count .C1FlexGrid.TextAlign = C1. _flex.AllowMergingEnum. 4). i++) { _flex[1. For more information on binding to a data source.Cols[0].object sender.Fixed. i + 4] = "Qtr " + i. C1. rng. _flex.Win.Load Dim i% ' Set up cell merging. ByVal e As System.Cols. i <= _flex.Cols.{ int i. For example.Fixed. Sample Project Available For an example of displaying merged data views with C1FlexGrid. The resulting behavior is similar to the one in Microsoft Excel. the entry will spill to occupy as much room as needed.Cols. for (int i = _flex.AllowMergingEnum. see the CellMerging sample on ComponentOne HelpCentral.AllowMerging = C1. // Set up cell merging. Spilling Text The AllowMerging property has two settings that operate differently from the others that do not require you to set the AllowMerging property on specific rows and columns.Cols(i). i++) { _flex.Win. Spill Setting The Spill setting causes text that is too long to fit in a cell to spill into empty adjacent cells.1. } } This is the result: Notice how merging the cells has the effect of visually grouping the data and making the information on the table easier to understand. If you type a long entry into a cell and the adjacent cell is empty.AllowMerging = true.C1FlexGrid.RestrictCols. the picture below shows what a grid might look like when AllowMerging is set to Spill and the user types entries of varying lengths: 71 . _flex.Count . and then AllowMerging is set to Nodes: This image is similar to the one in the Creating Subtotals (page 73) topic. By default. String comparisons are case-sensitive and blanks are included. the picture below shows what a grid might look like when the data is grouped and summarized using the C1FlexGridBase. the grid will merge adjacent cells that contain the same non-null value. Sample Project Available 72 . This setting is useful when data is organized into groups. For example.  Write a new class that derives from the C1FlexGrid and override the GetMergedRange virtual method.Nodes Setting The Nodes setting is similar to Spill but only applies to outline nodes.Subtotal method. The difference is that the subtotal rows (nodes) now spill onto empty adjacent cells. providing your own custom merging logic. Custom Merging You can customize the default merging behavior in two ways:  Assign a custom IComparer class to the CustomComparer property. improving the appearance of the grid. you could write a custom class that implements IComparer and assign it to the CustomComparer property. and the node rows contain information in a format different from the data rows. If you wanted the grid to merge cells using a case-insensitive comparison and trimming blanks. AutoSizeCols() End Sub  C# private void ShowTotals() { // Show OutlineBar on column 0. _flex. _flex. Region.Sum. see the CustomMerge.Subtotal(AggregateEnum.Subtotal(AggregateEnum.Subtotal(AggregateEnum. _flex. _flex. 1.Sum.Tree. "Total {0}"). 0.Subtotal(AggregateEnum. _flex. "Grand Total"). "Total {0}") ' Size column widths based on content.Subtotal method adds subtotal rows that contain aggregate data for the regular (non-subtotal) rows. 3. -1. To display hierarchical views of the data. CustomMerge2.Style = TreeStyleFlags.Tree.Clear) ' Get a Grand total (use -1 instead of column index). The code below illustrates this:  Visual Basic Private Sub ShowTotals() ' Show OutlineBar on column 0.Subtotal(AggregateEnum. Creating Subtotals The C1FlexGrid. Outlining and Summarizing Data The C1FlexGrid control has methods and properties that allow you to summarize data and display it in a hierarchical manner.Subtotal method.Sum.Clear). use the Tree property.Style = TreeStyleFlags. _flex. "Grand Total") ' Total per Product (column 0). -1. and Salesperson.Simple. -1. _flex. CustomMerge3. _flex.Sum. 3. 0. 1. use the C1FlexGrid.Subtotal(AggregateEnum. _flex. you may Subtotal to get aggregate sales figures by Product. 3. Subtotal supports hierarchical aggregates. 0. // Get a Grand total (use -1 instead of column index).Tree. _flex. 3. 73 . 0. -1. "Total {0}") ' Total per Region (column 1). if your grid contains sales data.Subtotal(AggregateEnum. // Clear existing subtotals. // Total per Region (column 1).For samples that show how to implement custom merging logic.Column = 0 _flex.Tree. // Total per Product (column 0).Column = 0. _flex. 3.Simple ' Clear existing subtotals.Sum. To summarize data and add aggregate values. For example. and CustomMerge4 samples on ComponentOne HelpCentral. Font = new Font(Font._flex.BackColor = Color.DarkRed cs.GrandTotal) cs.Font = New Font(Font. Dim cs As C1.Font = New Font(Font.C1FlexGrid. 1. After executing this code.CellStyle cs = _flex. cs. 1. cs = _flex.Subtotal0) cs. cs.Black cs.Subtotal1].Styles(C1. FontStyle. _flex.Win. 3.DarkBlue cs.C1FlexGrid.Styles(C1.GrandTotal]. FontStyle.ForeColor = Color.Bold) cs = _flex.Styles(C1.ForeColor = Color.White.C1FlexGrid.White. } When the C1FlexGrid. You can customize the appearance of the subtotal rows by changing the properties of the outline styles in the designer with the Style Editor or with code.Styles[CellStyleEnum.ForeColor = Color.Styles[CellStyleEnum.CellStyleEnum.Subtotal method adds rows with the aggregate information.Bold). cs.BackColor = Color.White  C# // Set styles for subtotals.Styles[CellStyleEnum.Font = new Font(Font. "Total {0}"). cs = _flex. the grid would look like this: 74 . CellStyle cs. FontStyle.White cs.ForeColor = Color.Black. cs.DarkBlue. // Size column widths based on content. For example:  Visual Basic ' Set styles for subtotals. cs.White.Bold).Win.BackColor = Color.ForeColor = Color.Win.Bold) cs = _flex.Sum.BackColor = Color.CellStyleEnum. cs. it automatically assigns subtotal styles to the new rows (there are built-in styles for 5 levels of subtotals).Subtotal(AggregateEnum.ForeColor = Color. cs.White cs.CellStyleEnum.Win.BackColor = Color.Subtotal0].DarkRed. FontStyle.BackColor = Color.AutoSizeCols(). cs = _flex.C1FlexGrid. cs.Subtotal1) cs. The other subtotals show total sales by product and region. To see the outline tree. The outline tree allows users to collapse and expand sections of the grid by clicking on the nodes. Visual Basic For example. This is useful to provide dynamic views of the data. It was created using a – 1 for the groupOn parameter in the call to the C1FlexGrid. subtotal rows will be skipped in the grid. You can get a Node object for any subtotal row through the Node property. averages or percentages). the subtotal rows do not correspond to actual data. Subtotal rows can be used as nodes in an outline. When the grid is bound to a data source. you need to set the Column and Tree.The Grand Total row contains the total sales for all products. where the user may move columns and resort the data. You can use outline trees to display many types of information. 4. making it necessary to recalculate the subtotals. the code below creates a directory tree:  75 . 2. Get the Node object for each node row and set its Level property to define the node's position in the tree hierarchy. you need to follow these steps: 1.Style properties to define the position and appearance of the outline tree. Subtotal rows can be treated as nodes in a tree. Subtotal rows created by the Subtotal method differ from regular rows in three aspects: 1. not only aggregates. regions. Creating Custom Trees To create outline trees without using the Subtotal method. and sales personnel. Turn some rows into outline nodes by setting their IsNode property to True. allowing you to collapse and expand groups of rows to present an overview of the data or to reveal its details. gross and net sales). Higher values mean the node is deeper (more indented) into the outline tree. If you move the cursor in the data source. 3. They were created using a values 0 and 1 for the groupOn parameter. 2. Add rows to the grid. Subtotal rows can be automatically removed by invoking the Subtotal method with the flexSTClear parameter. 3. and calculate several aggregates for each row (for example. The next topic shows how you can create a custom outline tree to display directory information.Subtotal method. You may also calculate aggregates other than sums (for example. // Initialize outline tree.Tree.Style = BorderStyleEnum.C1FlexGrid Private Sub Form1_Load(ByVal sender As System. AddDirectory(@"c:\\".Generic.Fixed = 0.Forms.Collections.Count = 1 _flex.Styles.Column = 0. _flex. _flex. private void Form1_Load(object sender.Data.Styles.Normal.Rows.Win. _flex. // Populate the grid.ExtendLastCol = true.Cols.DarkBlue ' Populate the grid.Count = 1 _flex. ByVal e As System.Normal.IO Imports C1. using System. AddDirectory("c:\".Cols.Windows.Cols.Tree. _flex.Tree.Column = 0 _flex. using System. _flex.Load ' Initialize grid layout.ExtendLastCol = True _flex. using C1.TextAlign = TextAlignEnum. _flex. _flex.Count = 1.Tree. _flex.IO.Border.Text.Normal. } The code above initializes the grid layout and calls the AddDirectory routine that does the job of populating the grid and setting up the tree structure: 76 .Style = TreeStyleFlags.Normal.Styles.Drawing. _flex.Tree. _flex.C1FlexGrid.EventArgs) Handles MyBase.None. using System.LeftCenter _flex.Style = TreeStyleFlags. using System. 0).ComponentModel.Border. using System.Cols.Styles.' add these Imports statements at the top of the form Imports System. EventArgs e) { // Initialize grid layout.LeftCenter.Object.LineColor = Color.DarkBlue.Style = BorderStyleEnum. _flex.Rows. 0) End Sub  C# // add these using statements at the top of the form using System. using System.SimpleLeaf _flex.LineColor = Color.SimpleLeaf.Tree.Count = 1.None ' Show outline tree. using System.TextAlign = TextAlignEnum.Win.Fixed = 0 _flex. //set node level Node nd = row. } _flex.AddItem(thisDir).IsNode = True r.Rows.Level = level. nd.Rows[_flex. // add files in this directory 77 . if (thisDir.ToLower()) r = _flex.Level = level ' Add files in this directory.Length == 0) { thisDir = dir. Dim file As String.GetFileName(dir).AddItem(Path.1].1) row.Rows(_flex. cnt As Integer.IsNode = true.Count .IsNode = True ' Set the node level.Count – 1) r. Dim nd As Node nd = row.Rows.AddItem(thisDir) ' Make this new row a node.Rows(_flex. level + 1) cnt = cnt + 1 If cnt > 10 Then Exit For Next End If End Sub  C# private void AddDirectory(string dir. Dim thisDir As String thisDir = Path.GetDirectories(dir) AddDirectory(subdir. Dim row As Row row = _flex. row.Node. //make this new row a node Row row = _flex. int level) { // add this directory string thisDir = Path.Rows.GetFileName(file). r As Row cnt = 0 For Each file In Directory. ByVal level As Integer) ' Add this directory. Visual Basic Private Sub AddDirectory(ByVal dir As String. If level <= 4 Then Dim subdir As String cnt = 0 For Each subdir In Directory.Length = 0 Then thisDir = dir _flex.Level = level + 1 cnt = cnt + 1 If cnt > 10 Then Exit For Next ' Add subdirectories (up to level 4).GetFileName(dir) If thisDir.GetFiles(dir) _flex.Node.Node nd.Count . //mark the row without child row as node r = _flex. if (cnt > 10) break. In a real application. } } } AddDirectory is a recursive routine that traverses the current directory and all its subdirectories.Count . foreach (string file in Directory. the tree size is limited to four directory levels in order to save time.Node.1].GetFiles(dir)) { _flex.GetFileName(file).Level = level + 1.ToLower()).Rows. foreach (string subdir in Directory. the routine should be changed to populate tree branches only when they are expanded (see the FlexGrid for WinForms Tutorials (page 113)). cnt = cnt + 1. r. r. In this example.GetDirectories(dir)) { AddDirectory(subdir.IsNode = true. This code creates a grid that looks like this: 78 . if (cnt > 10) break.AddItem(Path. level + 1).Rows[_flex.int cnt = 0. cnt = cnt + 1. } // add subdirectories (up to level 4) if (level <= 4) { cnt = 0. Row r. they act as headers under which similar data is grouped. hiding or showing the data they contain. Instead.Creating Outlines and Trees with the C1FlexGrid Control One of the unique and popular features of the C1FlexGrid control is the ability to add hierarchical grouping to regular unstructured data. but it adds a tree where each node contains a summary of the data below it. Nodes can be collapsed to show only the summary. exactly like nodes in a regular TreeView control. For example. but it's hard to see the total sales for each country or customer. 79 . Also like nodes in a TreeView control. country. city. node rows have a Level property that defines the node hierarchy. then by city within each country (level 1). In this article. node rows can be collapsed and expanded. Node rows do not contain regular data. Lower level nodes contain higher level nodes. then by customer within each city (level 2). we will walk you through the process of turning a regular grid into a richer outline grid. Here is the same grid with after adding the outline: This grid shows the same information as the previous one (it is bound to the same data source). and sales amounts. Note that each node row can show summaries for more than one column (in this case. or expanded to show the detail. This typical grid would normally look like this: All the information is there. Like nodes in a TreeView control. You could use the C1FlexGrid's outlining features to group the data by country (level 0). suppose you had a grid showing customer name. the C1FlexGrid introduces the concept of Node rows. total units sold and total amount). To achieve this. _flex. they exist to group regular rows that contain similar data. // format ExtendedPrice column _flex.Cols["ExtendedPrice"].Rows[rowIndex]. Node rows do not. you can use the IsNode property: var row = _flex.Format = "n2". } else { // this row is not a node 80 . you can set the grid's DataSource property in code. If your data source is available at design time. After running this code. fields).IsNode) { // row is a node var node = row.Fill(_dt). you can use the Visual Studio Property Window to set the grid's DataSource property and bind the grid to the data without writing any code. you would get the "regular grid" shown in the first image. Instead. // bind grid to data this. If the outline tree is not visible. users can collapse and expand nodes using the mouse or the keyboard. each regular row corresponds to an item in the data source. var sql = string.Loading the Data Loading data into an outline grid is exactly the same as loading it into a regular grid. ExtendedPrice". da. Quantity. Creating Node Rows Node rows are almost identical to regular rows. If the data source is not available at design time. we need to insert the node rows that make up the outline. When the grid is bound to a data source. all its data and child nodes are hidden. if (row. // get data var fields = @" Country. Node rows can be collapsed or expanded. } The code uses an OleDbDataAdapter to fill a DataTable with data. DoSomethingWithTheNode(node). thenand then assigns the DataTable to the grid's DataSource property. The data binding code typically looks like this: public Form1() { InitializeComponent(). SalesPerson. except for the following:  Node rows are not data bound.DataSource = _dt. then nodes can only be expanded or collapsed using code.Format("SELECT {0} FROM Invoices ORDER BY {0}". To turn this regular grid into the outline grid shown in the second image. var da = new OleDbDataAdapter(sql. GetConnectionString()). When a node row is collapsed. If the outline tree is visible.Node.  To determine whether a row is a node or not. City. which would cause the grid to flicker.). It gives the most control and flexibility and is demonstrated below. 0).Rows[r]. 4. columnName]. the method assumes that the data is sorted according to the outline structure.Cols.Fixed. This method scans the entire grid and automatically inserts node rows with optional subtotals at locations where the grid data changes. It requires very little code. a node row is inserted showing the new group name in the first scrollable column. skipping existing node rows (so it can be called to add several levels of nodes). current)) { // value changed: insert node _flex.Subtotal method. // group on a given column inserting nodes of a given level void GroupBy(string columnName. 81 . } Very simple. the GroupBy method may insert may rows.Rows. First. and keeps track of the current value for the column being grouped on. you could use this method to create a two-level outline by calling: void _btnGroupCountryCity_Click(object sender. you can use it like you would any other row (set the data for each column.Count.Equals(value. but makes some assumptions about how the data is structured on the grid and what the outline should look like. Also. r < _flex. Back to our example. To avoid this. if (!object. // update current value current = value. Use the C1FlexGrid. Once the node row has been created. 5.InsertNode(r.InsertNode method. 1). int level) { object current = null. then you can turn regular rows into node rows by setting the IsNode property to true. if the data were sorted by SalesPerson instead of by Country. which probably is not what you want. EventArgs e) { GroupBy("Country". The code below shows how you could implement a GroupBy method that inserts node rows grouping identical values on a given column. // show group name in first scrollable column _flex[r. but there are some caveats. Note that this only works when the grid is unbound. apply styles.Rows. This will insert a new node row at a specified index. GroupBy("City". level). When the current value changes. the outline would have several level-0 nodes for each country. you would normally set the Redraw property to false before making the updates and set it back to true when done. This is the 'high-level' way of inserting totals and building outlines. Use the Rows.IsNode) { var value = _flex[r. etc. _flex. for (int r = _flex. r++) { if (!_flex. In this example. Trying to turn a regular data bound row into a node will cause the grid to throw an exception.Fixed] = value. This is the 'low-level' way of inserting totals and building outlines. } } } } The code scans all the columns.} Node rows can be created in three ways: 3. If the grid is unbound.Rows. /// This avoids flicker and ensures the Redraw property is reset properly in case /// an exception is thrown during the operation. etc.Redraw = _redraw. The code looks like this: // unbind and re-bind grid in order to reset everything void ResetBinding() { // unbind grid _flex. class DeferRefresh : IDisposable { C1FlexGrid _grid. } public void Dispose() { _grid.DataSource = null. grid. // reset any custom sorting _dt. Here is the implementation of the DeferRefresh class: /// Utility class used to encapsulate grid lengthy operations in a Redraw block.To handle these issues. the code that creates the outline should be re-written as follows: void _btnGroupCountryCity_Click(object sender. } } The DeferRefresh class is a simple utility that sets the grid's Redraw property to false and restores its original value when it is disposed. } } The BindGrid method ensures that the grid is sorted in the order required by our outline structure. // format ExtendedPrice column _flex. In our example. 1). // re-bind grid _flex. City GroupBy("Country". // group by Country.Format = "n2". GroupBy("City".Redraw = false.) ResetBinding().Cols["ExtendedPrice"].Redraw.Empty. City. 0).DefaultView.DataSource = _dt. // auto-size the columns to fit their content 82 . public DeferRefresh(C1FlexGrid grid) { _grid = grid. EventArgs e) { // suspend redrawing while updating using (new DeferRefresh(_flex)) { // restore original sort (by Country. This ensures that Redraw is properly restored even when exceptions happen during the updates. bool _redraw. and SalesPerson. _redraw = grid.Sort = string. City. the sort order is by Country. LineColor: Gets or sets the color of the tree's connecting lines. you would use this code: void _btnTreeCountryCity_Click(object sender. It shows an indented structure with collapse/expand icons next to each node row so the user can expand and collapse the outline to see the desired level of detail. thenand then sets the Tree.Column = 0.Tree.Tree.Column property. Indent: Gets or sets the indent. To show the outline tree in the example given above. // autosize to accommodate tree _flex. // collapse detail nodes _flex.AutoSizeCol(_flex.   For example.CompleteLeaf. _flex. LineStyle: Gets or sets the style of the tree's connecting lines. by changing the code above to include these two lines: // show outline tree _flex. EventArgs e) { using (new DeferRefresh(_flex)) { // group by country and city as before _btnGroupCountryCity_Click(this.AutoSizeCols(). It also calls the C1FlexGrid.AutoSizeCol method to ensure that the column is wide enough to accommodate the outline tree. The outline tree can be displayed in any column.LineColor = Color. } } The code calls the previous method to build the outline. } If you run this code now.Empty).Column property to zero in order to show the outline tree in the first column. Higher indent levels cause the tree to become wider. so you can't expand and collapse the nodes.Tree. The outline tree is described in the next section. it calls the Tree. The main ones are listed below:    Column: Gets or sets the index of the column that contains the outline tree.Column).Tree. you will notice that the node rows are created as expected.Column = 0.Tree. EventArgs. Style: Gets or sets the type of outline tree to display. defined by the Tree. Finally. which causes the tree not to be displayed at all. Setting this property to -1 causes the outline tree to be hidden from the users. this property is set to -1.White. Outline Tree The outline tree is very similar to the one you see in a regular TreeView control.Show(1). Use this property to determine whether the tree should include a button bar at the top to allow users to collapse/expand the entire tree. The Tree property returns a reference to a GridTree object that exposes several methods and properties used to customize the outline tree._flex.Show method to display all level-0 nodes (cities in this case) and hide all the detail. // show outline tree _flex. in pixels. and whether lines should be displayed connecting the tree to data rows as well as node rows. between adjacent node levels. 83 .Style = TreeStyleFlags. _flex. but the outline tree is not visible. By default.Tree. whether lines and/or symbols should be displayed. IndexOf(colName).Rows[r]. Clicking these buttons would cause the entire tree to collapse or expand to the corresponding level. "2".Sum. If you created the outline tree using the Rows. r < _flex.Level == level) { // found a node.Subtotal method listed below shows how to do this: // add subtotals to each node at a given level void AddSubtotals(int level.Aggregate method to calculate the subtotals for each group of rows and insert the result directly into the node rows. range. string colName) { // get column we are going to total on int colIndex = _flex. then you should use the C1FlexGrid. then the subtotals are added automatically.r2. This will be described in a later section.r1.Count.Tree.GetCellRange(). colIndex. r++) { if (_flex. colIndex.Rows. var sum = _flex.Rows. To make the outlines really useful.ExcludeNodes). calculate the sum of extended price var range = node. If you create an outline tree using the C1FlexGrid.Cols.Aggregate(AggregateEnum.Node. Also notice the much wider indentation and the lines connecting the tree to regular rows ("Anne Dodsworth") as well as to node rows. the node rows should include summary information for the data they contain. // scan rows looking for nodes at the right level for (int r = _flex.Indent = 30. The C1FlexGrid. range.Rows[r]. AggregateFlags. if (node. // show the sum on the grid 84 . Adding Subtotals So far we have covered the creation of node rows and outline trees._flex.Subtotal method.InsertNode method as described above.IsNode) { var node = _flex. however.Fixed. The outline tree would change as follows: Notice the buttons labeled "1". and "*" on the top left cell. colIndex] = sum. and subtotals: void _btnTreeCountryCity_Click(object sender. we will add totals for the Quantity and ExtendedPrice columns.Column = 0.Show(1).Column). SalesPerson) ResetBinding(). Then it uses the C1FlexGrid. etc. If you expand any of the node rows. Note that this does not affect the data source in any way. City GroupBy("Country". (level 1) AddSubtotals(1.AutoSizeCol(_flex. "Quantity"). } } If you run the project now. // group by country (level 0) GroupBy("City". _flex. (level 0) AddSubtotals(1.Tree. you could add other aggregates such as average.Tree. minimum. } } } } The AddSubtotals method scans the grid rows looking for node rows. you will see a lot of duplicate values.// (will use the column format automatically) _flex[r. it is assigned to the node row's cell with the usual _flex[row. since node rows are not bound to the data. In this example. Once the subtotal has been calculated. 1). "ExtendedPrice"). the method uses the GetCellRange method to retrieve the node's child rows. City AddSubtotals(0. Note also that the method can be used to add multiple totals to each node row. All rows under a given city node have the same country and city: 85 . This is very nice. _flex. 0).Aggregate method to calculate the sum of the values on the target column over the entire range. outline tree. City. col] indexer. // group by Country. country (level 0) AddSubtotals(0. maximum. you will see a tree with node rows that show the total quantity and amount sold for each country and city. with node rows. but there is a little problem. // group by city (level 1) // add totals per Country. "Quantity").Tree. When a node row of the desired level is found. The call to Aggregate includes the ExcludeNodes flag to avoid double-counting existing nodes. In addition to sums. We can now use this method to create a complete outline. "ExtendedPrice"). EventArgs e) { using (new DeferRefresh(_flex)) { // restore original sort (by Country. 1) // extended price per // quantity per country // extended price per city // quantity per city (level // show outline tree _flex. you should remember to set the grid's AllowMerging property to Nodes. // extended price per country (level 0) AddTotals(0. all you have to do is set the Width of the columns that are being grouped on to zero.Width = 0. however. When you do that. that would also hide the node text) _flex. so the text assigned to the node rows will spill into the visible columns. // allow node content to spill onto next cell _flex. but merging is usually a better solution because it allows you to use longer text for the node rows). but it is also a waste of screen real estate. EventArgs e) { using (new DeferRefresh(_flex)) { // restore original sort (by Country.This is correct. City. City GroupBy("Country". (Another option would be to assign the node text to the first visible column. Here is the revised code and the final result: void _btnTreeCountryCity_Click(object sender. "Quantity"). // quantity per country (level 0) 86 . // group by city (level 1) // hide columns that we grouped on // (they only have duplicate values which already appear on the tree nodes) // (but don't make them invisible.Nodes. // add totals per Country. Eliminating these duplicate values is easy.Cols["Country"]. // group by Country. City AddTotals(0.Cols["City"]. "ExtendedPrice"). 0).Width = 0. // group by country (level 0) GroupBy("City". SalesPerson) ResetBinding(). _flex. 1).AllowMerging = AllowMergingEnum. Tree. _flex. city 0. only a little faster and without using any helper methods: void _btnTreeCountryCity_Click(object sender. 1.Sum. TheSubtotal method performs the same tasks as the GroupBy and AddSubtotals methods described above. "City". but their values still appear in the node rows.AutoSizeCol(_flex.Subtotal(AggregateEnum. _flex. "ExtendedPrice"). _flex.Show(1).Tree. 0.Subtotal(AggregateEnum. "Country". EventArgs e) { using (new DeferRefresh(_flex)) { // restore original sort (by Country. _flex. 1. The code below shows how you can use the Subtotal method to accomplish the same thing we did before.Sum. 87 . City. } } The Country and City columns are now invisible.Column). // extended price per city // quantity per city (level 1) // show outline tree _flex. "Quantity"). "ExtendedPrice").Tree. SalesPerson) ResetBinding(). (level 1) AddTotals(1. "Quantity"). "ExtendedPrice").Sum. Collapsing the tree shows totals for each country and city. "Quantity"). Using the Subtotal Method We mentioned earlier that you could also create trees using the C1FlexGrid's C1FlexGrid.Sum.Subtotal method.Subtotal(AggregateEnum. // group and total by country and _flex.Subtotal(AggregateEnum. "City". except it does both things in a single step and is therefore a little more efficient.AddTotals(1.Column = 0. "Country". _flex. // hide columns that we grouped on // (they only have duplicate values which already appear on the tree nodes) // (but don't make them invisible. 88 .Column = 0. then the Subtotal method assumes the rows should be in different groups and inserts a new node row even though the value of the groupBy column is the same. "Brazil". int groupBy. For example. The latter is the one we used in the example above. the Subtotal method inserts a node row whenever the value of the groupBy or any previous column changes. int totalOn. It is useful only for removing existing subtotals before inserting new ones. and so on. so if you are grouping by country.Clear. and so on. If you set the caption parameter to a string such as "Country: {0}". Subtotal(AggregateEnum aggType. how to perform the grouping. string caption) Subtotal(AggregateEnum aggType. if you a row has the same value in the "City" column as the previous row.AllowMerging = AllowMergingEnum. string totalOn. _flex. string groupBy. int groupFrom.Show(1). 2.Cols["City"]. The caption parameter determines the text that is added to the new node rows to identify the value being grouped on.Tree. int totalOn. but a different value in the "Country" column. Outline Maintenance So far we have discussed how to create outlines with trees and totals using the high-level C1FlexGrid. string totalOn.Tree. the node rows would show "Argentina". int groupBy. Subtotal(AggregateEnum aggType. string caption) These overloads add an extra caption parameter.Width = 0. the value being grouped on is shown. Subtotal(AggregateEnum aggType) This version of the method takes only one aggregate type as a parameter. The summary below describes the overloads available: 1. string caption) Subtotal(AggregateEnum aggType. 3. By default. string totalOn) These are the most commonly used overloads. int totalOn) Subtotal(AggregateEnum aggType. } } The Subtotal method is very convenient and flexible. that would also hide the node text) _flex. Subtotal(AggregateEnum aggType. In this case. the aggType parameter is set to AggregateEnum. 4. then the node rows would show "Country: Argentina" instead. // show outline tree _flex. string caption) These overloads separate the groupBy parameter into two: groupFrom and groupTo.Nodes. _flex. string groupTo. int groupTo.InsertNode and Aggregate methods. The columns may be referenced by index or by name. string groupBy. whether to include a caption in the node rows that it inserts.Column).Cols["Country"]. string groupFrom. The parameters are the type of aggregate to insert and the columns to group by and total on.AutoSizeCol(_flex.Subtotal method as well as lower-level Rows. It has a number of overloads that allow you to specify which columns should be grouped on and totaled on by index or by name. _flex. These aggregates let you override that behavior and specify the range of columns that should be considered when identifying a group.Tree. By default.Width = 0. _flex. once you have a Node object you can manipulate it using the following properties and methods:          Level: Gets or sets the node level in the outline tree.IsNode ? _flex. GetNode: Gets the node that has a given relationship to this node (parent.Node : null. Collapsed/Expanded: Gets or sets the node's collapsed/expanded state. the subtotals will not be automatically updated. Or you can retrieve the node for an existing row using the row's Node property: var node = _flex. Checked: Gets or sets the check state of the cell defined by Node. Either way. Update the outline when there are changes to the data or to the grid. To obtain a Node object. This is the easiest option. Children: Gets the number of child nodes under this node.Column. AllowDragging. Using the Node class The Node class provides a number of methods and properties that can be used to create and manage outline trees. so they should be familiar to most developers. Nodes: Gets a node array containing this node's child nodes. When the column order changes. Data: Gets or sets the value in the cell defined by Node. The sample creates an initial outline and allows users to reorder the columns. There are two common ways to maintain the outlines: 1. Things are actually somewhat simpler in this case. but is not bound to it in any way. You can also explore the outline structure using the following methods: The discussion above focused on bound scenarios.Rows. next sibling. Many of these methods and properties are based on the standard TreeView object model. 2. You would attach handlers to the grid's AfterDataRefresh. AfterSort. and AllowSorting properties to false and prevent any changes that would affect the outline.Row and the Tree. first child. and so on.Column. you can either: Use the return value of the Rows. GetCellRange(): Gets a CellRange object that described the range of rows that belong to this node. and AfterEdit events and re-generate the outline appropriately. Image: Gets or sets the image in the cell defined by Node. You would set the grid's AllowEditing.At this point. 89 . the sample automatically re-sorts the data and re-creates the outline. The user can easily create simple reports showing sales by country.InsertNode(index. This approach is illustrated by the Analyze sample provided with the C1FlexGrid.Row and the Tree. Option 2 is usually more interesting since it provides a quick and simple tool for dynamic data analysis. by salesperson. for example.Rows[index]. the data will be refreshed and the subtotals will disappear.Row and the Tree. it is important to remember that the outline tree is created based on the data. You can also create trees and outlines in unbound scenarios. and so on). where the grid is attached to a data source that provides the data.InsertNode method: var node = _flex. If the user sorts the grid. and is not automatically maintained when there are changes to the grid or to the data. If the user modifies a value in the "ExtendedPrice" column. since you can turn any row into a node row by setting its IsNode property to true. level). by product.Column. Prevent the user from making any changes that would invalidate the outline.Rows[index]. custom delimiters). commas. whether to save the fixed cells or only the scrollable cells. Saving and Loading Microsoft Excel Files Starting with version 2. but it will not load the underlying formulas. Microsoft Excel). the cell is enclosed in quotes. ASCII or Unicode). it owns all the data that is displayed.Excel and call the methods as usual.If the grid is unbound. The format of the text files is fairly simple.EventArgs) Handles _btnData. including row and column dimensions. The resulting text files can later be loaded back into the control. To save and load Excel files using the SaveGrid and LoadGrid methods. and the type of encoding to used (for example. fonts. This is the also the convention used in Microsoft Excel text files. This is different from data binding.xls) as well as text files. use the SaveExcel. For example. and cell alignment. If you want additional control over which sheets to load or save. Text files do not contain pictures or formatting information. The method has parameters that control the type of delimiter to use (for example. Cell contents are saved as formatted strings (exactly as they are displayed on the screen). load. Saving and Loading Grids to Text Files The SaveGrid method saves the grid contents to a text file. or into other applications that support comma or tab-delimited files (for example. you can use the SaveGrid and LoadGrid methods to save and load Microsoft Excel files (. data maps. and LoadExcelSheetNames methods instead. Using nodes in an unbound grid is very similar to using nodes in a regular TreeView control. Any quote characters contained in the cell text are doubled. you can use DataReader objects.Click ' Prepare DataReader. The LoadGrid method loads data from text files. simply set the format parameter to FileFormatEnum. you can move nodes around the tree using the Move method as shown by the TreeNode sample provided with the C1FlexGrid. LoadExcel. Excel files contain "workbooks". which are made up of "worksheets". If the cell text contains quote characters or cell separator characters. not all formatting elements can be converted. as shown below:  Visual Basic Private Sub _btnData_Click(ByVal sender As Object.5. and you do things that are not possible when a data source owns the data. Loading. colors. To load data from a database. Saving. tabs. The SaveGrid and LoadGrid methods always save books with a single sheet. the grid will load the values in Excel cells. formats. The process of saving and loading Excel files will convert most data types and formatting information. Other features such as frozen and merged cells. You can load text files created with the SaveGrid method or with other applications. For example. 90 . or selected). visible. You don't need to have Microsoft Excel installed on your computer. ByVal e As System. and cell borders are not translated either. and print grids. and load the first sheet from existing books. The SaveGrid method has a flags parameter that allows you to specify whether you want to save the entire grid or only certain parts (scrollable. which keeps a live connection between one or more controls and the underlying data source. Loading Grids from Databases You can also load grid data from a database. images. This allows you to save formatting information in addition to the data. However. and Printing The C1FlexGrid control has methods that allow you to save. SqlCommand("SELECT * FROM Employees".Data.Win. // Build the grid structure from the DB schema. 1) End While ' Cleanup.Open(). cols). System.Column = _flex. System.Rows.SqlConnection myConn = new System. DataTable dt = myReader.C1FlexGrid. _flex.Rows) { Column c = _flex.Name = (string)dr["ColumnName"].initial catalog=Northwind.Data.Data.Dim strConn As String = "data source=MYMACHINE. string strConn = "data source=MYMACHINE.Cols.ExecuteReader() ' Build the grid structure from the DB schema.Add() c. _flex.Data.SqlClient.Count = 1.SqlDataReader myReader = myCMD.SqlClient. myConn.SqlConnection(strConn).Data.ExecuteReader().Count = 1 Dim row As Integer = 1 Dim cols As Integer = dt.Cols. Dim dt As DataTable = myReader. c. } 91 . _flex.SqlClient. foreach (DataRow dr in dt.SqlCommand("SELECT * FROM Employees".AddItem(v.Add(). row + 1.Caption = c.Open() Dim myReader As SqlClient.CreateInstance(GetType(Object).EventArgs e) { // Prepare DataReader. c.SqlDataReader = myCMD." Dim myConn As New SqlClient.SqlClient.Caption =(c. System.Read() myReader.SqlConnection(strConn) Dim myCMD As New SqlClient. Object()) While myReader.DataType = CType(dr("DataType").Rows Dim c As C1.SqlClient. myConn).Cols.Cols.GetValues(v) _flex. Type) Next dr ' Populate the grid.SqlCommand myCMD = new System.GetSchemaTable().".Count = 1 Dim dr As DataRow For Each dr In dt. myConn) myConn.Close() End Sub  C# private void _btnData_Click(object sender.GetSchemaTable() _flex.Count Dim v As Object() = CType(Array.Close() myConn.AutoSizeCols() myReader.Columns.initial catalog=Northwind.DataType = (Type)dr["DataType"]. System.Name <= CStr(dr("ColumnName"))) c. 5" left margin).Bold) _flex. _flex.Win. } Printing Grids Use the PrintGrid method to print the contents of the grid.PrintDocument pd = _flex. 8. myReader. paper size and orientation.Drawing. myConn.Read()) { myReader.PrintParameters.Columns.PrintDocument pd = _flex. cols). header and footer fonts. int cols = dt. and a . The code below uses the PrintParameters property to set up the page orientation.Landscape = True .PrintParameters. The method has parameters that allow you to select the scaling mode.DefaultPageSettings. object[] v = (object[])Array. row++.Margins.Close().Count. _flex. whether to display print/preview dialog boxes. 1). and so on. pd. set headers and footers. Then it calls the PrintGrid method to display a print preview dialog window:  Visual Basic ' Get the grid's PrintDocument object.PrintDocument() ' Set up the page (landscape. 1. while (myReader.// Populate the grid.PrintGridFlags. "d").Italic) ' Preview the grid. _flex.PrintGridFlags.PrintParameters.Close(). The PrintParameters property exposes additional printing properties such as the font to use for headers and footers.PrintGrid("C1FlexGrid".FitToPageWidth + C1. FontStyle.HeaderFont = New Font("Arial Black".AddItem(v.Landscape = true. Dim pd As Printing.AutoSizeCols(). Chr(9) + Chr(9) + "Page {0} of {1}")  C# // Get the grid's PrintDocument object.Rows.Printing.Win. With pd.CreateInstance(typeof(object).Left = 150 End With ' Set up the header and footer fonts. _flex.PrintDocument. margins. margins. 14.Count = 1.5" left margin). _flex. System. // Set up the page (landscape. 1.PrintParameters. "C1FlexGrid" + Chr(9) + Chr(9) + Format(DateTime.Now. 92 . FontStyle.C1FlexGrid.NET Framework PrintDocument object that can be used to select the printer.ShowPreviewDialog. int row = 1.FooterFont = New Font("Arial Narrow".C1FlexGrid. and so on.GetValues(v). C1.DefaultPageSettings . } // Cleanup. (2) the filtering does not require extra real estate on the screen. This filter contains a list of values that should be displayed.  The code samples presented below were mostly taken from two new samples included with the product: ColumnFilters and CustomFilters. implementing them is relatively easy.PrintParameters. To enable simple filtering scenarios. _flex. FontStyle. 14.FooterFont = new Font("Arial Narrow". and (3) this type of filter allows for better filter editors and easier customization. This filter combines a ValueFilter and a ConditionFilter. users simply set the grid's AllowFiltering property to True. C1FlexGrid Filtering Data filtering in grids usually comes in two flavors:  Header-based: A filter icon appears over each column that has a filter applied to it. "d"). "C1FlexGrid\t\t" + Microsoft.DefaultPageSettings. the C1FlexGrid control follows the same pattern used to implement column moving and sizing. The main benefits of this type of filter are: (1) the user can see which columns are being filtered. ByCondition: The grid automatically creates a filter of type ConditionFilter.pd. The conditions may be combined with an AND or an OR operator. They can then disable or customize the filtering behavior for specific columns by changing the value of the column's AllowFiltering property.Strings. PrintGridFlags. The grid has a new AllowFiltering property that controls filtering at a control level. _flex. Any values not present on the list are hidden from the end user. The main benefit of this type of filter is that users can always see which columns are being filtered and what the current filter criteria are. Please refer to the samples for complete projects that show the features in action. "\t\tPage {0} of {1}"). This filter specifies two conditions such as "greater than" or "contains".Left = 150. _flex.HeaderFont = new Font("Arial Black".Italic). both described below. We provide a FilterRow sample that shows how to do it. The column's AllowFiltering property may be set to one of the following values:    Default: The grid automatically creates a filter of type ColumnFilter.Format(DateTime. // Set up the header and footer fonts. Filter Row: A filter row remains always visible and allows users to type values or expressions directly into the row. // Preview the grid. Custom: The grid does not create a filter automatically.Now.FitToPageWidth | PrintGridFlags. 8. Although filter rows are not built into the C1FlexGrid control. Users may see and edit the filters by clicking the filter icon. ByValue: The grid automatically creates a filter of type ValueFilter. and the grid's Column object also has an AllowFiltering property that controls filtering at the column level. This is the mechanism used by Windows 7/Vista and by the C1FlexGrid control. The developer is expected to instantiate a filter and explicitly assign it to the column's Filter property.PrintGrid("C1FlexGrid". AllowFiltering property To implement the header-based filters.PrintParameters.Margins. The main disadvantage is that the filter takes up some real estate and may interfere with the regular grid operation.ShowPreviewDialog. FontStyle.VisualBasic.Bold).   93 . None: The column cannot be filtered. The ValueFilter editor consists of a list of values with checkboxes. including "New York Hilton". 94 . or "Paris Hilton". However. the filter is de-activated and all values are displayed.By default. Value Filter The ValueFilter is conceptually very simple. typing "Hilton" will select the next value that contains "Hilton". For example. typing ctrl+Up or ctrl+Down will navigate to the next or previous checked item. The editor implements a flexible search buffer that allows users to locate values by typing any part of the value. it allows users to specify up to two conditions using operators such as "greater than". This image shows the ConditionFilter editor. and only the values listed are displayed on the grid. Values are displayed on the list using the Format currently assigned to the column. Instead of selecting specific values. Navigating long lists is easy with the advanced built-in keyboard navigation. or "contains". Condition Filter The ConditionFilter is more flexible. This image shows the ValueFilter editor. you can use the Language property to override the default and specify the language that should be used when the grid displays the column filter editor. This type of filter is recommended for filtering columns that contain discrete values such as names or enumerations. the C1FlexGrid control localizes the column filter editor to use the language specified by the CurrentUICulture setting. "starts with". Users may check or uncheck all values at once. If the list is set to null. It contains a list of values. This type of filter is recommended for filtering columns that contain "continuous" values such as numeric or date/time values. "Prince Edward Hilton". Also. to reset the filter. geographic. Custom Filters Custom filters may be created to handle specialized values. and Hebrew. The built-in filters support automatic localization in the following languages: English. and to return an editor to be used for viewing and editing the filter's parameters. Greek. or custom data types. German. Swedish. the developer must create two classes:  Filter: This class must implement the IC1ColumnFilter interface. French. Managing filters programmatically As we mentioned earlier in this document. Dutch. Polish. The localization is built-in and does not require satellite dlls. You can see this in the images. which specifies methods used to apply the filter to a specific value. For example. custom filters would be recommended to filter on colors. DateTime. Russian. Arabic. This can be achieved by modifying the AllowFiltering and Filter properties on individual columns. Finnish. setting the grid's AllowFiltering property to True is enough to enable column filtering on all columns. Norwegian. Spanish. In many cases however. the code below enables filtering but restricts the filtering to columns of type string: // bind and configure grid _flex. Japanese. To create a custom filter. which specifies methods used to initialize the editor and to apply changes to the filter. where the ProductName and Quantity column headers show the filter icon. Italian.  The CustomFilters sample contains implementations of three custom filters used for filtering values of type Color.Columns that have filters applied display the filter icon on their headers even when the mouse is not over them.DataSource = dtProducts. For example. Danish. Portuguese. Chinese. you may want finer control over filtering. Filter Editor: This class must inherit from Control and must implement the IC1ColumnFilterEditor interface. 95 . and string. AfterEdit += _flex_AfterEdit. To apply the filters to the data currently loaded on the grid. // restrict filtering to columns of type 'string' foreach (Column c in _flex.RowColEventArgs e) 96 .Default : AllowFiltering. and connects an event handler to the AfterEdit event. The event handler implementation follows: void _flex_AfterEdit(object sender. // enable filtering _flex. the code below enables an ApplyFilter button when the user edits the data on the grid. call the grid's ApplyFilters method.AllowFiltering = true. da.AllowFiltering = c.Cols["ProductName"]. Applying filters programmatically Filters are applied when the user edits them. var dtProducts = new DataTable(). } You can customize the filtering process further by creating filters and assigning them to columns.Format = "#. // bind the grid to the data _flex.AllowFiltering = true.Win.00".BeginsWith. // monitor changes to enable ApplyFilter button _flex.C1FlexGrid. configures it to select all items that start with the letter "C".Filter = filter.None.Condition1.Cols) { c. // configure filter to select items that start with "C" filter. They are not automatically applied when the data changes.Parameter = "C". or by retrieving existing filters and modifying their properties. Clicking the ApplyFilter button applies the filter and disables the button until the next change.DataSource = dtProducts. filter.Operator = ConditionOperator.Fill(dtProducts).DataType == typeof(string) ? AllowFiltering. C1. public Form1() { InitializeComponent().Cols["UnitPrice"]. enables filtering by setting the AllowFiltering property to True. and also when they are applied to a column. For example.Condition1. For example. // get some data var da = new OleDbDataAdapter("select * from products". the code below creates a ConditionFilter. and then assigns the new filter to the "ProductName" column: // create a new ConditionFilter var filter = new ConditionFilter(). // assign new filter to column "ProductName" _flexCustom. } The code above binds the grid to a data source. // enable filtering _flex. GetConnectionString()).###._flex. CancelEventArgs e) 97 .Win. _btnApplyFilters.C1FlexGrid. } Customizing filter behavior When filters are applied.ApplyFilters(). If instead of requiring a button click you simply wanted to apply the filter after every edit.BackColor = Color. the code attaches handlers for the BeforeFilter and AfterFilter events. _flex. cs.ForeColor = Color. But the grid also fires BeforeFilter and AfterFilter events that allow you to customize the filtering behavior. the grid hides rows by setting their Visible property to False. } } } This code scans all columns to determine whether a filter is defined for any column.Cols) { if (c. The event handlers are listed below: // suspend painting before filter is applied void _flex_BeforeFilter(object sender. the code enables the button that applies the filter to the current data.Add("filteredOut"). // configure grid _flex. C1. This can be accomplished easily using this code: public Form1() { InitializeComponent().Enabled = true. If an active filter is detected.Win. } The code creates a custom style that will be used to show rows that did not pass the filter (instead of making them invisible).Enabled = false.ApplyFilters().ActiveFilter != null) { _btnApplyFilters. } The code simply applies all the active filters and disables the button until the next change.C1FlexGrid. cs.LightSalmon. assume that instead of showing and hiding rows you wanted to apply different styles to indicate whether the the rows pass the filter or not. Next. For example. When the button is clicked. the following event handler executes: private void _btnApplyFilters_Click(object sender. break. as shown below: void _flex_AfterEdit(object sender.Column c in _flex.Styles. EventArgs e) { _flex.AllowFiltering = true.BeforeFilter += _flex_BeforeFilter.DarkOrange. // create style for rows excluded by the filter var cs = _flexStyles. _flex.AfterFilter += _flex_AfterFilter.{ foreach (C1. // connect handlers for the before and after filter events _flex.DataSource = dtInvoices.RowColEventArgs e) { _flex. you could call the ApplyFilter directly from the AfterEdit event handler. Style = null. implementing your own custom user interface.{ _flexStyles. EventArgs e) { // get style used to show filtered out rows var cs = _flex. // configure timer to apply the filter 1/2 second after the 98 . This type of search allows users to type in a value and automatically filters the grid rows to show the rows that contain the search string in any column. These are the rows that were hidden by the filter. It then scans the rows on the grid and applies the new style to all rows that have the Visible property set to False. if (row.Styles["filteredOut"]. row. We also define a timer that will apply the filter a few milliseconds after the users stops typing into the text box: public Form1() { InitializeComponent(). } The BeforeFilter event handler calls the new BeginUpdate method to prevent the grid from repainting itself until we are done applying the custom style to the rows that are filtered out. The BeginUpdate and EndUpdate methods replace the Redraw property which has been deprecated.Rows. To implement the iTunes-style search. However.EndUpdate().Visible) { // normal row.Count.Rows[r]. we start with a text box that contains the text that will be used as a filter parameter. For example. r++) { var row = _flexStyles. Once this is done. } // apply styles after the filter has been applied void _flexStyles_AfterFilter(object sender. you can use the column filter classes independently.Style = cs. the code calls EndUpdate to restore grid updating.Rows. } else { // filtered row. Customizing the Filtering UI We believe the default filtering behavior and UI will address the vast majority of scenarios that involve column filtering. } } // resume updates _flexStyles.BeginUpdate(). // apply style to all rows for (int r = _flexStyles. reset style row. The AfterFilter event handler starts by retrieving the style we created to show the rows that have been filtered out. r < _flexStyles. make visible and apply style row.Visible = true.Fixed. the code below shows how you can use the ConditionFilter class to implement an iTunes-style search box for the C1FlexGrid. .Fixed. r++) { bool visible = false.Win. all we need to do is create and apply the filter when the timer ticks: // apply filter when the timer ticks void t_Tick(object sender.Condition1.Count. for (int r = _flex. Cols.C1FlexGrid. methods. EventArgs e) { _timer. for (int c = _flex.Text. // configure filter var filter = new C1.Fixed.Cols. // monitor changes to the search box _txtSearch.Operator = C1.Cols. _timer. c])) { visible = true.Visible = visible.Condition1.// user stops typing into the search box _timer. } // re-start timer when the text in the search box changes void _txtSearch_TextChanged(object sender. } C1FlexGrid Property Groups The C1FlexGrid control has a rich set of properties. } } _flex. c < _flex.Tick += t_Tick. Select specific elements below for more details.Parameter = _txtSearch.BeginUpdate(). methods.Contains. _timer. The reference below shows the most important properties.ConditionFilter(). } Now that the timer is configured. 1) Grid Layout Rows. and events.Stop(). r < _flex. c++) { if (filter.Stop(). } _flex.Start(). You do not have to know all of them in order to use the control effectively.TextChanged += _txtSearch_TextChanged. filter. ScrollBars 2) Cursor and Selection 99 .Interval = 500. // apply filter _flex.Rows.ConditionOperator.Rows. AutoSizeCols.Win.EndUpdate(). Some elements appear in more than one group.. _timer.Rows[r]. EventArgs e) { // done for now. filter. break.Count.C1FlexGrid. and events grouped by usage type.Apply(_flex[r. SaveGrid. AfterDragRow. FindRow. AllowDragging. EditMask. Clip. SetData. CellChanged 5) User Interface AllowEditing. AfterResizeRow. Level. GetData. AutoSearchDelay. SaveExcel. BeforeResizeRow. Tree. Row. AfterRowColChange. AutoResize. ShowCell. PrintGrid 10) OLE Drag Drop DragMode. AfterEdit. BeforeDragRow. BeforeSelChange. Aggregate. DataMember. MouseRow. ShowScrollTip 6) Outlining and Summarizing Subtotal. FinishEditing. StartEditing. AfterResizeColumn. ChangeEdit 4) Getting and Setting Values Item (indexer). Collapsed. BeforeResizeColumn. GetDataDisplay. BeforeCollapse. Editor. AfterDataRefresh. IsNode. BeforeRowColChange. AllowSorting. ComboList. ValidateEdit. Col. AllowMerging. GetCellRange. BeforeEdit. LoadExcel. KeyUpEdit. KeyActionTab.SelectionMode. BeforeDragColumn. AllowResizing. KeyActionEnter 3) Editing AllowEditing. KeyDownEdit. AfterDragColumn. AutoSearch. KeyPressEdit. SetCellImage. StartEdit. DropMode. Loading. AfterSelChange. and Printing Grids LoadGrid. Select. ColSel. MouseCol. GridError 9) Saving. RowSel. ClipSeparators. CellButtonClick. AfterCollapse 7) Merging Cells AllowMerging 8) Data Binding DataSource. BeforeMouseDown 11) Filtering 100 . AfterSort. BeforeSort. GetCellImage. you can assign both properties simultaneously with a single call to the SetDataBinding method. To add a data source to your project. assign the data source object to the grid's DataSource property. either through the DataSource property in the Properties window or the Choose Data Source box in the C1FlexGrid Tasks menu. Sample Project Available For an example of reordering the grid columns after binding to a data source. If the data source object contains more than one table. DataView. see C1FlexGrid Tasks Menu (page 40). C1ExpressView. it will automatically refresh its columns to bind to the columns available in the data source. For more information on the C1FlexGrid Tasks menu. DataSet. You can also set column properties such as their Width. To bind the grid to a data source.NET Framework documentation. Clicking the drop-down arrow next to either the DataSource property in the Properties window or the Choose Data Source box in the C1FlexGrid Tasks menu allows you to select from a list of available data sources or to add a data source to your project. see the ComponentOne DataObjects for WinForms documentation included in ComponentOne Studio Enterprise and ComponentOne Studio for WinForms.Data Binding Data binding is a process that allows one or more data consumers to be connected to a data provider in a synchronized manner. C1FlexGrid also supports data binding to ComponentOne DataObjects for WinForms components such as C1ExpressTable. When you assign a new data source to the grid. other controls connected to the same data source will change to reflect the new value. see the ColumnOrder sample on ComponentOne HelpCentral For details about creating ADO. For details about using ComponentOne DataObjects for WinForms. EditMask and Format. Binding to a Data Source Without writing a line of code.NET data source objects such as DataTable. You can then customize the columns by moving. There are two ways to access the wizard. If you edit a value on a data-bound grid. other controls connected to the same data source will change to reflect the new current record. you can easily bind C1FlexGrid to a data source using the Data Source Configuration Wizard in Visual Studio. 101 . C1DataView. If you move the cursor on a data-bound grid. C1DataTableSource and C1DataSet. and DataViewManager. or deleting them.NET data source objects. please refer to the . Alternatively. C1FlexGrid supports data binding to ADO. you must also set the DataMember property a string that specifies which table should be used. hiding. C1ExpressConnection. click Add Project Data Source to open the Data Source Configuration Wizard. On the Choose Your Data Connection page. Mobile device users click here for additional information.NET Framework Data Provider for SQL Server Mobile Edition. If you have not already connected to the database. you can specify the location of the database. The default selection is Database. change the Data source to one that is supported by the Compact Framework. you can specify a new connection by clicking the New Connection button.The Data Source Configuration Wizard walks you through adding a data source step by step. such as the . in the Add Connection dialog box. If you are using the Mobile edition of ComponentOne FlexGrid for WinForms. Clicking the New Connection button opens the Add Connection dialog box where you can browse to the location of your database and test the connection. The Choose a Data Source Type page allows you to choose which type of application you would like to gather information from. 102 . For example. and adds them to your project.Selected = true. On this page you can specify a name or use the default provided by the wizard. On the Choose Your Database Objects page you can specify which tables and fields you want to include in your DataSet. The wizard creates the DataSet. the following code selects the data in the second cell of a row:   Visual Basic Row(2). changing data on the grid changes it in the underlying data source. in the C:\Program Files\Microsoft Visual Studio 8\SmartDevices\SDK\SQL Server\Mobile\v3. You can also provide a name for your DataSet or use the default provided by the wizard. If you double-click the form. the grid manages its own data source. In unbound mode.Then you can use a supported database. Storing and Retrieving Data The C1FlexGrid control can be used in bound or unbound mode. BindingSource.0 folder for Microsoft Visual Studio 2005. 103 . Microsoft provides a Northwind. In this mode. The wizard saves and names your connection on the Save the Connection String to the Application Configuration File page. Click the dropdown arrow again next to the DataSource property or the Choose Data Source box in the C1FlexGrid Tasks menu and then select the data source. In bound mode. for example. by default. In either bound or unbound modes.sdf. a SQL Server Mobile Edition Database. and all the data displayed on the grid comes from the data source. you will also notice that the code to fill the database is automatically generated in the Form_Load event.Selected = True C# Row[2]. and TableAdapter. The indexers allow you to specify a cell in a row or column from which to get or set the data stored there. the grid is connected to a data source. the easiest way to access data in the C1FlexGrid is using the Row and Column indexers. ) For example.1 _flex(r. The Item property is an indexer that takes row and column indices and gets or sets the data stored in the cell. To use different delimiters. If the conversion fails. the following code stores row numbers in the first grid column:  Visual Basic Dim r As Integer For r = _flex.Rows. r <= _flex. you can set and retrieve the contents of arbitrary cell ranges using CellRange objects (page 51). the grid fires the GridError event and does not change the cell.Count .1. r++) { _flex[r.Fixed To _flex. (You can also use column names as indices.Rows.Fixed. This property is especially useful in handling the clipboard and drag-drop operations.Count . You can override this behavior using the SetData method and setting the coerce parameter to False.Rows. use the GetDataDisplay method. To retrieve a string containing the formatted version of the data (what the grid displays to the user). You can also set and retrieve the contents of the selection using the Clip property. the grid returns the actual data stored in the cell. By default.The Item property is another easy way to access data in the C1FlexGrid. 0] = r. change the ClipSeparators property. When you retrieve data using the indexers. the Clip property returns a string with tab characters (Chr(9)) between cells and return characters (Chr(13)) between rows. the grid tries to convert that value into the column's specified DataType. Finally.Rows. 0) = r Next C# for (int r = _flex. 104 . }  When you assign a value to a cell. This sample shows how to implement your own merging logic to create a TV-guide display. This sample attaches notes to cells on a C1FlexGrid and implements Excelstyle cell notes using two classes: CellNote and CellNoteManager. This sample uses the C1FlexGrid control. BoundDelete BoundFinishEdit BoundImage C1FlexGridPrintable CellBorders CellDataType CellMerging CellNotes ColumnEditor CustomDataMap CustomEditor CustomMerge 105 . This sample uses the C1FlexGrid control. This sample shows how to implement your own cell editor. This sample uses OwnerDrawn cells to build a chart based on the grid data. This sample uses the C1FlexGrid control. This sample assigns cell types (and editors) on a per-cell basis.C1FlexGrid namespace. This sample calls the C1. This sample deletes rows from a bound FlexGrid. Samples can be accessed from the ComponentOne Sample Explorer.Win. This sample shows various types of cell-merging in a C1FlexGrid control. This sample exposes the C1FlexGrid design-time column editor in your controls. To view samples. This sample uses the C1FlexGrid control.FlexGrid for WinForms Samples Please be advised that this ComponentOne software tool is accompanied by various sample projects and/or demos which may make use of other development tools included with the ComponentOne Studios. This sample shows how to bind the grid to image fields stored as OLE objects. This sample demonstrates how to commit changes to a DataRow after editing.This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample provides a printable (via C1Preview) C1FlexGrid control.  Visual Basic Samples Sample AutoSizeEdit BarChart Blinker Description This sample demonstrates resizing the editor while the user types. This sample uses OwnerDraw to provide custom cell borders. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control and calls the C1. This causes all cells that have that style to blink. This sample shows how you can use CellStyles to make cells blink. This sample uses the C1FlexGrid control.C1Preview namespace. on the desktop. click the Start button and then click All Programs | ComponentOne | Studio for WinForms | Samples | FlexGrid Samples. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample demonstrates how to customize the options in drop-down lists when using DataMaps. This sample uses the C1FlexGrid control. The sample creates a custom style and uses a timer to change the foregound color on that style. This sample uses the C1FlexGrid control. This sample shows how to test grid response to changes in the data source object. formats. and other properties usually assigned to grid columns are assigned to grid rows. This sample uses the C1FlexGrid control. This sample populates a grid from a DataReader. This sample calls the C1. This sample uses the C1FlexGrid control. and bind a DataTable object to the grid (including add/remove rows). This sample uses the C1FlexGrid control. This sample uses the CreateImage method to print grids with arbitrary row and column breaks. This sample uses the C1FlexGrid control. This sample calls the C1.CustomMerge2 CustomMerge3 CustomMerge4 CustomPrint CustomTree DataIndex DataMap DataReader DataTable This sample shows how to implement your own merging logic to mix merging modes.Win.DataIndex property to get the underlying data row. This sample uses the C1FlexGrid control. This sample shows how to customize grouping by overriding the GetData method. This sample shows images stored in a DataTable. This sample uses the C1FlexGrid control. This sample shows how to implement manual OleDragDrop between controls and within the grid. This sample uses the C1FlexGrid control.Win.C1FlexGrid namespace. This sample shows a how to add totals to a bound grid with a FilterRow. This sample sets up a grid in 'transposed' format. masks. This sample shows how to assign styles to a cell based on the contents of another cell. edit masks. This sample shows how to display bound data in a hierarchical tree view. DataTree DBDynamicStyles DBImageField DBSchemaChange DBTree DragDrop DragDropManual DragRow DynamicStyles Editing FilterRow_With_Totals FlexByRow 106 . This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control.Win. This sample assigns styles to grid cells based on their contents. This sample shows how to customize automatic Drag & Drop. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control to build a tree. This sample uses the Row. This sample uses data-mapped columns when bound to a data source. This sample shows how to customize grouping by overriding the GetData method. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. lists.C1FlexGrid namespace. This sample uses the C1FlexGrid control. populate. This sample shows how to drag rows between grids. and checkboxes. This sample uses the C1FlexGrid control. This sample binds the grid to a hierarchical data source and show details in child grids. This sample demonstrates how to edit cells using textboxes. This sample shows how you can create. This sample calls the C1. In this sample data types.C1FlexGrid namespace. This sample demonstrates how to build a custom tree with product information. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid and C1Chart controls. This sample shows how to hide repeated data in an outline. This sample uses the C1FlexGrid control. This sample shows how to display RTF text in grid cells.FlexGroup FreezeBottom GridChart HierData Hyperlink LoadSpeed MapAndGroup MergeStyles MultiColumnDictionary Outline PdfExportVB ProductTree RTFGrid ScrollPosition SelectionMode Sorting Splits StartEditing Styles Subtotals Transpose TreeCheck This sample shows how you can implement Outlook-style grouping and filtering using the C1FlexGrid. This sample uses the C1FlexGrid control. This sample uses C1Pdf method to export C1FlexGrids to PDF files. This sample shows how the ScrollPosition property works. This sample demonstrates how to split a C1FlexGrid into multiple views. and cells. This sample shows how to transpose data in a grid. This sample demonstrates how to show frozen rows at the bottom of a grid. This sample uses the C1FlexGrid control. This sample implements a grid that stays in cell-editing mode. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample creates subtotals for multiple columns. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample shows several sorting techniques. This sample shows how you can bind to hierarchical data sources (masterdetail style). This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample uses the MultiColumnDictionary class to implement multicolumn drop-downs. This sample uses the C1FlexGrid control. 107 . This sample shows how you can add hyperlinks to cells in the C1FlexGrid. This sample uses the C1FlexGrid control. This sample shows the effect of the SelectionMode property. This sample uses the C1FlexGrid control. This sample shows how to add checkboxes to a grid tree. columns. This sample uses the C1FlexGrid control. This sample shows three techinques for loading data into a C1FlexGrid. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This samples show how you can attach a FlexGrid to a C1Chart control. This sample uses the C1FlexGrid control. This sample shows how you can use Styles to customize the appearance of the C1FlexGrid. This sample merges CellStyles assigned to rows. This sample shows grouping and sorting behavior when using data-mapped columns. The sample shows how you can control and customize the grid's built-in 108 . This sample shows how to show cell labels after a specified interval. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample shows how to delete rows from a bound FlexGrid. This sample shows how to zoom in on the selected cell. This sample shows how to provide dynamic data sorting and grouping. This sample uses the C1FlexGrid control. This sample shows how to use CellStyles to make cells blink.TreeNode Validate ZoomCell This sample shows how to manage an outline tree using the C1FlexGrid Node objects. This sample uses the C1FlexGrid control. This sample shows how to expose the FlexGrid design-time column editor in your controls. This sample uses the C1FlexGrid control and calls the C1. This sample shows how to use the ErrorProvider control with the C1FlexGrid. This sample shows how to use OwnerDraw to provide custom cell borders. This sample shows how to draw bar charts using the grid cells. This sample shows how to use the ImageMap property with a data-bound grid. This sample attaches notes to cells on a C1FlexGrid and implements Excelstyle cell notes using two classes: CellNote and CellNoteManager. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample provides a printable (via C1Preview) C1FlexGrid control. This sample uses the C1FlexGrid control. This sample shows how to display animated gifs in grid cells. This sample shows how to complete entries while the user types.C1Preview namespace. This sample shows a grid that derives from C1FlexGrid and provides an object model compatible with the VSFlexGrid control. This sample shows how to commit changes to a DataRow after editing. This sample shows how to resize the editor while the user types. This sample shows how to assign cell types (and editors) on a per-cell basis. This sample uses the C1FlexGrid control. This sample shows how to use the filtering feature in C1FlexGrid 2010. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control.  C# Samples Sample AcceleratorCaption Analyze AnimagedGif AutoComplete AutoSizeEdit BarChart Blinker BoundDelete BoundFinishEdit BoundImageMap C1FlexGridPrintable CellBorders CellDataType CellLabelDelay CellNotes Classic (C1FlexGridClassic) ColumnEditor ColumnFilters Description This sample shows how to add accelerator keys to grid captions. This sample calls the C1. This sample shows how to implement your own cell editor. This sample uses the C1FlexGrid control. This sample uses OwnerDraw to implement custom (non-rectangular) selection. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample demonstrates how to show images stored in a DataTable.Win. DBDynamicStyles DBImageField 109 . This sample uses the C1FlexGrid control. This sample calls the C1. This sample uses the C1FlexGrid control. This sample calls the C1. This sample shows how to customize grouping by overriding the GetData method.Win.Win. This sample shows how to implement a custom data source object. This sample shows how to summarize and cross-reference data using PivotTables. This sample shows how to use the CreateImage method to print grids with arbitrary row and column breaks.NET.Win. add and remove rows. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control.C1FlexGrid namespace. This sample shows how to implement your own merging logic to mix merging modes.C1FlexGrid namespace. This sample shows how to implement your own merging logic to create a TV-guide display.C1FlexGrid namespace. . This sample calls the C1. This sample shows how to implement custom filters for the C1FlexGrid.Win. This sample shows how to bind the grid to a hierarchical data source and show details in child grids.C1FlexGrid namespace. and custom edit controls with the C1FlexGrid. This sample uses the C1FlexGrid control. This sample shows how to use built-in. This sample shows how to use the Row.Win. This sample shows how to assign styles to grid cells based on their contents. This sample uses the C1FlexGrid control. This sample calls the C1. This sample uses the C1FlexGrid control. This sample shows how to implement your own sorting logic with a custom IComparer object. ColumnOrder ColumnWidthTip CrossTabs CustomData CustomDataMap CustomEditor CustomEditors CustomFilters CustomMerge CustomMerge2 CustomMerge3 CustomMerge4 CustomPrint CustomPrintMultiGrid CustomSelection CustomSort DataIndex DataTable DataTree This sample shows how to position columns dynamically. This sample shows how to customize grouping by overriding the GetData method.C1FlexGrid namespace.C1FlexGrid namespace. This sample shows how to customize the options in drop-down lists when using DataMaps. This sample shows how to show a ToolTip while the user resizes columns.filters using the AllowFiltering property and the AfterFilter event.DataIndex property to get the underlying data row. This sample calls the C1. This sample shows how to use the CreateImage method to print multiple grids in a single document. This sample shows how to bind to a DataTable. This sample uses the C1FlexGrid control. This sample shows how to drag rows between grids. This sample uses the C1FlexGrid control. This sample shows how to bind to hierarchical data sources (master-detail style). This sample adds a context-menu that allows sorting and filtering data. This sample shows how to test grid response to changes in the data source object. This sample uses the C1FlexGrid control. This sample calls the C1. This sample shows how to drag groups of merged columns. 110 . This sample shows how to customize automatic Drag & Drop This sample uses the C1FlexGrid control.Win. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample shows how to display bound data in a hierarchical tree view. This sample shows how to load and save Microsoft Excel files (. This sample shows how to save changes to the underlying database. This sample uses the C1FlexGrid control. This sample shows how to set up a grid in 'transposed' format. This sample uses the C1FlexGrid control. This sample shows how to implement hierarchical data binding using the C1FlexGrid. This sample shows how to how to find a row in the underlying datasource. This sample uses the C1FlexGrid control.DBImages DBSchemaChange DBTree DBUpdate DragDrop DragImages DragMerged DragRow DynamicStyles ErrorInfo Excel ExcelStyleFilter FilterRow FindRow FlexByRow FlexGroup FlexHierarchical FreezeBottom GridChart HierData HierData2 HostControls Hyperlink This sample shows how to bind the grid to a data base with image fields stored as OLE objects. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid and C1Chart controls. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample shows how to add hyperlinks to cells in the FlexGrid.xls). This sample shows how to bind to hierarchical data sources (master-detail style). This sample uses the C1FlexGrid control. This sample shows how to implement a FilterRow on a FlexGrid control. This sample demonstrates how to show error information on the grid. This sample shows how to attach a FlexGrid to a C1Chart control. This sample shows how to implement Outlook-style grouping using the C1FlexGrid. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample shows how to customize Ole Drag and Drop to use cell images. This sample shows how to assign styles to a cell based on the contents of another cell. This sample demonstrates how to show frozen rows at the bottom of a grid. This sample shows how to host controls in grid cells.C1FlexGrid namespace. This sample shows how to autosize Owner-Drawn cells. This sample shows how to create a complex master-detail display. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample shows how to place a new row template above the grid. columns. This sample uses the C1FlexGrid control. 111 . This sample shows how to hide repeated data in an outline. This sample uses the C1FlexGrid control. This sample shows how to use OwnerDraw with transparency to get MediaPlayer-like effects. This sample uses the DataTable. This sample shows how to shows how the ScrollPosition property works. This sample shows the new features that were added for the V1/2009 release. This sample shows how to use different styles to display DataRows in different states. This sample shows how to prevent the user from selecting certain columns. This sample shows how to merge CellStyles assigned to rows. This sample shows how to use the MultiColumnDictionary class to implement multi-column drop-downs. This sample shows how to implement multi-range selection. This sample shows how to shows several sorting techniques. This sample uses the C1FlexGrid control.Win. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control.LegacyDates LockedColumns MasterDetail MergeStyles MultiColumnDictionary MultiParent MultiSelection NewFeatures20091 NewRowTemplate Outline OwnerDraw OwnerDrawAlpha PasswordChar PdfExport RowStateDisplay RTFGrid ScrollPosition SelectionMode SetupEditor SimpleCalc Sorting SortNulls Splits This sample shows how to use an unbound column to convert dates stored as strings into real dates. and cells. This sample shows how to split a C1FlexGrid into multiple views.C1FlexGrid namespace. This sample shows how to use the C1Pdf method to export C1FlexGrids to PDF files. This sample shows how to use a custom sort to place null values at the bottom of the grid. This sample shows how to shows the effect of the SelectionMode property.Compute method to evaluate expressions in grid cells and displays the results using OwnerDraw. This sample uses the C1FlexGrid control. This sample shows how to display RTF text in grid cells. This sample calls the C1. This sample shows how to create and bind master-detail DataSets in code. This sample uses the C1FlexGrid control. This sample shows how to use the C1FlexGrid to enter and edit passwords. This sample uses the C1FlexGrid control. This sample shows how to use the SetupEditor event to customize the grid editors. This sample shows how to implement a grid that stays in cell-editing mode. This sample uses the C1FlexGrid control. This sample shows how to manage an outline tree using the FlexGrid Node objects. This sample shows how to update the grid from a different thread. This sample uses the C1FlexGrid control. This sample demonstrates how to show a ContextMenu after selecting an item on the grid. This sample demonstrates how to show different types of built-in editors and dynamic formatting. This sample shows how to additional support for unbound columns. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample shows how to provide three-state (grayable) values in Boolean columns. This sample shows how to add checkboxes to a grid tree.Win. This sample uses the C1FlexGrid control. This sample uses the C1FlexGrid control. This sample shows how to create subtotals for multiple columns. This sample uses the C1FlexGrid control.SqlBuilder StartEditing Subtotals Themes ThreadedUpdate TreeCheck TreeNode TriStateBound UnboundColumns ZoomCell This sample shows how to a grid-based graphical interface for creating SQL statements. This sample calls the C1.C1FlexGrid namespace. This sample uses the C1FlexGrid control. This sample shows how to zoom in on the selected cell. This sample shows how to draw bar charts using the grid cells.  ComponentOne FlexGrid for Mobile Devices Visual Basic Samples Sample Analyze BarChart EditData ThreadedUpdate Description This sample shows how to provide dynamic data sorting and grouping. This sample shows how to update the grid from a different thread. This sample shows how to draw bar charts using the grid cells. This sample shows how to change the appearance of the grid to achieve one of several pre-defined looks. 112 .  ComponentOne FlexGrid for Mobile Devices C# Samples Sample Analyze BarChart ContextMenu Description This sample shows how to provide dynamic data sorting and grouping. automatic subtotals. 6. This sample demonstrates how to show different types of built-in editors and dynamic formatting. and clipboard support. automatic sorting. input masks.DataTree EditData MasterDetail TransparentImages This sample demonstrates how to show hierarchical data in a drill-down grid. FlexGrid for WinForms Tutorials The following sections contain tutorials that illustrate some of the main features in the C1FlexGrid control. The tutorials are: Tutorial Edit Tutorial (page 113) Outline Tutorial (page 126) Data Analysis Tutorial (page 137) Description Starting with a basic data-entry grid. check boxes. The tutorials walk you through the creation of several simple projects. The distribution CD contains more sophisticated samples that can be used as a reference. Starting with a grid containing sales data for different products. 2. then adds the following features: 1. This sample demonstrates how to show hierarchial data using two grids. this tutorial show how to implement dynamic layout (column order). and salespeople. describing each step in detail. regions. 4. this tutorial shows how to implement data formatting. This sample shows how to render images with transparency. data validation. 5. Shows how you can use the C1FlexGrid as an outliner to display structured (or hierarchical) data. 3. Edit Tutorial This tutorial starts with a basic data-entry grid. Formatting Check boxes Drop-down lists Complex data validation Clipboard support Custom editors Here is what the final application will look like: 113 . cell merging. drop-down lists. and outlining. Set the following properties in the Properties window for the C1FlexGrid control: Property Dock Cols. This makes the objects defined in the C1FlexGrid assembly visible to the project and saves a lot of typing. add the following statement:   Visual Basic Imports C1.C1FlexGrid C# using C1.C1FlexGrid. then clicking on the form and dragging until the object has the proper size. Step 1 of 6: Create the C1FlexGrid Control for the Edit Tutorial Start a new project and add a C1FlexGrid control to the form by clicking the C1FlexGrid icon on the Toolbox. you may need to re-install the product.Fixed Setting Fill 5 0 2.Win. Then. 3. look for the C1FlexGrid control on the list of .Win. 1. If you can't find the grid in the component list. or in code.A video is available for this tutorial on the ComponentOne Videos Web page. Double-click the form caption area to open the code window. Set up the columns by either in the designer through the Column Tasks menu or the C1FlexGrid Column Editor. right-click on the toolbox and select Choose Items.Count Cols. At the top of the file. In the Designer 114 .NET components and make sure it is checked. If you can't find the C1FlexGrid control in the toolbox. Set the Column Caption and Data Field boxes for the remainder of the columns as follows: Column 1 Column Caption Data Field Column 2 Column Caption Data Field Column 3 Column Caption Data Field Column 4 Column Caption Data Field Bonus Bonus Sales Sales Salesperson Salesperson Region Region Alternatively. Enter Product in the Column Caption and Data Field boxes. Set the Name and Caption properties for the remainder of the columns as follows: Column 1 Name Caption Column 2 Name Caption Column 3 Name Caption Column 4 Name Bonus Sales Sales Salesperson Salesperson Region Region    115 . In the left pane. For details on how to access the C1FlexGrid Column Editor. Select the Column 0 in the right pane. see Accessing the C1FlexGrid Column Editor (page 149). the columns can also be set up through the C1FlexGrid Column Editor:  Open the C1FlexGrid Column Editor by clicking Designer in the C1FlexGrid Tasks menu. This will open the Column Tasks menu for the column.   Select the first column in the grid. set the Name and Caption properties to Product. c1FlexGrid1.1 C1FlexGrid1(0. i) = colNames(i) C1FlexGrid1. Dim cols As String = "Product|Region|Salesperson|Sales|Bonus" Dim colNames As String() = cols. In Code Add the following code to the Form_Load event:  Visual Basic ' Set up the columns.1. for (int i = 0. c1FlexGrid1. 116 .Caption Bonus  Click OK when finished to close the editor.Cols[i].Cols. Press F5 to run the project. i] = colNames[i]. }  Run the program and observe the following: That's it. or just type new entries over existing ones.Split("|") Dim i% For i = 0 To C1FlexGrid1.Name = colNames[i]. string[] colNames = cols.Name = colNames(i) Next C# // Set up the columns. string cols = "Product|Region|Salesperson|Sales|Bonus".Count . and you can start typing data into the control.Split(new char[] { '|' }). i++) { c1FlexGrid1[0. Press F2 or the SPACEBAR to edit existing entries.Count .Cols. i <= this.Cols(i). Click the ellipsis button next to the Format property. Click OK to close the Format String dialog box. This will open the Column Tasks menu for the Bonus column. Click OK to close the editor. 3. see Accessing the C1FlexGrid Column Editor (page 149).DataType = typeof(Decimal). Alternatively. 7. Set the DataType property to Decimal.Cols("Sales") c. 8.Format = "c2" c = C1FlexGrid1. 9. This will open the Format String dialog box. // Currency. 3. For details on how to access the C1FlexGrid Column Editor. Click the ellipsis button in the Format String box to open the Format String dialog box. In Code To specify the DataType and Format for the columns. Select the Sales column in the right pane.ImageAlign = ImageAlignEnum. 6. c. Column c = c1FlexGrid1. Select the Bonus column in the grid. Set the DataType property to Boolean. 5. The C1FlexGrid control allows you to specify the DataType and Format for each column.Format = "c2". 5. 117 .Cols["Sales"]. 4. 6. Dim c As Column = C1FlexGrid1. Click OK to close the Format String dialog box.Cols("Bonus") c. These properties can be set either in the designer or in code. Set the Data Type box to Decimal. Select the Sales column in the grid. Set the Data Type box to Boolean. 1. add the following code after the code added in Step 1 of 6: Create the C1FlexGrid Control for the Edit Tutorial (page 114):  Visual Basic ' Set the column DataType and Format. 2.Step 2 of 6: Set Column Types and Formats When displaying numeric or date values.CenterCenter  C# // Set the column DataType and Format. you will typically want to adopt a consistent format for the values.DataType = GetType(Decimal) ' Currency. 7. Under Format type select Currency. 4. This will open the Column Tasks menu for the Sales column. c.DataType = GetType(Boolean) c. Under Format type select Currency. Select the Bonus column in the right pane. In the Designer 1. Open the C1FlexGrid Column Editor by selecting Designer in the C1FlexGrid Tasks menu. the DataType and Format properties can also be set up through the C1FlexGrid Column Editor: 2. c. c. Wahoos. South. 2. This is the default behavior for Boolean columns. This will open the Column Tasks menu for the Product column. In the Designer 1. This property can be set either in the designer or in code. Step 3 of 6: Incorporate Drop-Down Lists Entering data is a tedious and error-prone process.c = c1FlexGrid1. Run the program and observe the following: The new code formats the Sales column to store and display currency values. and increase the consistency of the data. Click the ellipsis button in the Combo List box to open the Combo List dialog box.CenterCenter.DataType = typeof(bool). East. Drop-down lists are great because they minimize the amount of typing you must do. To use these lists as drop-downs in the C1FlexGrid control. only how it is displayed. and Paula). and Gadgets). and that there are three full-time sales people (Mary. Select the Product column. and West). you will notice that the grid won't accept non-numeric entries. If you enter some numeric and non-numeric values in the Sales column. Wahoos. The Bonus column displays values as checkboxes. Let's assume that our tutorial project only involves sales of three products (Applets. Enter Applets. in four regions (North. which can be toggled with the mouse or with the keyboard. 3. Sarah. and Gadgets as shown below: 118 .ImageAlign = ImageAlignEnum.Cols["Bonus"]. Note that the Format property does not affect the data in any way. c. and the Bonus column to deal with Boolean values. all you have to do is build strings containing the items in each list (separated by pipe characters) and assign them to the ComboList property of each column. reduce the chance of errors. 4. Enter North. East. 10. Select the Salesperson column. 7. South. 6. Select the Region column. 5. Click the ellipsis button in the Combo List box. 9. Click the ellipsis button in the Combo List box. 119 . Click OK. Click OK to close the Combo List dialog box. and West as shown below: 8. 4. Alternatively.Cols("Region"). 7. 3.Cols("Product"). set the ComboList property to Applets|Wahoos|Gadgets. In Code To add the combolists. the ComboList property can be set using the C1FlexGrid Column Editor: 1. Enter Mary. Select the Dropdown Combo option. Select the Product column in the right pane. add the following code after the code added in Step 2 of 6: Set Column Types and Formats (page 117):  Visual Basic ' Set up the drop-down lists.ComboList = "Applets|Wahoos|Gadgets" C1FlexGrid1. For details on how to access the C1FlexGrid Column Editor.  120 . 5. Select the Region column in the right pane. set the ComboList property to North|South|East|West. 8.Cols("Salesperson"). In the left pane set the ComboList property to |Mary|Paula|Sarah. Click OK. In the left pane.11. Click OK to close the editor. and Sarah as shown below: 12.ComboList = "|Mary|Paula|Sarah" C# // Set up the drop-down lists. In the left pane. C1FlexGrid1. 13.ComboList = "North|South|East|West" C1FlexGrid1. Select the Salesperson column in the right pane. Open the C1FlexGrid Column Editor by selecting Designer in the C1FlexGrid Tasks menu. 2. 6. see Accessing the C1FlexGrid Column Editor (page 149). Paula. you should use the ValidateEdit event. c1FlexGrid1. Run the program and observe the following: Notice how the last ComboList string starts with a pipe (text input cursor). To prevent data-entry mistakes and costly lawsuits. Select Case e. For that. these values will be edited using a drop-down combo. ByVal e As ValidateEditEventArgs) Handles C1FlexGrid1. Press F5 to run the project again. Add the following code to the form:  Visual Basic Private Sub C1FlexGrid1_ValidateEdit(ByVal sender As Object.Col Case 0 121 .ComboList = "|Mary|Paula|Sarah".Cols["Salesperson"]. but you will often need stricter validation to ensure that the data entered is correct.ValidateEdit Dim rgn As String = String.Empty ' Collect the data we need. You may click on it to show the list. we want to prevent users from entering this combination into the control.ComboList = "North|South|East|West".ComboList = "Applets|Wahoos|Gadgets". This helps prevent errors. For example. This allows users to type additional names that are not on the list. as opposed to a simple drop-down list. The following event checks the data after each edit and prevents invalid entries. or simply type the first letter of an entry to highlight it on the list. and then move the cursor around.Empty Dim prd As String = String.Cols["Product"]. the grid will ensure that only data of the proper type is stored in that column. imagine that anti-trust regulations prevent us from selling our Applets in the North region. a drop-down button becomes visible.Cols["Region"]. In other words. When you move the cursor to one of the columns that have combo lists. Step 4 of 6: Add Data Validation If you assign a data type to a grid column. c1FlexGrid1.c1FlexGrid1. Cancel = true. e. if ( prd == "Applets" && rgn == "North" ) { MessageBox. // Collect the data we need.Empty.Editor.Text. "Product") = C1FlexGrid1.Text property. " & _ "Please verify input. break. You will see that the control will reject them. rgn = c1FlexGrid1. 122 .Text. "Region"].Editor.Editor.Row.Show("Warning: Regulation #12333AS/SDA-23 forbids " + "the sale of " + prd + " in region " + rgn + ". "Region") = C1FlexGrid1(e.Text ' We can't sell Applets in the North Region. " + "Please verify input.Cancel = True End If End Sub  C# private void c1FlexGrid1_ValidateEdit( object sender. This is necessary because the edits have not yet been applied to the control.prd rgn Case 1 prd rgn End Select = C1FlexGrid1.Row.Empty. "Product"].Text = C1FlexGrid1(e. Note that the values being checked are retrieved using the Editor.Row. string prd = string. break. If the test fails.Row.Editor."). then try inputting some bad values. case 1: prd = (string)c1FlexGrid1[e. rgn = (string)c1FlexGrid1[e. ValidateEditEventArgs e) { string rgn = string.") e. switch (e. If prd = "Applets" And rgn = "North" Then MsgBox("Warning: Regulation #12333AS/SDA-23 forbids " & _ "the sale of " & prd & " in region " & rgn & ". } // We can't sell Applets in the North Region.Col) { case 0: prd = c1FlexGrid1. } } Run the program and observe the following: The function starts by gathering the input that needs to be validated. the function displays a warning and then sets the Cancel parameter to True. Press F5 to run the project again. which cancels the edits and puts the cell back in edit mode so the user can try again. Automatic C# c1FlexGrid1.Automatic. Note that you can paste invalid data.AutoClipboard = True C# c1FlexGrid1. Step 6 of 6: Include Custom Editors The C1FlexGrid has powerful built-in editors for entering text.AutoClipboard = true.Automatic C1FlexGrid1.DropMode = DropModeEnum.DropMode = DropModeEnum. and the grid will automatically handle all standard keyboard commands related to the clipboard: CTRL+X or SHIFT+DELETE to cut. which help implement this feature.Step 5 of 6: Add Clipboard Support The Windows clipboard is a very useful device for transferring information between applications.Automatic. C1FlexGrid has two properties. perhaps one of the input controls in the 123 . and CTRL+V or SHIFT+INSERT to paste.DragMode = DragModeEnum. In the Designer Locate the DragMode and DropMode properties and set them both to Automatic.  Run the program and observe the following: Press F5 to run the project again. Simply set the AutoClipboard property to True either in the designer or in code. In Code Add the following code after the code to set the AutoClipboard property:  Visual Basic C1FlexGrid1. and you will be able to drag selections by their edges and drop them into other applications such as Microsoft Excel. masked text. c1FlexGrid1. and more. checkboxes. Another great Windows feature that is closely related to clipboard operations is OLE Drag and Drop. Just set both properties to their automatic settings either in the designer or in code.DragMode = DragModeEnum. In the Designer Locate the AutoClipboard property in the Properties window and set it to True. or drag ranges from an Excel spreadsheet and drop them into the C1FlexGrid control. because our paste code does not perform any data validation. CTRL+C or CTRL+INSERT to copy. DragMode and DropMode. But in some cases you may want to use a custom editor instead. selecting from lists. Adding clipboard support to FlexGrid for WinForms projects is fairly easy. In Code Add the following code after the code added in Step 3 of 6: Incorporate Drop-Down Lists (page 118):   Visual Basic C1FlexGrid1. This is left as an exercise for the reader. then try copying and pasting some data. To attach a custom editor to the Sales column on our tutorial. 2.C1Input library or a control that you wrote. The control is properly positioned.5. For example: 1. 3. 1. Select the Sales column (or Column 3 where the Sales figures will be). When you move the focus to a different cell. The size of the editor isn't exactly right (it looks a bit too small). start by adding a NumericUpDown control to the form. When you start editing by typing a number. But the custom editor doesn't behave exactly like the built-in ones. initialized. Run the program and observe the following: Now run the project and try editing some values in the Sales column. the old value isn't cleared. Notice that the grid uses the NumericUpDown control instead of the built-in editors. and managed. 124 . and set the Editor property to NumericUpDown1. the FlexGrid allows you to easily plug-in custom editors. the value is stored in the grid. Starting in version 2. Set the following properties the Properties window to for the NumericUpDown control: Property BorderStyle DecimalPlaces Maximum ThousandsSeparator Visible Setting None 2 5000000 True False 2. Select Designer from the C1FlexGrid Tasks menu to bring up the grid's column editor. 3. public void C1EditorUpdateBounds(Rectangle rc) { base. You can overcome these problems in a couple of ways.Select(0.Height Bounds = rc End Sub ' Suppress the beeps when a user presses ENTER. One way would be to use the editor's events. // Select the whole entry. GetType(Decimal)) ' Select the whole entry. Bounds = rc.MaxValue).ChangeType(value. System.MaxValue) End Sub ' Set the FontHeight so the control honors the rectangle height. Public Sub C1EditorUpdateBounds(ByVal rc As Rectangle) MyBase.Focused) Then SendKeys.Collections.Enter) Then Parent. Another way would be to create a derived class and implement some methods in the IC1EmbeddedEditor interface.ProcessDialogKey(keyData) End Function End Class  C# internal class MyUpDown : NumericUpDown { // Set the initial value. Value = (decimal)Convert. int. typeof(decimal)).Height.Focus() If (Parent. as in the following code. value = Convert. There's a beep when you press ENTER to finish editing. Protected Overrides Function ProcessDialogKey(ByVal keyData As Keys) As Boolean If (keyData = Keys.ChangeType(value. Select(0. ByVal editorAttributes As IDictionary) ' Apply the initial value. public void C1EditorInitialize(object value. Public Sub C1EditorInitialize(ByVal value As Object. } // Set the FontHeight so the control honors the rectangle height.FontHeight = rc.FontHeight = rc.  Visual Basic Public Class MyUpDown Inherits NumericUpDown ' Set the initial value. MyBase. Int32.Send("{Down}") Return True End If Return MyBase. but that would make it difficult to reuse the control in other projects. 125 .IDictionary editorAttributes) { // Apply the initial value. C1EditorUpdateBounds is called to position the editor over the cell being edited.Enter) { Parent. override protected bool ProcessDialogKey(Keys keyData) { if (keyData == Keys. return true.} // Suppress the beeps when a user presses ENTER.Focused) SendKeys. } return base. This will take care of the first problem. displaying nodes that can be collapsed or expanded to show branches containing subordinate data.ProcessDialogKey(keyData). though (that is why it looks too short for the cell). if (Parent. ProcessDialogKey method is overridden to suppress the beeps when the user presses the ENTER key. It sets the initial value and then selects the whole entry. where it is displayed as a tree. typing the first character will now replace the current contents as we want. When used as an outliner. the C1FlexGrid control behaves like a Tree control.Focus(). The height of the NumericUpDown control is set automatically based on the font size. The tutorial allows you to load an XML document into the grid.   Outline Tutorial This tutorial shows how you can use the C1FlexGrid as an outliner to display structured (or hierarchical) data. Here is what the final application will look like: 126 .Send("{Down}"). The code sets the editor's FontHeight property so it will be positioned exactly over the cell. Because the whole entry is selected. } } The previous code implements three methods:  C1EditorInitialize is called to initialize the editor. Then. A C1FlexGrid control in the area below the button. 127 .NET components and make sure it is checked. right-click on the toolbox and select Choose Items.C1FlexGrid C# using C1. If you can't find the C1FlexGrid control in the Toolbox. This makes the objects defined in the C1FlexGrid assembly visible to the project and saves a lot of typing.Win. 1. At the top of the file.Step 1 of 5: Create the Controls Start a new project and add two controls:   A command Button near the top of the form. look for the C1FlexGrid control on the list of . add the following statement:   Visual Basic Imports C1.C1FlexGrid. you may need to re-install the product. Set the following properties in the Properties window:  Command Button Property Dock Text Setting Top "Open XML File…"  C1FlexGrid Property Dock Setting Fill 2. If you can't find the grid in the component list. Double-click the form caption area to open the code window.Win. Style Setting 2 0 True 1 0 SimpleLeaf Set up the styles for the grid:  Open the C1FlexGrid Style Editor by selecting Styles from the C1FlexGrid Tasks menu. Click OK to close the editor.Style property to None. Alternatively.Count Tree. Select Column 0 in the right pane. see Accessing the C1FlexGrid Column Editor (page 149). Rename CustomStyle1 to Data. see Accessing the C1FlexGrid Style Editor (page 149). Click the Add button.       Set up the columns for the grid:      Select Column 0 in the grid. the TextAlign property to LeftCenter. set the AllowEditing property to False and the Caption property to Element. For details on how to access the C1FlexGrid Column Editor. In the Designer Set the following properties for the C1FlexGrid control in the Properties window: Property Cols. Set the Border.Fixed ExtendLastCol Rows.   128 . or in code by typing (or copying) the following code. Set up the grid either in the designer using the Properties window and editors. Uncheck the Allow Editing check box. Set the Column Caption to Element.Column Tree. and the WordWrap property to False.3. This will open the Column Tasks menu for Column 0. Set the BackColor property to Control. For more information on accessing the C1FlexGrid Style Editor. Set the Column Caption to Text. In the left pane. the columns can also be set up through the C1FlexGrid Column Editor:  Open the C1FlexGrid Column Editor by selecting Designer in the C1FlexGrid Tasks menu.Count Cols. Select Normal in the list of Built-In Styles. Select Column 1. TextAlign = TextAlignEnum.ExtendLastCol = true.BackColor = SystemColors.Cols[0].Style = BorderStyleEnum.Count = 1 C1FlexGrid1.Styles. c1FlexGrid1.Normal.EventArgs e) { // Initialize the grid.AllowEditing = false.Fixed = 0 C1FlexGrid1. c1FlexGrid1.TextAlign = TextAlignEnum. Click OK to close the editor.Normal.Control End Sub In Code  C# private void Form1_Load( System.Styles. In the left pane.Normal.Style = TreeStyleFlags.Rows.Normal. // Initialize the outline tree.Rows.WordWrap = false.Style = BorderStyleEnum. } Run the program and observe the following: The code starts by setting up the grid layout and column heading text.Cols. // Initialize styles. Visual Basic Private Sub Form1_Load(ByVal sender As System. c1FlexGrid1.object sender. CellStyle cs = c1FlexGrid1.Cols(0).LeftCenter C1FlexGrid1. set the Caption property to Text.Add("Data"). 0] = "Element".Tree.AllowEditing = False ' Initialize styles.ExtendLastCol = True C1FlexGrid1(0.LeftCenter. c1FlexGrid1[0. C1FlexGrid1. System.Normal. ByVal e As System.Column = 0.Add("Data") cs. c1FlexGrid1.EventArgs) Handles MyBase.Cols.WordWrap = False Dim cs As CellStyle = C1FlexGrid1. c1FlexGrid1.Load ' Initialize the grid. 1) = "Text" ' Initialize the outline tree.Tree.Tree.Control.Tree. C1FlexGrid1. cs.Styles.None C1FlexGrid1.Styles.Styles.Style = TreeStyleFlags. c1FlexGrid1.Cols.    Select Column 1 in the right pane.Count = 1. 129 . 0) = "Element" C1FlexGrid1(0.Border. c1FlexGrid1. c1FlexGrid1. c1FlexGrid1. c1FlexGrid1.Column = 0 C1FlexGrid1.SimpleLeaf C1FlexGrid1.Fixed = 0.Styles.Border.Cols. C1FlexGrid1.Count = 2 C1FlexGrid1.Normal.None.Object.Styles.Styles.Count = 2.SimpleLeaf. 1] = "Text". c1FlexGrid1[0.BackColor = SystemColors. xml" If fo. Double-click the command button and add the following code to the Button1_Click event:  Visual Basic Private Sub Button1_Click(ByVal sender As System.Object.XmlDocument = New System.Xml. Dim fo As OpenFileDialog = New OpenFileDialog() fo. which contains the data in each XML node. We can start adding some code to it.Load(fo. C1FlexGrid1.Forms.Next. C1FlexGrid1.Rows. 1.XmlDocument() xdoc.DefaultExt = "xml" fo. 0) ' Autosize the tree column.ChildNodes(1).AutoSizeCol(0) 130 .OK Then Exit Sub ' Load the XML file.Count = 1 GetXMLData(xdoc.EventArgs) Handles Button1.Redraw = False ' Populate the grid. Dim xdoc As System.Filter = "XML Files (*. it initializes the outline tree using the Tree property and prevents editing of the XML nodes by setting the AllowEditing property of the first column to False. Step 2 of 5: Read the Data and Build the Outline To read the data and build the outline.Click ' Get the file name.Xml.ShowDialog() <> Windows.FileName) ' Stop redrawing to improve speed. ByVal e As System. Note that the user can still edit data in the second column. C1FlexGrid1.xml)|*.DialogResult. Now the control is ready. add code to the Button1_Click event and add the GetXMLData routine. 1.Count = 1.FileName). the routine uses the AutoSizeCol method to adjust the width of the first column based on its contents. The GetXMLData routine is the main one in this tutorial.Redraw = true. System. and 2. The routine then sets the Redraw property back to True so the grid starts repainting normally. System. c1FlexGrid1. which parses the contents of the file into memory. It traverses the XMLDocument object and builds the outline tree. Add the following code to the form:  Visual Basic 131 . When the file is selected. // Start redrawing. This technique improves performance significantly. and you should always use it when adding substantial amounts of data to the C1FlexGrid. // Autosize the tree column. c1FlexGrid1. and the Show method to expand the outline and show levels 0.Show(2). // Populate the grid. xdoc.Tree.' Show levels 0. and 2. 2.Xml.Show(2) ' Start redrawing.ShowDialog() != DialogResult.AutoSizeCol(0). if ( fo. 1. // Load the XML file. Next. 0).Redraw = True End Sub  C# private void button1_Click(System.xml".object sender. c1FlexGrid1. The routine then sets the grid's Redraw property to False to suspend repainting while the control is populated.Filter = "XML Files (*.XmlDocument xdoc = new System.OK ) return.Redraw = false. and is listed below. c1FlexGrid1. the routine loads it into an XmlDocument object. c1FlexGrid1. the routine clears any data by setting Count to 1.EventArgs e) { // Get the file name.ChildNodes[1]. } Observe the following: The routine starts by showing an OpenFileDialog that allows the user to select an XML file to load into the grid. 1.XmlDocument(). and calls the GetXMLData routine to populate the control with the contents of the XmlDocument. and 2. C1FlexGrid1. The GetXMLData routine is the most interesting one in this tutorial. OpenFileDialog fo = new OpenFileDialog().Load(fo. fo.Rows. C1FlexGrid1. // Stop redrawing to improve speed. GetXMLData(xdoc.xml)|*. After the grid has been populated.Xml.DefaultExt = "xml". fo.Tree. // Show levels 0. Count C1FlexGrid1. If node.NodeType == System.Node.ChildNodes.Count == 1 ) 132 .Styles("Data")) End If ' If the node has a "Name" subnode.Level = level ' Recurse to get children.InnerText C1FlexGrid1. If node. C1FlexGrid1(row.Xml.ChildNodes. C1FlexGrid1. c1FlexGrid1.Name If node.Xml. Dim row As Integer = C1FlexGrid1.Comment Then Exit Sub End If ' Add a new row for this node.ChildNodes. level + 1) Next End If End Sub  C# private void GetXMLData(System.SelectSingleNode("Name") If Not (ndName Is Nothing) Then C1FlexGrid1. int row = c1FlexGrid1.InnerText End If End If ' If this node has children.Add().UserData = ndName. save it to use as a ToolTip.Count > 1 Then ' Make this row a node. if ( node. // Add data to the new row.XmlNode node.Count = 1 Then C1FlexGrid1(row.XmlNodeType.ChildNodes GetXMLData(child.Xml.Rows.ChildNodes.Rows(row).XmlNodeType.Private Sub GetXMLData(ByVal node As System.Rows(row). 1) = node. c1FlexGrid1[row. 1.Count.Count > 0 Then Dim ndName As System.Add() ' Add data to the new row. int level) { // Skip the comment nodes.SetCellStyle(row.Xml. 0) = node.Xml.Rows. Dim child As System. } // Add a new row for this node. 0] = node.Rows(row). get them as well.Rows. if ( node.XmlNode For Each child In node.NodeType = System.Rows.IsNode = True C1FlexGrid1. ByVal level As Integer) ' Skip the comment nodes.Xml.XmlNode. If node. C1FlexGrid1.XmlNode = node.Comment ) { return.Name. Xml. } } // If this node has children.Count > 0) { System. foreach (System.Rows[row].XmlNode ndName = node.SetCellStyle(row. then the contents of the "Name" node are assigned to the new row's UserData property. The next block of code checks to see whether this node has a subnode called "Name". c1FlexGrid1.Xml.Styles["Data"]).SelectSingleNode("Name"). if (ndName != null) { c1FlexGrid1. and the node's InnerText property is copied to the second column on the new row.ChildNodes. 1] = node. } // If the node has a "Name" subnode. if ( node. Then it uses the Rows. get them as well. // Recurse to get children. if the node has children. In this case. Next.Rows[row]. c1FlexGrid1. The code also sets the style of cells containing data to the custom style "Data" created when the form was loaded.{ c1FlexGrid1[row.Level = level. c1FlexGrid1.Node.Count > 1 ) { // Make this row a node. c1FlexGrid1. if (node. the node is interpreted as a data node. so users can see the node name even when it is collapsed.ChildNodes) GetXMLData(child. Run the program and observe the following: The project can load XML files and display them. save it to use as a ToolTip.ChildNodes. 133 .InnerText. and the user can collapse and expand nodes by clicking on them. the routine sets the node name and checks whether the node has exactly one child.IsNode = true.UserData = ndName.Add method to add a new row to the grid. If it does. This value will be used later to implement ToolTips.InnerText. Finally. the GetXMLData routine calls itself to add the child nodes to the grid as well.XmlNode child in node. 1. } } Observe the following: The routine starts by skipping XML comment nodes.Rows[row]. level + 1). Node. Every time a branch is expanded or collapsed.Rows(C1FlexGrid1.DoubleClick If C1FlexGrid1. no work is done.Row) If Not r.Collapsed End Sub 134 .Collapsed = Not r. but you may extend and customize its behavior.MouseCol = 0 Then ToggleNodeState() End If End Sub Private Sub C1FlexGrid1_KeyPress(ByVal sender As Object.IsNode Then Exit Sub ' Toggle the collapsed state. Dim r As Row = C1FlexGrid1. ByVal e As KeyPressEventArgs) Handles C1FlexGrid1.KeyChar = vbCr Then ToggleNodeState() End If End Sub Private Sub ToggleNodeState() ' If the current row is not a node. In this tutorial. the control fires the BeforeCollapse and AfterCollapse events so you may take actions in response to that. Step 3 of 5: Add Custom Mouse and Keyboard Handling The C1FlexGrid provides the expanding and collapsing for you. Furthermore. we will trap the DoubleClick and KeyPress events to expand and collapse nodes when the user double clicks or presses the ENTER key. Add the following DoubleClick and KeyPress events to the form:  Visual Basic Private Sub C1FlexGrid1_DoubleClick(ByVal sender As Object. you may use the Collapsed property to get and set the collapsed state of each branch in code.KeyPress If e.Node. ByVal e As EventArgs) Handles C1FlexGrid1.The next steps add a few improvements to make the application easier to use. r. Rows(C1FlexGrid1. if (! r. ToggleNodeState checks whether the current row is a node row.Rows[c1FlexGrid1. C# private void c1FlexGrid1_DoubleClick( object sender. // Toggle the collapsed state. KeyPressEventArgs e) { if ( e.IsNode Then e.Collapsed.IsNode ) e.Row].IsNode ) return. don't edit it. don't edit it. } Run the program and observe the following: The event handlers check whether the user double-clicked the first column or hit the ENTER key. EventArgs e) { if ( c1FlexGrid1. and toggles the value of the Collapsed property if it is.Cancel = true. r. To do this. We would also like to prevent users from entering data in the second column of node rows. } } private void ToggleNodeState() { // If the current row is not a node. Step 4 of 5: Allow/Prevent Editing Recall that we set the AllowEditing property of the first column to False.Rows[c1FlexGrid1. then call the ToggleNodeState routine. } 135 .Cancel = True End Sub  C# private void c1FlexGrid1_BeforeEdit( object sender.KeyChar == 13 ) { ToggleNodeState(). RowColEventArgs e) { // If the current row is a node. This prevents users from editing any cells in the first column. ByVal e As RowColEventArgs) Handles C1FlexGrid1.Row) If r.MouseCol == 0 ) { ToggleNodeState().Row].Node. Dim r As Row = C1FlexGrid1. add the following code to handle the BeforeEdit event:  Visual Basic Private Sub C1FlexGrid1_BeforeEdit(ByVal sender As Object. if (r. no work is done.BeforeEdit ' If the current row is a node. Row r = c1FlexGrid1.Collapsed = !r. Row r = c1FlexGrid1.Node. } } private void c1FlexGrid1_KeyPress( object sender. Otherwise.UserData ' Set it if it is different from the current ToolTip. the ToolTip text is set to Nothing.UserData.SetToolTip(C1FlexGrid1. ByVal e As MouseEventArgs) Handles C1FlexGrid1.MouseRow]. If the mouse is over the first column on a row that contains text for the ToolTip. we will add ToolTips to the outline. MouseEventArgs e) { // Check the ToolTip for this cell.Step 5 of 5: Implement ToolTips To conclude this tutorial.Rows[c1FlexGrid1. tip) End If End If End Sub  C# private void c1FlexGrid1_MouseMove( object sender. The ToolTips will display the text that was stored in each row's UserData property by the GetXMLData routine described above.MouseRow).MouseCol = 0 And C1FlexGrid1. The ToolTips will show the contents of the "Name" node when the user moves the mouse over its parent node.GetToolTip(c1FlexGrid1) ) { toolTip1.SetToolTip(c1FlexGrid1. string tip. 1.MouseRow > 0 Then tip = C1FlexGrid1.MouseCol == 0 && c1FlexGrid1.Rows(C1FlexGrid1.MouseRow > 0 ) { tip = (string)c1FlexGrid1. if ( tip != toolTip1.GetToolTip(C1FlexGrid1) Then ToolTip1. This is useful when the parent node is collapsed and the "Name" node is not visible. 2. } } } Run the program and observe the following: The code starts by checking the cell under the mouse using the MouseRow and MouseCol properties. Dim tip As String If C1FlexGrid1. If tip <> ToolTip1. it retrieves the text. Add the following code to handle the grid's MouseMove event:  Visual Basic Private Sub C1FlexGrid1_MouseMove(ByVal sender As Object. // Set it if it is different from the current ToolTip. tip). Add a ToolTip control to the form. 136 .MouseMove ' Check the ToolTip for this cell. if ( c1FlexGrid1. Then the routine compares the new and current ToolTip text. and updates the text if necessary. adding. by calling the SetToolTip method on the ToolTip control. then adds the following features:      Dynamic layout (column order) Automatic sorting Cell merging Automatic subtotals Outlining The picture below shows what the final application looks like. The user can drag the first three columns to group the data by salesperson. including saving edits back into the XML document. The application starts with a simple data-bound grid containing sales data (from the NorthWind database). and so on. When a column is dragged. You can extend this project in many ways. the totals are automatically recalculated and the outline tree is rebuilt. using different styles for different types of data. and product name. This concludes this tutorial. and moving nodes. Data Analysis Tutorial This tutorial combines some of the most useful features in the C1FlexGrid control to provide a dynamic view of a data table. deleting. country. 137 . add the following statements:  Visual Basic Imports System. and use the GetDataSource method to populate the grid.Data.Step 1 of 4: Create the C1FlexGrid Control for the Data Analysis Tutorial Start a new project and add a C1FlexGrid control to the form by clicking the C1FlexGrid icon on the toolbox.NET components and make sure it is checked. Step 2 of 4: Initialize and Populate the Grid To set up the grid and populate the grid with the sales data we want to analyze.ComponentModel Imports C1. Then. look for the C1FlexGrid control on the list of . using System. If you can't find the C1FlexGrid control in the Toolbox. right-click on the Toolbox and select Choose Items. This sets the grid's Dock property to Fill so the grid will fill the form.Win.ComponentModel.OleDb Imports System. 1. If you can't find the grid in the component list. Set up the grid layout and styles either in the designer or in code. then clicking on the form and dragging until the object has the proper size. 1. Double-click the form caption area to open the code window.C1FlexGrid. In the C1FlexGrid Tasks menu.Data. set the following properties: 138 .  This makes the objects defined in the C1FlexGrid and OleDb assemblies visible to the project and saves a lot of typing. using C1. In the Designer  In the Properties window.OleDb. click Dock in parent container. 2. At the top of the file. you may need to re-install the product.Win.C1FlexGrid C# using System. set the layout properties and styles either in the designer or in code. C1FlexGrid1.ExtendLastCol = True 139 .Property AllowEditing AllowSorting AllowMerging ExtendLastCol SelectionMode Tree. ByVal e As EventArgs) Handles MyBase.AllowEditing = False C1FlexGrid1.Load ' Set up the grid layout/behavior.SelectionMode = SelectionModeEnum.Cell C1FlexGrid1.Nodes C1FlexGrid1.Column Setting False None Nodes True Cell Simple 1  Open the C1FlexGrid Style Editor by selecting Styles from the C1FlexGrid Tasks menu.Style property to None and the Trimming property to EllipsisCharacter.AllowSorting = AllowSortingEnum.AllowMerging = AllowMergingEnum. Select Subtotal0 from the list of Built-In Styles. Set the Border.None C1FlexGrid1. Select Normal from the list of Built-In Styles. and the ForeColor property to Black.Object. Set the BackColor property to Gold. see Accessing the C1FlexGrid Style Editor (page 149). Set the properties for Subtotal1 and Subtotal2 to the following: Subtotal1 BackColor ForeColor Subtotal2 BackColor ForeColor LightGoldenrodYellow Black Khaki Black       Click OK to close the editor. In Code Add the following code to the Form_Load event to set up the grid layout and styles:  Visual Basic Private Sub Form1_Load(ByVal sender As System. For more information on accessing the C1FlexGrid Style Editor.Style Tree. None C1FlexGrid1.Black s.Black.Trimming = StringTrimming.Black s = C1FlexGrid1.Simple C1FlexGrid1.Simple.Width = C1FlexGrid1.Styles(CellStyleEnum.Normal.Black s = C1FlexGrid1. s = c1FlexGrid1. c1FlexGrid1.Gold s.Normal.ForeColor = Color.ForeColor = Color.Width = c1FlexGrid1.Black End Sub  C# private void Form1_Load( System.SelectionMode = SelectionModeEnum.Style = BorderStyleEnum.Style = BorderStyleEnum.Trimming = StringTrimming.Column = 1 ' Set up grid styles.Column = 1. CellStyle s = c1FlexGrid1.White s = C1FlexGrid1.LightGoldenrodYellow s.GrandTotal]. c1FlexGrid1.DefaultSize / 4 C1FlexGrid1.None.Black.ForeColor = Color.Styles. // Set up grid styles.ExtendLastCol = true.EllipsisCharacter Dim s As CellStyle = C1FlexGrid1.BackColor = Color.ForeColor = Color. s.BackColor = Color.Style = TreeStyleFlags.BackColor = Color.Subtotal0].Nodes.None.C1FlexGrid1.Styles[CellStyleEnum.AllowSorting = AllowSortingEnum. C1FlexGrid1.Styles[CellStyleEnum.Styles. s = c1FlexGrid1. EventArgs e) { // Set up the grid layout/behavior.ForeColor = Color. c1FlexGrid1.GrandTotal) s.White. s.Style = TreeStyleFlags.Tree. c1FlexGrid1.Border.Cols. c1FlexGrid1.Styles.Cols.LightGoldenrodYellow.ForeColor = Color.Tree.Subtotal2) s. s. s.Styles(CellStyleEnum.Tree. s. 2.Black.Normal.BackColor = Color. c1FlexGrid1.Cols(0). s = c1FlexGrid1.BackColor = Color.Subtotal1) s. s.Cols[0].Cell.Subtotal2].Subtotal1].BackColor = Color. Bind C1FlexGrid to a data source by adding the following code to the Form_Load event: 140 .Styles.BackColor = Color. c1FlexGrid1.Khaki s.Khaki. c1FlexGrid1.AllowEditing = false. s.Styles(CellStyleEnum.Border.Tree.ForeColor = Color.Styles(CellStyleEnum.BackColor = Color.Styles[CellStyleEnum. } The routine starts by setting up the grid layout and some styles.Gold. c1FlexGrid1.Styles[CellStyleEnum.Subtotal0) s.Normal. s.Black.DefaultSize / 4.ForeColor = Color.EllipsisCharacter.object sender.AllowMerging = AllowMergingEnum. c1FlexGrid1. DataSource = GetDataSource(). 3. Do not close the editor. listed below. Under Format type select Currency.  4. the Format property can also be set using the C1FlexGrid Column Editor: 141 . This is done to prevent the user from grouping the data in these columns (the values in these columns are distinct for each row). see Accessing the C1FlexGrid Column Editor (page 149). Visual Basic ' Bind C1FlexGrid to the data source.AllowDragging = False C# // Prevent the user from dragging c1FlexGrid1. c1FlexGrid1.Cols(6).Cols(5). Alternatively. For details on how to access the C1FlexGrid Column Editor. Lock the last three columns in place by setting their AllowDragging property to False. In the left pane.AllowDragging c1FlexGrid1. Set the AllowDragging property to False for Column 5 and Column 6. Uncheck the Allow Dragging check box.Cols[4]. This property can be set either in the designer or at in code. = false. This can be done either in the designer or in code. C1FlexGrid1. C1FlexGrid1.AllowDragging c1FlexGrid1. Set the Format property of the Sales Amount column so that the amounts are displayed as currency values. Open the C1FlexGrid Column Editor by selecting Designer in the C1FlexGrid Tasks menu.AllowDragging last three columns. Select Column 4 in the right pane. Click the ellipsis button in the Format String box to open the Format String dialog box. = false.Cols(4). Click OK to close the Format String dialog box.  The routine binds it to a data source created by the GetDataSource method.AllowDragging = False C1FlexGrid1.Cols[5].Cols[6]. the AllowDragging property can also be set using the C1FlexGrid Column Editor:     In Code Add the following code to the Form_Load event:  Visual Basic ' Prevent the user from dragging last three columns. Alternatively. = false.AllowDragging = False C1FlexGrid1. This will open the Column Tasks menu for Column 4. set the AllowDragging property to False.DataSource = GetDataSource() C# // Bind C1FlexGrid to the data source. In the Designer     Select Column 6 in the grid. Repeat for Column 5 and Column 6. In the Designer     Select Column 4 in the grid. Tables(0) End Function 142 .Orders. The GetDataSource method creates the data table that is displayed by the grid.OrderID = [Order Details].ProductID " & _ "ORDER BY Employees.EmployeeID) " & _ "INNER JOIN [Order Details] " & _ "ON Orders." & _ "Categories.[UnitPrice] AS [Sale Amount] " & _ "FROM (Categories INNER JOIN Products " & _ "ON Categories. Add the following code to the form.Cols(6). except for the SQL statement that retrieves the data. The routine is very basic.4.0.Format = "c" C# // Display currency values in the Sales Amount column.CategoryID = Products.ShipCountry." & _ "Categories.Products.mdb" ' Set up the SQL statement. but use visual designers such as the one in Visual Studio or Microsoft Access to do that." ' Retrieve the data into the DataSet. In Code  5.ProductName.Fill(ds) ' Return the data table. C1FlexGrid1. Dim conn As String = "Provider=Microsoft.Cols[6]. click the ellipsis button next to the Format property to open the Format String dialog box.LastName.ShipCountry.CategoryName.ProductID = [Order Details]. Under Format type select Currency. because it has a reference to the NorthWind database and that file might be in a different folder in your system:  Visual Basic Private Function GetDataSource() As DataTable ' Set up the connection string.Jet.OrderDate.Orders.OLEDB. Click OK to close the editor." & _ "Data Source=C:\Program Files\ComponentOne Studio.EmployeeID = Orders.      In the C1FlexGrid Column Editor.CategoryID) " & _ "INNER JOIN ((Employees INNER JOIN Orders " & _ "ON Employees.Orders. In the left pane. c1FlexGrid1.CategoryName.0\Common\Nwind. GetDataSource = ds. Dim da As OleDbDataAdapter = New OleDbDataAdapter(rs.OrderID) " & _ "ON Products. select Column 6 in the right pane.LastName. Dim rs As String = _ "SELECT Employees." & _ "[Quantity]*[Products].NET 2. Note that you may have to change the connection string slightly. conn) Dim ds As DataSet = New DataSet() da. Visual Basic ' Display currency values in the Sales Amount column. Click OK to close the Format String dialog box.Format = "c". Most people don't write these SQL statements manually. However. 143 .4.Orders.ShipCountry.[UnitPrice] AS [Sale Amount] " + "FROM (Categories INNER JOIN Products " + "ON Categories.".LastName. return ds.CategoryID = Products.OLEDB. the data is not structured in a clear way. // Retrieve the data into the DataSet.ProductName.ShipCountry.LastName.Products. OleDbDataAdapter da = new OleDbDataAdapter(rs. conn).NET 2.OrderDate.Jet.OrderID = [Order Details]. C# private DataTable GetDataSource() { // Set up the connection string. and this table contains a couple of thousand records.ProductID = [Order Details].Tables[0]. da.0.mdb"." + "[Quantity]*[Products].CategoryID) " + "INNER JOIN ((Employees INNER JOIN Orders " + "ON Employees. so it is pretty difficult to get an overview of what the data means.Fill(ds). // Set up the SQL statement." + "Categories.Orders.CategoryName.EmployeeID = Orders.CategoryName." + "Data Source=C:\\Program Files\\ComponentOne Studio.Orders.OrderID) " + "ON Products. } Run the program and observe the following: You will see a plain-looking grid that allows you to move columns around and browse through the data.EmployeeID) " + "INNER JOIN [Order Details] " + "ON Orders. DataSet ds = new DataSet().0\\Common\\Nwind.ProductID " + "ORDER BY Employees. // Return the data table. string conn = "Provider=Microsoft. string rs = "SELECT Employees." + "Categories. ' This will cause a data refresh. the C1FlexGrid control fires the AfterDragColumn event. Furthermore.DefaultView.Name + ". DragRowColEventArgs e) { // Sort the recordset when the user drags columns.Name & ".Cols(3). which rebuilds the subtotals. DataTable dt = (DataTable)c1FlexGrid1. " & _ C1FlexGrid1.Sort = sort. " + c1FlexGrid1.AfterDragColumn ' Sort the recordset when the user drags columns.Cols[3]. Dim sort As String = C1FlexGrid1.Name + ". ByVal e As DragRowColEventArgs) Handles C1FlexGrid1.Cols[1]. removing all subtotals and ' firing the AfterDataRefresh event. We will add an event handler to sort the data in the underlying data table. dt.DefaultView.DataSource. // This will cause a data refresh. 144 .Name & ".Cols(1). (If the grid were being used in unbound mode.) Add the following code to the form to sort the recordset and rebuild the subtotals when the user drags columns:  Visual Basic Private Sub C1FlexGrid1_AfterDragColumn(ByVal sender As Object.DataSource dt.Name Dim dt As DataTable = C1FlexGrid1.Cols[2].Step 3 of 4: Allow Automatic Sorting The first step in organizing the data is sorting it. After the user reorders the columns.Cols(2). " & _ C1FlexGrid1.Name. which rebuilds the subtotals. string sort = c1FlexGrid1.Sort = sort End Sub  C# private void c1FlexGrid1_AfterDragColumn( object sender. we would like the data to be sorted automatically whenever the user reorders the columns. we would accomplish this using the Sort method. " + c1FlexGrid1. removing all subtotals and // firing the AfterDataRefresh event. 3. C1FlexGrid1. totalOn.AutoSizeCols(1. Add the following AfterDataRefresh event handler to the form:  Visual Basic Private Sub C1FlexGrid1_AfterDataRefresh(ByVal sender As Object. 2. the data is automatically sorted. 1.AfterDataRefresh ' Total the Sale Amount. any changes to the data source cause the grid to fire the AfterDataRefresh event. 3. 0.Cols("Sale Amount").Subtotal(AggregateEnum. caption) C1FlexGrid1. we will add subtotals and an outline tree. In the next step. 2. caption) C1FlexGrid1. totalOn.Subtotal(AggregateEnum. This event is the ideal place to put the code that inserts the subtotals and builds the outline tree for the grid. ByVal e As ListChangedEventArgs) Handles C1FlexGrid1. 1.IgnoreHidden) 145 . AutoSizeFlags. Dim totalOn As Integer = C1FlexGrid1.Tree. 1.Sum.Show(2) ' Autosize the grid to accommodate the tree. Step 4 of 4: Include Subtotals and Outline Tree When the grid is used in bound mode.Sum.} Run the program and observe the following: Run the project and try reordering the first three columns by dragging their headings around. 30. which makes it easier to interpret.Subtotal(AggregateEnum. C1FlexGrid1. totalOn. Whenever you move a column.Sum. caption) ' Collapse the outline to level 2.SafeIndex Dim caption As String = "Total for {0}" ' Calculate three levels of totals. C1FlexGrid1. 1000. c1FlexGrid1. c1FlexGrid1. string caption = "Total for {0}". though. 0. ListChangedEventArgs e) { // Total the Sale Amount. The new rows are automatically configured as outline nodes (their IsNode property is set to True).IgnoreHidden). 30. 3. so the subtotals are collapsible. Looking up the index is usually better than hardwiring it. int totalOn = c1FlexGrid1.End Sub  C# private void c1FlexGrid1_AfterDataRefresh( object sender. // Autosize the grid to accommodate the tree. totalOn.Sum. 2. c1FlexGrid1.Tree. c1FlexGrid1.Show(2). 1000. because if someone added a couple of fields to the SQL statement the index would change. // Calculate three levels of totals. The code then calls the C1FlexGrid. 146 . // Collapse the outline to level 2. } Run the program and observe the following: The code starts by getting the index of the Sale Amount column. 1.Subtotal method to group the data and insert new rows with the subtotals. 2. caption).Subtotal(AggregateEnum. totalOn. caption).Sum. 3.Cols["Sale Amount"]. totalOn.AutoSizeCols(1.Subtotal(AggregateEnum.Subtotal(AggregateEnum. caption).SafeIndex. AutoSizeFlags. In this tutorial.Sum. c1FlexGrid1. 1. the index will always be the same (Column 6). 1. Try dragging columns around. changing some values in the Sale Amount column will cause the AfterDataRefresh event to fire again. and the totals will be automatically updated. Note also that the grid is editable. You can also expand tree nodes to drill down into the data if you want to see more detail. You can easily see the totals by country. product category. 147 . This concludes this tutorial. or salesperson. . NET Project (page 21). you will be able to create projects demonstrating a variety of C1FlexGrid features. Accessing the C1FlexGrid Editors The C1FlexGrid editors can be accessed through the C1FlexGrid Tasks menu. C1FlexGrid Tasks Menu Click the smart tag ( Styles. and know how to use bound and unbound controls in general. C1FlexGrid Tasks Menu Click the smart tag ( Designer. use the C1FlexGrid Style Editor. Context Menu Right-click on the form and select Styles from the context menu. Accessing the C1FlexGrid Column Editor To access the C1FlexGrid Column Editor. To modify existing styles and add custom styles. see C1FlexGrid Style Editor (page 33). ) in the upper right corner of C1FlexGrid to open the C1FlexGrid Tasks menu. use the C1FlexGrid Column Editor.NET. If you are a novice to the ComponentOne FlexGrid for WinForms product. Each topic provides a solution for specific tasks using the ComponentOne FlexGrid for WinForms product.NET project. the context menu. use the C1FlexGrid Tasks menu.FlexGrid for WinForms Task-Based Help The task-based help assumes that you are familiar with programming in Visual Studio . click the ellipsis button next to the Cols property. To reorder columns. Each task-based help topic also assumes that you have created a new . and select Accessing the C1FlexGrid Style Editor To access the C1FlexGrid Style Editor. Properties Window In the Properties window. or the Properties window. By following the steps outlined in the help. and columns. the context menu. Context Menu Right-click on the form and select Designer from the context menu. For additional information on this topic. and select 149 . the context menu. or the Properties window. the C1FlexGrid Column Editor and the C1FlexGrid Style Editor. use the C1FlexGrid Tasks menu. rows. There are two C1FlexGrid editors. and insert or remove columns. For more information on customizing cell appearance with the C1FlexGrid Style Editor. see Creating a . please see the FlexGrid for WinForms Tutorials (page 113) first. set column properties. which may later be assigned to cells. see C1FlexGrid Column Editor (page 31). or the Properties window. ) in the upper right corner of C1FlexGrid to open the C1FlexGrid Tasks menu. For more information on editing columns with the C1FlexGrid Column Editor. which allow you to control the layout and appearance of C1FlexGrid at design time. adjust column widths. TextAlignEnum.Normal.Width = 150. 1. Resize the cells to fit the image using the Height and Width properties.C1FlexGrid.Win. Image.SetCellImage(1.ImageAlign = C1. Visual Basic Me. 1.c1FlexGrid1.Normal. Visual Basic Me.Styles. click the ellipsis button next to the Styles property. "ComponentOne").C1FlexGrid1.FromFile(@"c:\c1logo.C1FlexGrid1.Height = 90 Me. 150 .c1FlexGrid1. Adding Pictures and Text to a Cell To add pictures and text to a cell.bmp")) C# this.TextAlign = C1.c1FlexGrid1.TextAlign = C1.ImageAlignEnum.Height = 90.C1FlexGrid. use the SetData and SetCellImage methods.C1FlexGrid1.C1FlexGrid1.C1FlexGrid1.Styles. "ComponentOne") C# this.Width = 150 C# this.SetData(1. Add the following code to the Form_Load event: 1. Set the alignment of the image to CenterTop and the text to CenterBottom:  Visual Basic Me.c1FlexGrid1.   3.CenterTop Me.Styles.CenterTop.ImageAlign = C1. Add the SetData method to add the text:   4. this.c1FlexGrid1.  This topic illustrates the following: Your grid will look like the following with an image and text in the same cell. Image.CenterBottom.  Visual Basic Me.bmp")).Properties Window In the Properties window.C1FlexGrid.TextAlignEnum. this.FromFile("c:\c1logo.Win.Cols[1].Cols(1).CenterBottom C# this.C1FlexGrid.SetCellImage(1. 1.  2.Styles.Normal.Win.Win.Rows(1).ImageAlignEnum.SetData(1.C1FlexGrid1.Rows[1]. Add the SetCellImage method to add the image.Normal.c1FlexGrid1. 1. this.C1FlexGrid.OwnerDrawCellEventArgs) Handles C1FlexGrid1. C1.C1FlexGrid. like in Microsoft Excel.C1FlexGrid1.Col == (this.Text = ((e.Win.Row >= this.Fixed And e. ByVal e As C1.DrawMode = C1.Row .c1FlexGrid1.Win. aligned left.Win.Fixed . 1.c1FlexGrid1.Cols.C1FlexGrid.C1FlexGrid1.c1FlexGrid1.OwnerDrawCell If e.1 Then Dim rowNumber As Integer = e.Win.Rows. and the alignment of the image to CenterBottom.C1FlexGrid1. } } Add the OwnerDrawCell event:   This topic illustrates the following: 151 . Add the following code to the Form_Load event to fire the OwnerDrawCell event:   2.Row .OwnerDraw C# this. Adding Row Numbers in a Fixed Column To add row numbers in a fixed column. Visual Basic Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object.Rows.DrawMode = C1.Fixed .DrawModeEnum.Rows.ToString().Cols. in a fixed column.Fixed) & (e.OwnerDraw.ToString() End If End Sub C# private void c1FlexGrid1_OwnerDrawCell(object sender. use the OwnerDrawCell event to draw the numbers.1))) { e.c1FlexGrid1.C1FlexGrid1.Col = Me.Note: To set the text on top of the picture. change the alignment of the text to CenterTop.Text = rowNumber.DrawModeEnum.OwnerDrawCellEventArgs e) { if ((e.Rows. Visual Basic Me.C1FlexGrid.Fixed + 1 e.Row >= Me.Fixed) + 1).Me. Click Add to create a new style. Create a new style called 3DText.Row numbers appear in the first column. see Accessing the C1FlexGrid Style Editor (page 149). set the TextEffect property to Raised for text with a shadow offset by one pixel to the right and below the text or Inset for text with a shadow offset by one pixel to the left and above the text. Do not exit the C1FlexGrid Style Editor. In the Designer     Open the C1FlexGrid Style Editor. Setting the TextEffect property to Flat gives text no effect. Adding Three-Dimensional Text to a Header Row To add three-dimensional text to the table's header row.c1FlexGrid1. Double-click CustomStyle1. rename it 3DText.Add("3DText") C# C1.  2.C1FlexGrid. Set the TextEffect property to Raised.C1FlexGrid.Win.Styles. For details on how to access the C1FlexGrid Style Editor. In the Designer Locate the TextEffect property in the right pane and set it to Raised. and press ENTER when finished.CellStyle tdt = this. and are left-aligned like in Microsoft Excel.Add("3Dtext").Win. which is fixed.CellStyle tdt = Me. In Code Add the following code to the Form_Load event:  Visual Basic Dim tdt As C1. 1. 152 .C1FlexGrid1.Styles. Setting the TextEffect property to Flat gives text no effect. Apply the style to the header row by adding the following code to the Form_Load event:   Visual Basic Me.C1FlexGrid1.C1FlexGrid.In Code Add the following code to the Form_Load event:   3.TextEffect = C1.TextEffectEnum.Win.C1FlexGrid. In the right column. Select Fixed under Built-In Styles.TextEffect = C1.TextEffectEnum.C1FlexGrid1.c1FlexGrid1. 153 .Style = this.Styles["3DText"].Raised. To add a header with three-dimensional text using styles.c1FlexGrid1. This property can be set either in the designer or in code.Styles("3DText") C# this. see Accessing the C1FlexGrid Style Editor (page 149).Style = Me. In the Designer 1. For details on how to access the C1FlexGrid Style Editor. locate the TextEffect property and set it to Raised. Open the C1FlexGrid Style Editor. Adding Three-Dimensional Text to a Header Row Using Built-In Styles The TextEffect property can be used to add a three-dimensional text effect to C1FlexGrid's built-in styles. Visual Basic tdt.Rows[0]. This topic illustrates the following: The table should have a header with raised text similar to the following image.Raised C# tdt. 3.Rows(0).Win. set the TextEffect property within a style to Raised for text with a shadow offset by one pixel to the right and below the text or Inset for text with a shadow offset by one pixel to the left and above the text. 2. c1FlexGrid1. UserData ToolTips for a Column To add ToolTips that display UserData for a column.C1FlexGrid1. In Code Click OK to close the editor. set the UserData property for the AtomicMass column:   Visual Basic Me.TextEffect = C1. Add the following code to the Form_Load event to set the TextEffect property in the Fixed style:  Visual Basic Me.  This topic illustrates the following: By setting the TextEffect property in the Fixed style. cell range. In the Form_Load event.Raised.C1FlexGrid. use C1FlexGrid's MouseMove event to get the UserData property and display it in a ToolTip control.C1FlexGrid.Win.4. use C1FlexGrid's MouseMove event to get the UserData property and display it in a ToolTip control. ToolTips can be set to a column.C1FlexGrid1. 1. cell style.Cols("AtomicMass").TextEffect = C1. 2.Raised C# this.UserData = "in atomic mass units (u)" C# 154 . only fixed cells in the table will have a raised threedimensional effect. See CellStyleEnum Enumeration for a list and descriptions of the built-in styles.Styles["Fixed"]. a row. The TextEffect property can also be set in the all of the built-in styles.Win.TextEffectEnum. Locate the ToolTip control in the Toolbox and add it to the form.TextEffectEnum.Styles("Fixed"). or a single cell. Adding ToolTips That Display UserData To add ToolTips that display UserData. c1FlexGrid1.Windows.UserData ToolTip1. use C1FlexGrid's MouseMove event to get the CellRange. Add the following MouseMove event:  Visual Basic Private Sub C1FlexGrid1_MouseMove(ByVal sender As Object. }  This topic illustrates the following: The ToolTip appears within the entire AtomicMass column. tip). 1.UserData. tip = (string)c1FlexGrid1.this.Cols["AtomicMass"].MouseMove Dim tip As String tip = C1FlexGrid1.Cols(C1FlexGrid1. Locate the ToolTip control in the Toolbox and add it to the form.Windows. 3.Forms.UserData property and display it in a ToolTip control.MouseCol).MouseEventArgs e) { string tip. tip) End Sub C# private void c1FlexGrid1_MouseMove(object sender.SetToolTip(c1FlexGrid1. UserData ToolTips for a Cell Range To add ToolTips that display UserData for a cell range.UserData = "in atomic mass units (u)". toolTip1. set the UserData property for a cell range that contains a group of non-metallic elements:  Visual Basic 155 .SetToolTip(C1FlexGrid1. ByVal e As System.Cols[c1FlexGrid1. System.MouseCol]. 2. In the Form_Load event.Forms.MouseEventArgs) Handles C1FlexGrid1. AliceBlue.BackColor = Color.AliceBlue ' Set the user data for the cell range. rng. ByVal e As System.SetToolTip(C1FlexGrid1. 3.Forms. 10. C1.StyleNew. rng.Windows. c1FlexGrid1.UserData = "Non-Metallic"  C# // Set the cell range that contains the non-metallic elements. 1. Add the following MouseMove event:  Visual Basic Private Sub C1FlexGrid1_MouseMove(ByVal sender As Object.MouseEventArgs e) { string tip. 1. 10. rng. toolTip1.c1FlexGrid1. // Set the background color to see the cell range more easily.Win.GetUserData(C1FlexGrid1.CellRange = Me.Windows. 10). tip) End Sub C# private void c1FlexGrid1_MouseMove(object sender.MouseRow.Win.CellRange rng = this.C1FlexGrid. tip = (string)this.MouseRow.Forms.MouseEventArgs) Handles C1FlexGrid1.GetCellRange(6.UserData = "Non-Metallic".SetToolTip(c1FlexGrid1.MouseCol).MouseMove Dim tip As String tip = Me.MouseCol) ToolTip1.GetCellRange(6.StyleNew.C1FlexGrid1. 10) ' Set the background color to see the cell range more easily. System. tip). rng. C1FlexGrid1. // Set the user data for the cell range.C1FlexGrid1. 156 .c1FlexGrid1. Dim rng As C1.' Set the cell range that contains the non-metallic elements. }  This topic illustrates the following: The ToolTip appears within the entire cell range.C1FlexGrid.BackColor = Color.GetUserData(c1FlexGrid1. Styles("RowColor")  C# // Create a CellStyle for columns.C1FlexGrid1.  Visual Basic ' Create a CellStyle for columns.UserData = "ColumnColor Style" ' Create a CellStyle for rows. rs.Style = Me.C1FlexGrid.Styles("ColumnColor") ' Assign the RowColor Style to a row.C1FlexGrid1. see the Setting the Background Color of Columns and Rows (page 199) topic. Me.UserData = "RowColor Style" ' Assign the ColumnColor Style to a column.Cols(2).Rows(8). For more information on how to create CellStyles. use C1FlexGrid's MouseMove event to get the CellStyle.UserData property and display it in a ToolTip control. Me. 1.Add("RowColor") rs. and assign the styles to a column and row in the grid.BackColor = Color. 2. 157 .Styles.C1FlexGrid1.CellStyle rs = Me.Styles.UserData ToolTips for a Cell Style To add ToolTips that display UserData for a cell style.PowderBlue ' Add UserData with the style name.BackColor = Color.C1FlexGrid1.Add("ColumnColor") cc. Dim rs As C1.C1FlexGrid.CellStyle cc.C1FlexGrid1. Dim cc As C1.Win. cc.Win. create a custom CellStyle for columns and a custom CellStyle for rows.CellStyle cc = Me. C1.Cornsilk ' Add UserData with the style name.C1FlexGrid1.C1FlexGrid.Win. Locate the ToolTip control in the Toolbox and add it to the form.Style = Me. In the Form_Load event. System.Win. cc.Add("RowColor").Windows. rs = this. cc.BackColor = Color.MouseRow <> C1FlexGrid1.MouseCol != c1FlexGrid1.c1FlexGrid1.Fixed . 158 .Windows.Style.C1FlexGrid. Add the following MouseMove event:  Visual Basic Private Sub C1FlexGrid1_MouseMove(ByVal sender As Object.1 & c1FlexGrid1.BackColor = Color.MouseMove Dim tip As String If C1FlexGrid1.Styles. // Assign the RowColor Style to a row.Cols[c1FlexGrid1. 3. toolTip1.Rows.Cols(C1FlexGrid1.Fixed . rs.Cols[2].cc = this. if (c1FlexGrid1.Cols. this.Style = this. tip).PowderBlue.MouseCol).UserData = "ColumnColor Style".1) { tip = (string)c1FlexGrid1.c1FlexGrid1.CellStyle rs.c1FlexGrid1.Styles["RowColor"].Fixed .c1FlexGrid1. C1.UserData ToolTip1.c1FlexGrid1.MouseCol].c1FlexGrid1. // Add UserData with the style name.Cornsilk.Fixed .MouseEventArgs e) { string tip.MouseRow != c1FlexGrid1. ByVal e As System.1 Then tip = C1FlexGrid1.Styles.UserData = "RowColor Style". // Add UserData with the style name.Cols.Styles["ColumnColor"]. rs. // Create a CellStyle for rows. } }  This topic illustrates the following: The ToolTip appears within the CellStyle.Style = this.SetToolTip(C1FlexGrid1. // Assign the ColumnColor Style to a column.UserData.SetToolTip(c1FlexGrid1.Style. tip) End If End Sub C# private void c1FlexGrid1_MouseMove(object sender. this.Forms.1 And C1FlexGrid1.MouseEventArgs) Handles C1FlexGrid1.Add("ColumnColor").Rows[8].Rows.Forms.MouseCol <> C1FlexGrid1. Windows.UserData.Rows(8).". Add the following MouseMove event:  Visual Basic Private Sub C1FlexGrid1_MouseMove(ByVal sender As Object.UserData ToolTips for a Row To add ToolTips that display UserData for a row.Forms.Rows[8]. set the UserData property for the row that contains Oxygen:  Visual Basic Me. 1. tip) End Sub C# private void c1FlexGrid1_MouseMove(object sender.c1FlexGrid1.MouseRow). tip = (string)c1FlexGrid1.MouseMove Dim tip As String tip = C1FlexGrid1.UserData ToolTip1.MouseRow].MouseEventArgs e) { string tip. }  This topic illustrates the following: The ToolTip appears across the entire row. System.Rows(C1FlexGrid1. In the Form_Load event.C1FlexGrid1. 159 . tip).SetToolTip(C1FlexGrid1. use C1FlexGrid's MouseMove event to get the UserData property and display it in a ToolTip control." C# this.Windows.MouseEventArgs) Handles C1FlexGrid1. 2.Forms.Rows[c1FlexGrid1. toolTip1.SetToolTip(c1FlexGrid1.UserData = "Oxygen makes up approximately 1/5 of the earth's atmosphere.UserData = "Oxygen makes up approximately 1/5 of the earth's atmosphere. Locate the ToolTip control in the Toolbox and add it to the form.  3. ByVal e As System. UserData ToolTips for a Single Cell To add ToolTips that display UserData for a single cell, use C1FlexGrid's MouseMove event to get the UserData and display it in a ToolTip control. 1. 2. Locate the ToolTip control in the Toolbox and add it to the form. Add the following SetUserData method to the Form_Load event:  Visual Basic Me.C1FlexGrid1.SetUserData(1, "Element", "Hydrogen is a highly flammable gas.") C# this.c1FlexGrid1.SetUserData(1, "Element", "Hydrogen is a highly flammable gas.");  3. Add the following MouseMove event:  Visual Basic Private Sub C1FlexGrid1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles C1FlexGrid1.MouseMove Dim tip As String tip = Me.C1FlexGrid1.GetUserData(C1FlexGrid1.MouseRow, C1FlexGrid1.MouseCol) ToolTip1.SetToolTip(C1FlexGrid1, tip) End Sub C# private void c1FlexGrid1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { string tip; tip = (string)this.c1FlexGrid1.GetUserData(c1FlexGrid1.MouseRow, c1FlexGrid1.MouseCol); toolTip1.SetToolTip(c1FlexGrid1, tip);  160 } This topic illustrates the following: When the mouse moves over the first row in the Element column, the information about Hydrogen appears. Applying a Gradient Background to a CellRange To apply a gradient background to a CellRange, use the OwnerDrawCell event to create custom cell painting. 1. Create a LinearGradient brush and a CellRange by adding the following code to the form class level:  Visual Basic Dim GradientStyleBrush As System.Drawing.Drawing2D.LinearGradientBrush Dim rng As C1.Win.C1FlexGrid.CellRange C# System.Drawing.Drawing2D.LinearGradientBrush GradientStyleBrush; C1.Win.C1FlexGrid.CellRange rng;  2. Set C1FlexGrid's DrawMode property to OwnerDraw by adding the following code to the Form_Load event:   Visual Basic Me.C1FlexGrid1.DrawMode = C1.Win.C1FlexGrid.DrawModeEnum.OwnerDraw C# this.c1FlexGrid1.DrawMode = C1.Win.C1FlexGrid.DrawModeEnum.OwnerDraw; 3. Set the CellRange using the GetCellRange method:   Visual Basic rng = Me.C1FlexGrid1.GetCellRange(2, 2, 4, 4) C# rng = this.c1FlexGrid1.GetCellRange(2, 2, 4, 4); 4. Set the LinearGradient brush colors and angle of the gradient: 161  Visual Basic GradientStyleBrush = New System.Drawing.Drawing2D.LinearGradientBrush(ClientRectangle, Color.Navy, Color.Transparent, 270) C# GradientStyleBrush = new System.Drawing.Drawing2D.LinearGradientBrush(ClientRectangle, Color.Navy, Color.Transparent, 270);  5. Add the OwnerDrawCell event to draw the gradient in the CellRange:  Visual Basic Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.OwnerDrawCellEventArgs) Handles C1FlexGrid1.OwnerDrawCell ' Draw cell background using gradient brush. If (e.Row >= rng.r1) And (e.Row <= rng.r2) Then If (e.Col >= rng.c1) And (e.Col <= rng.c2) Then ' Draw background. e.Graphics.FillRectangle(GradientStyleBrush, e.Bounds) ' Let the grid draw the content. e.DrawCell(C1.Win.C1FlexGrid.DrawCellFlags.Content) ' Finish drawing the cell. e.Handled = True End If End If End Sub  C# private void c1FlexGrid1_OwnerDrawCell(object sender, C1.Win.C1FlexGrid.OwnerDrawCellEventArgs e) { // Draw cell background using gradient brush. if ((e.Row >= rng.r1) & (e.Row <= rng.r2)) { if ((e.Col >= rng.c1) & (e.Col <= rng.c2)) { // Draw background. e.Graphics.FillRectangle(GradientStyleBrush, e.Bounds); // Let the grid draw the content. e.DrawCell(C1.Win.C1FlexGrid.DrawCellFlags.Content); // Finish drawing the cell. e.Handled = true; } } } This topic illustrates the following: The Transparent to Navy gradient background appears only in the CellRange. 162 Changing the Column Order in the Grid To change the column order in the grid, drag the column to the new position in the grid or use the C1FlexGrid Column Editor, or set the MoveRange method in code. In the Designer 1. 2. In the grid, select the column you would like to move. In this example, the Element column will be moved. Click and drag the column to the left. A vertical dotted line appears where the column can be dropped. 3. Drop the Element column before the AtomicNumber column. 163 Click the Designer link. Click and drag the column to the left. 4. Select the Enable Column Filtering check box. Click the drop-down arrow next to the AllowFiltering property and select ByValue. 164 . 2. In the designer. 4. For details on how to access the C1FlexGrid Column Editor. columns can be reordered in the grid using the C1FlexGrid Column Editor: 1.Cols. A vertical dotted line appears where the column can be dropped. the Element column will be moved. In Code Add the following code to the Form_Load event to move Column 2 (the Element column in this example) to the Column 1 position:   Visual Basic Me. see Accessing the C1FlexGrid Column Editor (page 149).Cols. 1. 1. This topic illustrates the following: The Element column now appears before the AtomicNumber column in the grid. Open the C1FlexGrid Column Editor.MoveRange(2. The C1FlexGrid Column Editor appears.C1FlexGrid1. 2. Filtering by Value To use the ValueFilter. 1) C# this. 5.c1FlexGrid1. In this example.Alternatively. Click OK to close the editor. 3. 1). Drop the Element column before the AtomicNumber column.MoveRange(2. select the column you would like to move. 3. Select the grid and click the smart tag to open the C1FlexGrid Tasks menu. follow these steps: 1. 4. the second column is sorted by value: Filtering by Condition To use the ConditionFilter. Click the Designer link.c1FlexGrid1. this.ByValue C# this.AllowFiltering = True Me.  This topic illustrates the following: 165 .Cols[1].ByValue  This topic illustrates the following: In this example.C1FlexGrid1.Cols[1].AllowFiltering = true. Select the Enable Column Filtering check box.AllowFiltering = AllowFiltering. In Code Add the following code to the Form_Load event:  Visual Basic Me. 2.C1FlexGrid1.ByCondition Select the grid and click the smart tag to open the C1FlexGrid Tasks menu.AllowFiltering = AllowFiltering.AllowFiltering = AllowFiltering. Click the drop-down arrow next to the AllowFiltering property and select ByCondition.AllowFiltering = True Me.c1FlexGrid1.AllowFiltering = true. 3.C1FlexGrid1. The C1FlexGrid Column Editor appears.c1FlexGrid1.C1FlexGrid1.Cols(1). this.AllowFiltering = AllowFiltering.In Code Add the following code to the Form_Load event:  Visual Basic Me.c1FlexGrid1. follow these steps: 1.ByCondition C# this.Cols(1). AllowFiltering = true.C1FlexGrid1.c1FlexGrid1. this.Localization.Language. 166 . Right-click your grid and select Properties to view the Visual Studio Properties window.Language = C1.Language = C1.In this example.Util. you can use the Language property. 4. The language of the column filter editor matches the language specified in the Language property.Language. 1.C1FlexGrid1. 3. 2. Set the AllowFiltering property to True.Util. Run the project and click the drop-down arrow on one of the column headers to open the column filter editor. Click the drop-down arrow next to the Language property and select a language.Danish C# this.  This topic illustrates the following: Notice the language of the column filter editor matches the language specified in the Language property.Localization.AllowFiltering = True Me.c1FlexGrid1.Danish. In Code Add the following code to the Form_Load event:  Visual Basic Me. the second column is sorted by condition: Changing the Filter Language To change the language used in the column filter editor. C1FlexGrid1. see FlexGrid for WinForms Tutorials (page 113) and Outlining and Summarizing Data (page 73).c1FlexGrid1.Count = Me.Fixed.Rows. the tree view disappears. This code will set the editable row count equal to zero. set the editable row count to zero.Rows. Add the following code for the Button1_Click event.c1FlexGrid1.   Visual Basic Me. and the tree will be cleared when the Clear button is clicked.Clearing a Tree View To clear a tree view in C1FlexGrid. This topic illustrates the following: Once the button is clicked.Rows.C1FlexGrid1.Rows. For additional information on creating trees. 167 .Fixed C# this.Count = this. styles or UserData has been cleared. The following image shows the grid before any content. or all three. Clearing Content To clear the contents of C1FlexGrid. In this example. 168 . the code was added to the Click event of the Clear Contents button. use the Clear method.Clearing C1FlexGrid To clear C1FlexGrid. UserData. add the following Clear method. The Clear method clears either the content. styles. ClearFlags. This topic illustrates the following: Clicking Clear Styles clears only the style formatting.Win.ClearFlags.Clear(C1.C1FlexGrid1. the code was added to the Click event of the Clear Styles button.Style).Clear(C1.Clear(C1.C1FlexGrid. Clearing Styles To clear the style formatting of C1FlexGrid.Win.C1FlexGrid.ClearFlags.ClearFlags. add the following Clear method.Content). not the contents or UserData of the grid.Style) C# this.  Visual Basic Me.C1FlexGrid.Win.Clear(C1. This topic illustrates the following: Clicking Clear Content clears only the contents. In this example.Content) C# this. 169 .   Visual Basic Me.C1FlexGrid.c1FlexGrid1.c1FlexGrid1. not the styles or UserData of the grid.C1FlexGrid1.Win. style formatting.All) C# this.UserData) C# this.C1FlexGrid. In this example.   Visual Basic Me. add the following Clear method.All). Clearing Content.C1FlexGrid.C1FlexGrid.c1FlexGrid1.c1FlexGrid1.Win.ClearFlags. This topic illustrates the following: Clicking Clear All clears the contents.ClearFlags.C1FlexGrid1. and UserData of the grid.Clearing UserData To clear the UserData of C1FlexGrid. leaving a blank grid. In this example.Win.C1FlexGrid1.Clear(C1. the code was added to the Click event of the Clear UserData button. and UserData To clear the contents. style formatting.ClearFlags. Note that there will be no visible change to the grid when clearing UserData.Win.C1FlexGrid.Win. the code was added to the Click event of the Clear All button.ClearFlags.   Visual Basic Me. and UserData of C1FlexGrid.Clear(C1. since UserData only stores data that is useful to the application. 170 . Styles.Clear(C1.UserData). add the following Clear method.Clear(C1. Converting Column Letters to Uppercase To convert column letters from lowercase to uppercase, add the following SetupEditor event to your form:  Visual Basic Private Sub C1FlexGrid1_SetupEditor(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.RowColEventArgs) Handles C1FlexGrid1.SetupEditor If Me.C1FlexGrid1.Cols(e.Col).Name = "UCASECOL" Then Dim tb As TextBox = Me.C1FlexGrid1.Editor tb.CharacterCasing = CharacterCasing.Upper End If End Sub C# private void c1FlexGrid1_SetupEditor(object sender, C1.Win.C1FlexGrid.RowColEventArgs e) { if (this.c1FlexGrid1.Cols[e.Col].Name == "UCASECOL") { TextBox tb = this.c1FlexGrid1.Editor as TextBox; tb.CharacterCasing = CharacterCasing.Upper; } }  Customizing Appearance Using Visual Styles To customize the appearance of C1FlexGrid using Visual Styles, set the VisualStyle property to Custom, Office2007Black, Office2007Blue, Office2007Silver, Office2010Blue, Office2010Black, Office2010Silver, or System. This property can be set either in the designer or in code. The following table describes each of the Visual Styles: Visual Style Custom Description Do not use any visual styles. Render the control using the 171 styles and properties only. Office2007Black Office2007Blue Office2007Silver System Office2010Black Office2010Silver Office2010Blue Do not use any visual styles. Render the control using the styles and properties only. Do not use any visual styles. Render the control using the styles and properties only. Render the control with an appearance based on the Office 2007 Silver color scheme. Render the control with an appearance based on the current system settings. Render the control with an appearance based on the current system settings. Render the control with an appearance based on the Office 2010 Silver color scheme. Render the control with an appearance based on the Office 2010 Blue color scheme. In the Designer Locate the VisualStyle property in the Properties window and set it to Custom, Office2007Black, Office2007Blue, Office2007Silver, Office2010Blue, Office2010Black, Office2010Silver, or System. In this example, the VisualStyle property is set to Office2007Blue. In Code Add code to the Form_Load event to set the VisualStyle property to Custom, Office2007Black, Office2007Blue, Office2007Silver, Office2010Blue, Office2010Black, Office2010Silver, or System. The following code sets the VisualStyle property to Office2007Blue:   Visual Basic Me.C1FlexGrid1.VisualStyle = C1.Win.C1FlexGrid.VisualStyle.Office2007Blue C# this.c1FlexGrid1.VisualStyle = C1.Win.C1FlexGrid.VisualStyle.Office2007Blue; Custom Visual Style No visual style is applied: Office2007Black Visual Style The Office 2007 Black color scheme: 172 Office2007Blue Visual Style The Office 2007 Blue color scheme: Office2007Silver Visual Style The Office 2007 Silver color scheme. Office2010Blue Visual Style The Office 2010 Blue color scheme: Office2010Silver Visual Style The Office 2010 Silver color scheme: 173 Office2010Black Visual Style The Office 2010 Black color scheme: System Visual Style The current system settings: Entering Only Numbers in a Cell To allow entering only numbers in a cell, use the KeyPressEdit event and set the e.Handled parameter to True for the invalid keys. Use the following code to set the fourth column to accept only numbers, BACKSPACE, DELETE, and the PERIOD keys:  Visual Basic Private Sub C1FlexGrid1_KeyPressEdit(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.KeyPressEditEventArgs) Handles C1FlexGrid1.KeyPressEdit If e.Col = 3 Then ' If not the characters 0-9, PERIOD, DELETE, or BACKSPACE. If Not (e.KeyChar = Chr(48) Or e.KeyChar = Chr(49) Or _ e.KeyChar = Chr(50) Or e.KeyChar = Chr(51) Or _ e.KeyChar = Chr(52) Or e.KeyChar = Chr(53) Or _ e.KeyChar = Chr(54) Or e.KeyChar = Chr(55) Or _ e.KeyChar = Chr(56) Or e.KeyChar = Chr(57) Or _ e.KeyChar = Chr(46) Or e.KeyChar = Chr(127) Or _ 174 or BACKSPACE. For example.KeyChar == 127) || (e. e.Win. } } Formatting Cells Formatting cells allows you to control the accessibility and appearance of data in a single cell or multiple cells.KeyChar == 48) || (e. ByVal e As C1.KeyPressEditEventArgs e) { if( e.Cancel = True End If End Sub C# private void c1FlexGrid1_BeforeEdit(object sender.e.C1FlexGrid. PERIOD. DELETE.KeyChar == 54) || (e.KeyChar == 46) || (e.KeyChar == 52) || (e. C1.KeyChar == 51) || (e.KeyChar == 50) || (e. The following topics show you how to set cells to be read-only.Handled = True End If End If End Sub  C# private void c1FlexGrid1_KeyPressEdit(object sender.KeyChar == 49) || (e. format a cell to display currency values. row 1 read-only:  Visual Basic Private Sub C1FlexGrid1_BeforeEdit(ByVal sender As Object.Row == 1 & e.C1FlexGrid.KeyChar = Chr(8)) Then ' Stop the character from being entered into the ' control since it is an invalid key. if( !((e.Win.KeyChar == 57) || (e.Col == 1) { e. use the BeforeEdit event.RowColEventArgs) Handles C1FlexGrid1. Formatting a Cell as Read-Only To make a single cell or multiple cells read-only. C1. enter the following code to make the cell in column 1. e.C1FlexGrid.BeforeEdit If e. and format cells based on their contents.Row = 1 And e.Win. }  175 .KeyChar == 53) || (e.Handled = true.Col = 1 Then e.KeyChar == 56) || (e.Col == 3 ) { // If not the characters 0-9.Cancel = true.RowColEventArgs e) { if (e.KeyChar == 55) || (e.KeyChar == 8))) // Stop the character from being entered into the // control since it is an invalid key. Single Cell Read-Only You can make any cell in the grid read-only so that the data within it cannot be changed. While the orders and addresses may change.RowColEventArgs e) { for (int i = 1. Enter the following code:  Visual Basic Private Sub C1FlexGrid1_BeforeEdit(ByVal sender As Object.RowColEventArgs) Handles C1FlexGrid1.C1FlexGrid. set the Format property either in the designer or in code. and orders.Win. In this example.Col = 1 And e.Row = i Then e. addresses.Row == i) { e. The code below assumes you have nine rows in your grid.Win. i++) { if (e. Formatting a Cell with Decimal Content To format a cell that contains decimal numbers. numbers already entered in the first column will be formatted to a decimal amount. In the Designer 176 . Suppose you have an editable grid used to enter customers' information.Cancel = true. the customer IDs will not.BeforeEdit Dim i As Integer For i = 1 To 9 If e.Cancel = True End If Next End Sub C# private void c1FlexGrid1_BeforeEdit(object sender.} Multiple Cell Read-Only You may also want to set multiple cells in the grid to read-only at one time. ByVal e As C1. i <= 9. read-only.C1FlexGrid. C1. the Customer ID column.Col == 1 & e. such as customer IDs. and you would like to make all of the rows in the first column. } } }  This topic illustrates the following: Notice that none of the cells in the Customer ID column are editable. Note: The format specifier follows the standard . 3. This will open the Column Tasks menu for Column 1. This topic illustrates the following: In this example.NET conventions.##0. Click OK to close the editor. For details on how to access the C1FlexGrid Column Editor.Cols[1]. Create a new CellStyle called LargeValue and set the BackColor property to Gold. 1.00". In Code Select Column 1 in the grid. 1. 4. see Accessing the C1FlexGrid Column Editor (page 149).00" C# this. regardless of locale. In the Designer 177 .' for thousand separators and '. create a new style and use the CellChanged event. Open the C1FlexGrid Column Editor. 3.00 in the left pane.Format = "$#. Alternatively.##0. 2.C1FlexGrid1.00.Format = "$#. Click OK to close the Format String dialog box. Formatting Cells Based on the Contents To conditionally format cells based on the contents. Use '.##0.c1FlexGrid1.' for the decimal. 2. the Format property can also be set using the C1FlexGrid Column Editor: Add the following code to the Form_Load event:   Visual Basic Me. the numbers in the first column are converted to a dollar amount.Cols(1). Click the ellipsis button in the Format String box to open the Format String dialog box. Under Format type select Custom and set the Custom format to $#.1.##0. Select Column 1 from the right pane and set the Format property to $#. C1FlexGrid1.Row.c1FlexGrid1.000 as LargeValues.  2.Win.Gold C# // Create a custom style for large values. ' Reset others by setting their Style to Nothing. private void c1FlexGrid1_CellChanged(object sender.Italic) cs.SetCellStyle(e.        Open the C1FlexGrid Style Editor. Dim cs As C1. cs = this. ByVal e As C1.BackColor = Color.Styles. // Reset others by setting their Style to Nothing. if (Val(this.Win.RowColEventArgs e) { // Mark currency values > 50.Gold. Visual Basic ' Format cells based on their content.Italic).C1FlexGrid. C1. see Accessing the C1FlexGrid Style Editor (page 149). Double-click CustomStyle1. Use the CellChanged event to format the cells based on the contents:  178 .C1FlexGrid.CellStyle cs. Click OK to close the Font dialog box. e.RowColEventArgs) Handles C1FlexGrid1. C1.Add("LargeValue"). Click OK to close the C1FlexGrid Style Editor.Add("LargeValue") cs.C1FlexGrid1.Col)) >= 50000 Then cs = Me. e. cs) End Sub  C# // Format cells based on their content.CellStyle cs = Me.C1FlexGrid1. e.Font = New Font(Font.c1FlexGrid1(e.C1FlexGrid.Row.Styles.Row.C1FlexGrid1(e.C1FlexGrid.000 as LargeValues.Win.C1FlexGridCellStyle If Val(Me.c1FlexGrid1.Win. FontStyle. cs.Col.C1FlexGrid.Styles("LargeValue") End If Me.Styles("LargeValue"). Click Add to create a new style. cs.CellStyle cs. Private Sub C1FlexGrid1_CellChanged(ByVal sender As Object. Set the Font style box to Italic.Win.Col)) >= 50000) { cs = this. rename it LargeValue.CellChanged ' Mark currency values > 50. Locate the Font property and click the ellipsis button next to it to open the Font dialog box. C1. Locate the BackColor property in the right pane and set it to Gold. and press ENTER when finished. Dim cs As C1. FontStyle. In Code Add the following code to the Form_Load event:  Visual Basic ' Create a custom style for large values.BackColor = Color. For details on how to access the C1FlexGrid Style Editor.Font = new Font(Font.Win. Row.Col. A light sunken border.SetCellStyle(e. The following code sets the BorderStyle property to Fixed3D:  Visual Basic 179 . or XpThemes. In Code Add code to the Form_Load event to set the BorderStyle property to Fixed3D. A border drawn using XP themes. In the Designer Locate the BorderStyle property in the Properties window and set it to Fixed3D. set the ScrollableControl. or XpThemes. The following table describes each of the border styles. Light3D. This property can be set either in the designer or in code. None.} this. Light3D. cs).000 are highlighted in gold. No border. FixedSingle. FixedSingle. Formatting the Border Style of the Control To format the border style of the control. or XpThemes.BorderStyle property to Fixed3D. Formatting the Border Style Formatting the border style allows you to customize the appearance of the grid. cells containing values greater than or equal to 50. This is the default setting. None. In this example. The border style can be set for both the control and the grid. e.c1FlexGrid1. } This topic illustrates the following: In this example. A single line border. Border Fixed3D FixedSingle Light3D None XpThemes Description A three-dimensional border. FixedSingle. None. Light3D. the BorderStyle property is set to Fixed3D. C1FlexGrid.C1FlexGrid1.BorderStyle = C1. Three-Dimensional Border The border will be three-dimensional.BaseControls.Util.BorderStyleEnum.c1FlexGrid1.Util.Fixed3D.BaseControls.BorderStyleEnum.Win.Fixed3D  C# this.Win.BorderStyle = C1. Single Line Border The border will be a single line. 180 .Me.C1FlexGrid. No Border There is no border. 181 .Light Sunken Border The border will be light and three-dimensional. XP Theme Border The border will be XP themed. This property can be set using C1FlexGrid's built-in styles either in the designer or in code. Flat. None. Inset. or Raised. Formatting the Border Style of the Grid To format the border style of the grid. Fillet. Double. The following table describes each of the border styles. set the Style property to Dotted. Groove. 182 . Groove. In this example. 2. Fillet border.  Visual Basic Me.Border.Border Dotted Double Fillet Flat Groove Inset None Raised Description Dotted border. see Accessing the C1FlexGrid Style Editor (page 149). locate the Border property and expand it.Border. Click OK to close the editor. Inset. Select Normal under Built-In Styles. No border. 183 . the Style property is set to Dotted.  Dotted Border The cell border will be a dotted line. Open the C1FlexGrid Style Editor. For details on how to access the C1FlexGrid Style Editor. Groove. Double border. or Raised. None. Double. Fillet.Styles("Normal").Styles["Normal"]. Raised border.Win.Dotted C# this. Double. Inset.c1FlexGrid1.BorderStyleEnum.Dotted.C1FlexGrid.C1FlexGrid1. In Code Add code to the Form_Load event to set the Style property in the Normal style one of the following options: Dotted. 3. In the right column.Win. Flat. The following code sets the Style property to Dotted. Set the Style property to Dotted. Flat.BorderStyleEnum. Solid flat border. In the Designer 1. This is the default setting.Style = C1.C1FlexGrid. or Raised.Style = C1. Groove border. None. Inset border. Fillet. 184 .Double Border The cell border will be double lines. Fillet Border The cell border will be fillet. Groove Border The cell border will be grooved. 185 .Flat Border The cell border will be a solid flat line. Inset Border The cell border will be inset. 186 . No Border There is no cell border. to disable freezing. or Both to freeze both columns and rows. Conversely.Raised Border The cell border will be raised. Rows to freeze only rows. 187 . This property can be set either in the designer or in code. set the AllowFreezing property to None. Freezing Rows and Columns To allow the user to freeze rows and columns with the mouse. set the AllowFreezing property to Columns to freeze only columns. which is the default setting. Win.C1FlexGrid1.Both C# this. the row containing Hydrogen is frozen and will remain on the grid when it is scrolled to the bottom.C1FlexGrid.AllowFreezing = C1. 188 . click and drag the mouse over the rows or columns to freeze.C1FlexGrid.In the Designer Locate the AllowFreezing property in the Properties window and set it to Both.AllowFreezing = C1.AllowFreezingEnum.AllowFreezingEnum. In this example.Both.Win. In this example. This topic illustrates the following: When the mouse pointer becomes the lock rows or the lock columns icon.c1FlexGrid1. In Code Add the following code to the Form_Load event to set the AllowFreezing property to Both:   Visual Basic Me. the Element column is frozen and will remain on the grid when it is scrolled to the right. Any files with a "XLSX" or "ZIP" extensions are treated as Open XML files. but with an extension other than "XLSX". Loading and Saving Open XML Files You can load and save Microsoft Excel 2007 Open XML files within a C1FlexGrid control.Note: Setting the AllowFreezing property to Both allows both rows and columns to be frozen at the same time. standards-based format introduced by Microsoft in Office 2007. 189 . Open XML files are usually much smaller than traditional document files (such as XLS files). By default. your application may use the Open XML format for its data files. respectively. Open XML is an open. as seen in the following image. complete the following steps: 6. and Load in the Text property for each. This allows you to take control over the file format and not rely on the file extension. To save and load a grid as an OpenXml file. You can specify the file type as "Excel" and use the OpenXml option of the FileFlags enumeration. Add three buttons to the form containing the C1FlexGrid control and enter Save. Because they are compressed. Clear. in the Visual Basic Properties window. the Load and Save methods in C1FlexGrid select the appropriate file format automatically based on the file extension. The LoadGrid and SaveGrid methods also have overloads that take the file type as a parameter. Open XML files contain a number of XML files compressed using Zip compression. For example. Click Me. ByVal e As System.Clear(ClearFlags. FileFormatEnum. EventArgs e) { this.OpenXml) 190 .xlsx".C1FlexGrid.Excel.Object. Enter the following code for the Button3_Click event to be used for the Load button:  Visual Basic Private Sub button3_Click(ByVal sender As System. } Note: You must have the Imports or using statement at the top of your form in order for this code to work correctly. EventArgs e) { this.Object. Button_1.SaveGrid(@"C:\test\myfile. FileFlags.OpenXml).Click Me.SaveGrid("C:\test\myfile.Win. FileFlags.C1FlexGrid.EventArgs) Handles Button2. double-click the Save button.c1FlexGrid1.Clear(ClearFlags.Excel. and enter code in the Button1_Click event. If coding in C#. use using C1. From the Designer.C1FlexGrid1.Excel.LoadGrid("C:\test\myfile.All). ByVal e As System. If coding in Visual Basic. }  9.EventArgs) Handles Button3. FileFormatEnum.Click Me. Enter the following code for the Button2_Click event to be used for the Clear button:  Visual Basic Private Sub Button2_Click(ByVal sender As System.EventArgs) Handles Button1. use Imports C1.Win.xlsx". FileFormatEnum.OpenXml) End Sub C# private void button1_Click(object sender.xlsx". so it looks like the following:  Visual Basic Private Sub Button1_Click(ByVal sender As System.C1FlexGrid1. FileFlags.C1FlexGrid1.  8.7.All) End Sub C# private void button2_Click(object sender.Object..c1FlexGrid1. ByVal e As System. use the Data property. use the grid's indexer to populate a column. Enter content in the grid. Click the Load button. Click the Clear button to clear the grid.Fixed. Populating a Column with Data To populate a column with data when the form loads. Add the following code to the Form_Load event to set column one to zero:  Visual Basic Dim r As Integer For r = C1FlexGrid1. To populate a cell range.Count -1. FileFlags. and the grid you previously saved is loaded. The grid is saved as an Open XML file with an .End Sub  C# private void button3_Click(object sender. Click the Save button. r <= c1FlexGrid1.Rows.Excel. or a single cell. } Run the project: 1.OpenXml).c1FlexGrid1[r. You must create this folder if it does not already exist.LoadGrid(@"C:\test\myfile. set a loop with the grid's indexer to the data to fill the column.  191 . 1] = 0. EventArgs e) { this. 1) = 0 Next C# int r.Rows.xlsx". row.c1FlexGrid1. for (r = c1FlexGrid1. 4.r++) { this.xlsx extension to the "C:\test" folder.1 Me. 3.Fixed To C1FlexGrid1.Rows. 2. FileFormatEnum.C1FlexGrid1(r. as desired. Populating an Unbound Grid with Data To populate an unbound grid with data.Rows.Count . 1.Cols.1.Fixed. r) = 0 Next C# int r.Win.Cols.} This topic illustrates the following: Column one fills with zeros. third column. Add the following code to the Form_Load event to set the Data property to zero:  Visual Basic Dim rng As C1.r++) { this.C1FlexGrid1.Count .CellRange rng = this. for (r = c1FlexGrid1. 2] = "Cell Text". Populating a Row with Data To populate a row with data when the form loads. 3) rng.  This topic illustrates the following: The cell range fills with zeros.Data = 0.c1FlexGrid1[1.GetCellRange(1.C1FlexGrid1(1. Populating a Range of Cells with Data To populate a range of cells with data when the form loads.1 Me.CellRange = Me.Win.Fixed To C1FlexGrid1. }  This topic illustrates the following: Row one fills with zeros.C1FlexGrid1(3.Cols.GetCellRange(1. This topic illustrates the following: The text Cell Text is in the fourth row.C1FlexGrid.Data = 0 C# C1. Populating a Single Cell with Data To populate a single cell with data when the form loads. Add the following code to the Form_Load event to set the cell text:   Visual Basic Me.c1FlexGrid1.C1FlexGrid. set the grid's indexer to the data.3. 2) = "Cell Text" C# this. set the Data property of the CellRange. 3. 192 .Cols.Count -1.c1FlexGrid1[3.3). Add the following code to the Form_Load event to set column one to zero:  Visual Basic Dim r As Integer For r = C1FlexGrid1. set a loop with the grid's indexer to the data to fill the row. r] = 0. r <= c1FlexGrid1. rng. Alternatively.Cols["AtomicMass"]. 2. set the AllowEditing property to True. In this example. 3.AllowEditing = False ' Is the same as: Me.Cols("AtomicMass"). This will open the Column Tasks menu for that column. set the AllowEditing property to False either in the designer or in code.C1FlexGrid1. 2. 1.C1FlexGrid1.AllowEditing = false. the code will restrict editing in the 6th row:  Visual Basic Me. see Accessing the C1FlexGrid Column Editor (page 149). setting the AllowEditing property to False either in the designer or in code.c1FlexGrid1. Uncheck the Allow Editing check box.c1FlexGrid1. which is the default value. Open the C1FlexGrid Column Editor. the AllowEditing property can be set using the C1FlexGrid Column Editor:  Disable Editing for a Specific Row To disable editing for a specific row.C1FlexGrid1.AllowEditing = false.c1FlexGrid1. set the AllowEditing property to False. Conversely.AllowEditing = False C# this.AllowEditing = False C# this. In Code Add the following code to the Form_Load event to restrict editing the AtomicMass column:  Visual Basic Me. add the following code to the Form_Load event to set the AllowEditing property to False. Click OK to close the editor.C1FlexGrid1. to allow editing.Cols(4).Restricting Grid Editing To disable editing of the entire grid. For details on how to access the C1FlexGrid Column Editor. In the Designer 1. Select the column in the grid that you would like to edit. uncheck the Enable Editing check box. Disable Editing for a Specific Column To disable editing for a specific column.Rows(5). locate the AllowEditing property in the Properties window and set it to False. In Code Add the following code to the Form_Load event:   Visual Basic Me.AllowEditing = False 193 . specific column or specific row. In the Designer In the C1FlexGrid Tasks menu.AllowEditing = false. // Is the same as: this.Cols[4]. Disable Editing for the Entire Grid To disable editing for the entire grid. Alternatively. Select the column that you would like to edit from the right pane and set the AllowEditing property to False in the left pane. Rows[1].Rows.  2.Rows(2).c1FlexGrid1. Click OK to close the editor. this. Alternatively.c1FlexGrid1. Set the row height of the first two rows by adding the following code to the Form_Load event:  Visual Basic Me. // Is the same as: this. This will open the Column Tasks menu for that column.DefaultSize. Scale the images in the column. In Code Add the following code to the Form_Load event to restrict sorting the AtomicNumber column:  Visual Basic Me.c1FlexGrid1. set the AllowSorting property to False either in the designer or in code. Select the column in the grid that you would like to edit. Restricting Sorting for a Specific Column To restrict sorting for a specific column.DefaultSize C# this.c1FlexGrid1.C1FlexGrid1. Open the C1FlexGrid Column Editor.Cols(1).C1FlexGrid1. In the Designer    Open the C1FlexGrid Column Editor.Rows.Height = 2 * Me.Cols("AtomicNumber"). C# this. 3.C1FlexGrid1. For details on how to access the C1FlexGrid Column Editor.AllowEditing = false.Rows[5]. 2.Rows.c1FlexGrid1.Rows(1).Rows.Cols["AtomicNumber"].C1FlexGrid1.Height = 2 * this. Click OK to close the editor. Select the column that contains the images from the right pane and set the ImageAlign property to Scale in the left pane.AllowSorting = false. Select the column that you would like to edit from the right pane and set the AllowSorting property to False in the left pane. 1.AllowSorting = False ' Is the same as: Me. 194 . For details on how to access the C1FlexGrid Column Editor. set the ImageAlign property to Scale.C1FlexGrid1. In the Designer 1.C1FlexGrid1. see Accessing the C1FlexGrid Column Editor (page 149).Height = 2 * Me.Cols[1].AllowEditing = false. 2.c1FlexGrid1. Uncheck the Allow Sorting check box. 1.DefaultSize. the AllowSorting property can be set using the C1FlexGrid Column Editor:  Scaling an Image To scale an image in a single column when the rows of the grid are resized. see Accessing the C1FlexGrid Column Editor (page 149).Rows[2].Height = 2 * this.c1FlexGrid1.AllowEditing = False C# this.DefaultSize Me. c1FlexGrid1. Click OK to close the editor.C1FlexGrid.ImageAlignEnum.ImageAlignEnum.C1FlexGrid.Styles("Normal"). Open the C1FlexGrid Style Editor.Scale.ImageAlign = C1.Scale C# this.ImageAlign = C1.Win.  This topic illustrates the following: By using the ImageAlign property.ImageAlignEnum. the image will be scaled to fit the maximum area within the cell while preserving the picture's original aspect ratio.C1FlexGrid.C1FlexGrid.Scale C# this.ImageAlign = C1. 2.ImageAlign = C1.Win. not just one column.  195 .Win. In the right pane.In Code Add the following code after the code in step 1:  Visual Basic Me. Scaling Images in the Entire Grid To scale the images in the entire grid. see Accessing the C1FlexGrid Style Editor (page 149).Cols[3].ImageAlignEnum.Scale.Styles["Normal"]. In the Designer 1.c1FlexGrid1. 3. locate the ImageAlign property and set it to Scale. set the ImageAlign property for the Normal style to Scale.Win.C1FlexGrid1.C1FlexGrid1. Select Normal in the Built-In Styles list. 4.Cols(3). For details on how to access the C1FlexGrid Style Editor. In Code Add the following code to the Form_Load event:  Visual Basic Me. C1FlexGrid1.C1FlexGrid. to disable the search.Win.AutoSearch = C1.AutoSearch = C1. This topic illustrates the following: As the user types. tying C in the Element column highlights Carbon. Setting a Cell's Value to Zero When Users Press the Delete Key To set a cell's value to zero when a user presses the DELETE key.FromTop.c1FlexGrid1. In this example. use C1FlexGrid's KeyDown event to catch when the DELETE key is pressed. which is the default setting. For example.AutoSearchEnum. Conversely. This property can be set either in the designer or in code. set the AutoSearch property to FromCursor to begin the search from the current row or FromTop to begin the search from the first scrollable row.Win. Add the following KeyDown event to your form:  Visual Basic 196 . In the Designer Locate the AutoSearch property in the Properties window and set it to FromTop.AutoSearchEnum.Searching for Entries in a Column To search for entries in a column as a user types. typing He in the Element column will highlight Helium. set the AutoSearch property to None. Note: If more than one entry begins with the same letter.FromTop C# this. typing the next letter will highlight the entry with those letters. the search will highlight the cell containing that letter. In Code Add the following code to the Form_Load event to set the AutoSearch property to FromTop:   Visual Basic Me.C1FlexGrid. KeyCode = Keys.Col) = 0 End If End Sub  C# private void c1FlexGrid1_KeyDown(object sender.Count = 7.  197 . this.DataType = GetType(String) row(3).C1FlexGrid1.DataType = GetType(Integer)  2.C1FlexGrid1.Windows.Windows.C1FlexGrid1. 1.Caption = "Platform" row(4).Caption = "Phone" row(3). c1FlexGrid1. Set the Caption and DataType for each row.Caption = "Date" row(1).c1FlexGrid1.KeyDownEventArgs e) { if (e.RowCollection row = this.C1FlexGrid.Win. Add the following code to the Form_Load event to set the number of rows and columns to appear in the grid.C1FlexGrid.KeyEventArgs) Handles C1FlexGrid1. C1FlexGrid1.DataType = GetType(String) row(4).Rows C# C1. ByVal e As System. set the Caption and DataType properties for each row.Caption = "Contact" row(2).Count = 5 Me.Rows. Visual Basic row(1).Col) = 0.Row.Delete) { c1FlexGrid1(c1FlexGrid1.Caption = "Error Code" row(5).Rows.EditMask = "(999) 999-9999. Add the rows to the RowCollection:   3. System.Row.Private Sub C1FlexGrid1_KeyDown(ByVal sender As Object.*" row(4).KeyDown If (e.Cols.Rows.Forms.DataType = GetType(String) row(3).Count = 5.KeyCode == Keys.RowCollection = Me.Count = 7 C# this. Visual Basic Dim row As C1.DataType = GetType(DateTime) row(2). } } Setting Rows As Headers To set rows as headers.c1FlexGrid1.Delete) Then C1FlexGrid1(C1FlexGrid1.Win.ComboList = "|Windows XP|Windows 2000|Windows ME|Windows NT|Windows 98|Windows 95" row(5).Forms.  Visual Basic Me.c1FlexGrid1.Cols. Visual Basic Me.*".AllowMergingEnum.DataType = GetType(Boolean)  C# row[1].DataType = typeof(DateTime). row[2]. row[5]. FontStyle.Font = New Font("Tahoma". 4. 9pt.1.FixedOnly row(0).CellRange rng = c1FlexGrid1.Caption = "Date".C1FlexGrid1.C1FlexGrid1. 9.FixedOnly. row[4]. FontStyle. 198 .DataType = typeof(int).Styles("Fixed").AllowMerging = true.Caption = "Contact".EditMask = "(999) 999-9999.Data = "Call Log". row[3].Caption = "Resolved".Caption = "Error Code".row(6).AllowMergingEnum.Data = "Call Log" C# this.Bold).c1FlexGrid1. row[4]. row[4].AllowMerging = C1. row[0].Font = new Font("Tahoma". row[1].C1FlexGrid. row[3]. row[2].Caption = "Phone". Merge the fixed row and add a header to it:   This topic illustrates the following: The row headers appears in the first column and the each row will be formatted according to its DataType property.Win.CellRange = C1FlexGrid1. row[3]. Bold font.DataType = typeof(string).  Visual Basic Me.c1FlexGrid1.C1FlexGrid. 4) rng.  5.Caption = "Platform". 9.0.C1FlexGrid. 0. row[6].Win. row[6].DataType = typeof(string). C1.GetCellRange(0.ComboList = "|Windows XP|Windows 2000|Windows ME|Windows NT|Windows 98|Windows 95". 1.Caption = "Resolved" row(6). row[5].Win. Format the headers to Tahoma. rng.AllowMerging = True Dim rng As C1.Bold) C# this.DataType = typeof(bool).Styles["Fixed"].DataType = typeof(string).AllowMerging = C1.Win.GetCellRange(0.C1FlexGrid.4). Click OK to close the C1FlexGrid Style Editor.Styles. create a new style and assign it to a column and row.Win. In the Designer     Open the C1FlexGrid Style Editor.CellStyle cc = this. Setting the Background Color of Columns 1. and press ENTER when finished.  2. In the Designer   In the C1FlexGrid Style Editor.C1FlexGrid1.Add("ColumnColor"). rename it ColumnColor. Create a new style for the column. For details on how to access the C1FlexGrid Style Editor. Set the BackColor color to CornSilk. see Accessing the C1FlexGrid Style Editor (page 149).CellStyle cc = Me. In Code Add the following code to the Form_Load event:  Visual Basic Dim cc As C1.Win.c1FlexGrid1. Do not exit the C1FlexGrid Style Editor.C1FlexGrid. Click Add to create a new style. Double-click CustomStyle1.C1FlexGrid. In Code 199 .Styles.Setting the Background Color of Columns and Rows To set the background color of columns and rows.Add("ColumnColor") C# C1. locate the BackColor property in the right pane and set it to CornSilk. In the Designer     Open the C1FlexGrid Style Editor.Styles["ColumnColor"]. In the Designer     In the C1FlexGrid Style Editor.Styles.Styles("RowColor") 200 .Style = Me.BackColor = Color.C1FlexGrid1.C1FlexGrid1. Create a new style for the row. Double-click CustomStyle1.CellStyle rs = Me. Set the BackColor to PowderBlue. Do not exit the C1FlexGrid Style Editor.C1FlexGrid1.BackColor = Color.Cols(2). locate the BackColor property and set it to PowderBlue. In Code 3.Styles. In Code Add the following code to the Form_Load event:  Visual Basic Dim rs As C1.Win.BackColor = Color.C1FlexGrid1. and press ENTER when finished. Visual Basic rs.Cornsilk C# cc.c1FlexGrid1.Styles("ColumnColor") C# this.Win. Assign the style to a row by adding the following code to the Form_Load event:  Visual Basic Me.Style = this.Add the following code to the Form_Load event:   3.BackColor = Color.c1FlexGrid1. For details on how to access the C1FlexGrid Style Editor.Rows(8). Click Add to create a new style. Assign the style to a column by adding the following code to the Form_Load event:   Visual Basic Me. rename it RowColor.c1FlexGrid1.  2.Add("RowColor") C# C1. Setting the Background Color of Rows 1.CellStyle rs = this.Add("RowColor").PowderBlue.PowderBlue C# rs. This topic illustrates the following: The background color of the Element column is set to CornSilk. Click OK to close the C1FlexGrid Style Editor.Cornsilk.Style = Me.C1FlexGrid1.C1FlexGrid. Visual Basic cc. see Accessing the C1FlexGrid Style Editor (page 149).Cols[2].C1FlexGrid. c1FlexGrid1. this. create a new style and set it to the columns or rows as in Setting the Background Color of Columns and Rows (page 199). Setting the Background Color of Rows and Columns in a Single Statement To set the background color of rows and columns in a single statement. add the following code to the Form_Load event:  Visual Basic Me. This topic illustrates the following: The background color of the row is set to PowderBlue. However.Styles["RowColor"].Rows[8].StyleNew.BackColor = Color.C1FlexGrid1.BackColor = Color. 201 .Style = this. To apply a style to multiple columns or rows.  This topic illustrates the following: The single line of code produces the same result as creating a new style and assigning it to a row.Cols(2).Cols[2].StyleNew.Rows(8).StyleNew.c1FlexGrid1.c1FlexGrid1.BackColor = Color.PowderBlue C# this.Rows[8]. Notice how the column color takes precedence over the row color.C1FlexGrid1.BackColor = Color.Cornsilk Me.PowderBlue.c1FlexGrid1. using a single statement only changes the row or column it is set to.Cornsilk. C# this.StyleNew. CellStyle cs = Me. and press ENTER when finished. In the Designer     In the C1FlexGrid Style Editor. create a new style and assign it to a cell. Click Add to create a new style. In Code Add the following code to the Form_Load event:  Visual Basic Dim cs As C1. Bold. 202 . Create a new style. locate the Font property in the right pane and click the ellipsis button.  2. rename it myStyle.C1FlexGrid.Styles. Set the font to Tahoma.Win. see Accessing the C1FlexGrid Style Editor (page 149).c1FlexGrid1.C1FlexGrid1.Win. In the Designer     Open the C1FlexGrid Style Editor.C1FlexGrid. For details on how to access the C1FlexGrid Style Editor. Double-click CustomStyle1. Set the Font style box to Bold. The Font dialog will appear.Setting the Font of a Single Cell To set the font of a single cell.Add("myStyle").Add("myStyle") C# C1. Set the Size box to 10. Set the Font box to Tahoma. Do not exit the C1FlexGrid Style Editor.CellStyle cs = this. 1.Styles. 10 pt. Visual Basic cs. 2. FontStyle. 10. Assign the style to a cell by adding the following code to the Form_Load event:   Visual Basic Me. In Code Add the following code to the Form_Load event:   3.Bold). 10 pt. "myStyle"). Click OK to close the C1FlexGrid Style Editor. locate the ForeColor property in the right pane and set it to Blue.C1FlexGrid1. Set the font color to Blue.ForeColor = Color.ForeColor = Color. In the Designer   In the C1FlexGrid Style Editor. FontStyle. but do not exit the C1FlexGrid Style Editor. "myStyle") C# this. Bold.Blue. 10.SetCellStyle(6.Font = New Font("Tahoma".SetCellStyle(6. In Code Add the following code to the Form_Load event:   4.c1FlexGrid1. This topic illustrates the following: Carbon appears in Blue.Font = new Font("Tahoma". Tahoma font.Bold) C# cs. Visual Basic cs. Click OK to close the Font dialog box. 203 . 2.Blue C# cs. Cols. this.Split(".C1FlexGrid1.C1FlexGrid1. this.Descending C# this. this.SortFlags.Fixed = 0 Dim i% For i = 0 To Me.c1FlexGrid1.1 Me.c1FlexGrid1.Sort = C1.  2.Descending.Ascending Me.C1FlexGrid1.SortFlags.Count .C1FlexGrid1.Cols(2).Cols.c1FlexGrid1. Sorting Multiple Columns To sort multiple columns.Region.C1FlexGrid.Cols[2].C1FlexGrid.Cols(i). Visual Basic Me.c1FlexGrid1.C1FlexGrid.Cols[i].Salesperson.  Visual Basic Me. this. 1. 1.SortFlags.Region.Win.c1FlexGrid1[0. for (int i = 0.Name = colNames[i].") Me.Split(new char[] { '.   This topic illustrates the following: 204 .' }).Win.UseColSort.SortFlags.Cols.Ascending.Sales.Count = 5.Win. Add the following code to the Form_Load event to set the second column to sort in ascending order and the third column to sort in descending order.Cols.SortFlags. 1. string[] colNames = cols.Sort = C1.C1FlexGrid1. Add the following Sort method to sort according to the settings in columns two and three.C1FlexGrid1.Bonus".Win.Sort(C1.C1FlexGrid1(0.Salesperson. Changing the semicolon to a comma in both the Split method and the string will produce the same output as the semicolon.C1FlexGrid. 2). 2) C# this.Cols. set the Split method.1.Win. } This topic illustrates the following: The string in the Split method determines the delimiting character.Setting the Text Delimiting Character in C1FlexGrid To set the text delimiting character in C1FlexGrid. Add the following code to the Form_Load event to set the delimiting character to a semicolon:  Visual Basic Dim cols As String = "Product.UseColSort.Sort = C1.Count = 5 Me.Win. i <= this. set each column's Sort property and use the Sort method to sort according to the column settings.c1FlexGrid1. i++) { this.Cols(1).C1FlexGrid.c1FlexGrid1.Cols.Fixed = 0.Name = colNames(i) Next  C# string cols = "Product.SortFlags.c1FlexGrid1.Sales.C1FlexGrid1. i] = colNames[i].C1FlexGrid.Count .Bonus" Dim colNames As String() = cols.Sort = C1. i) = colNames(i) Me.Sort(C1.Cols[1]. Sort = "" End Sub C# private void Button1_Click(object sender. then the third column in descending order. and setting the sort string to null forces the DataView to undo the previous sort. }  Note: The DataTable. then by the Element column in descending order. Undoing a Sort To undo a sort in C1FlexGrid when the grid is bound to a DataTable. In this example.DefaultView. ByVal e As System.EventArgs) Handles Button1.DefaultView returns the DataView of the DataTable.EventArgs e) { CustTable. System.DefaultView. Add the following code to the Button1_Click event:  Visual Basic Private Sub Button1_Click(ByVal sender As System.Your grid will look like the following with the second column sorted in ascending order. 205 .Object. Neon appears before Argon in the Element column since the grid is sorted first by the StandardState column in ascending order.Click CustTable. This topic illustrates the following: Click the Last Name column to sort on it.Sort = "". set the DefaultView property to null. C1FlexGrid.EventArgs) Handles MyBase.C1FlexGrid1.Name) = "Password") Me. Using Password Entries in C1FlexGrid To show placeholder characters (*) in cells used for password entry.Cols(1).  206 .Object.Cols[0].Click the Undo button.OwnerDraw End Sub C# private void Form1_Load(object sender. use the SetupEditor event.C1FlexGrid1.EventArgs e) { this. and the sort will be undone.ShowCursor = true.DrawMode = C1. Create a column for passwords in the grid and set the draw mode:  Visual Basic Private Sub Form1_Load(ByVal sender As System.ShowCursor = True Me.Width = Me.c1FlexGrid1.Caption =((Me.C1FlexGrid1.Rows(0).Win.HeightDisplay.Cols(0). ByVal e As System.DrawModeEnum.C1FlexGrid1.c1FlexGrid1.C1FlexGrid1.Load Me.HeightDisplay Me. 1. this.C1FlexGrid1. System.Cols(1).Rows[0].Width = this.c1FlexGrid1.  Visual Basic Private Sub C1FlexGrid1_SetupEditor(ByVal sender As Object. } }  This topic illustrates the following: When the user enters a password in the Password column and presses ENTER.Editor as TextBox.PasswordChar = "*"c Else tb.Name == "Password") tb.Cols[e.C1FlexGrid.PasswordChar = (char)0.RowColEventArgs) Handles C1FlexGrid1. This code will hide characters that are entered by the user. use the OwnerDrawCell event. 207 .C1FlexGrid1. else tb. Add the following code for the SetupEditor event.Win.DrawMode = C1. ByVal e As C1.OwnerDraw.c1FlexGrid1.DrawModeEnum. if (tb != null) { if (this.PasswordChar = CChar(0) End If End If End Sub C# private void c1FlexGrid1_SetupEditor(object sender.this.RowColEventArgs e) { TextBox tb = this.C1FlexGrid.Win.Cols(e. Hiding Characters Already Entered To hide the characters that have already been entered and do not need edited.C1FlexGrid. the text is automatically converted to asterisks.Col].Caption = this.Editor If Not (tb Is Nothing) Then If Me.c1FlexGrid1.Col).Name = "Password" Then tb.Name = "Password".c1FlexGrid1.SetupEditor Dim tb As TextBox = Me. } 2.Cols[1].c1FlexGrid1. this.Cols[1].Win.c1FlexGrid1. C1.C1FlexGrid1.PasswordChar = '*'. Fixed And Me.C1FlexGrid1(1. 1. 208 .Col). Set the Caption property for a column header in the grid. This topic illustrates the following: Run the project again and notice the numbers are automatically loaded onto the form in the Password column as asterisks.Row >= this. This code will hide the characters that have already been entered and do not need edited. Add the following code for the OwnerDrawCell event.Text = new string('*'.Text. In the Designer   Select a column in the grid.Win.Name = "Password" Then e.1] = "123456".c1FlexGrid1.Name == "Password") { e.c1FlexGrid1.Win.Fixed && this.OwnerDrawCellEventArgs e) { if (e.Rows.Length).C1FlexGrid. 1) = "123456" C# this. ByVal e As C1.OwnerDrawCellEventArgs) Handles C1FlexGrid1. e. C1.Cols[e. enter Word Wrapping in Header.Col].OwnerDrawCell If e. In the Column Caption box. set the Height and WordWrap properties.Cols(e. e.c1FlexGrid1[1.Length) End If End Sub C# private void c1FlexGrid1_OwnerDrawCell(object sender.1.Text = New String("*"c. Word Wrapping in a Header or Fixed Row To set word wrapping in a header or fixed row. Add the following code to the Form_Load event:   Visual Basic Me.  Visual Basic Private Sub C1FlexGrid1_OwnerDrawCell(ByVal sender As Object.C1FlexGrid1. } }  2. This will open the Column Tasks menu for that column.Row >= Me.C1FlexGrid1.Rows.C1FlexGrid.Text. In the Designer     Open the C1FlexGrid Style Editor.WordWrap = true. Select a column in the right pane and set the Caption property in the left pane to Word Wrapping in Header. This topic illustrates the following: In this example.Rows.DefaultSize C# this.Styles["Fixed"]. For details on how to access the C1FlexGrid Column Editor. 209 . Click OK to close the editor.C1FlexGrid1.DefaultSize. Set the row height of the header.    Open the C1FlexGrid Column Editor. Enable word wrapping for the fixed cells. a three-line header is created.   3.Height = 3 * Me.c1FlexGrid1. Visual Basic Me. the Caption property can also be set using the C1FlexGrid Column Editor.Styles("Fixed").c1FlexGrid1.WordWrap = True C# this. Visual Basic Me.   2. and the text is wrapped. For details on how to access the C1FlexGrid Style Editor. Click OK to close the designer.Rows(0).Rows[0].c1FlexGrid1.Cols[1]. see Accessing the C1FlexGrid Style Editor (page 149).C1FlexGrid1.C1FlexGrid1.c1FlexGrid1.Alternatively.Caption = "Word Wrapping in Header" C# this. Select Fixed in the Built-In Styles list. In Code Add the following code to the Form_Load event:   Visual Basic Me.Cols(1). Locate the WordWrap property in the right pane and set it to True.C1FlexGrid1. see Accessing the C1FlexGrid Column Editor (page 149).Height = 3 * this.Rows.Caption = "Word Wrapping in Header". In Code Add the following code to the Form_Load event. 210 . BeginUpdate().Rows. c++) { _flex[r. } } } finally { // Always call EndUpdate when done. c) = (r + c) c += 1 Loop r += 1 Loop Finally ' Always call EndUpdate when done.FlexGrid for WinForms Top Tips The following tips were compiled from frequently asked user questions posted in the C1FlexGrid forum. c < _flex.Count) _flex(r.Count) Dim c As Integer = 0 Do While (c < _flex.EndUpdate method is called even if the update code fails and throws an exception.Cols. _flex. _flex. You can increase performance significantly by enclosing the changes in calls to the BeginUpdate and EndUpdate methods.Count.Cols. try { for (int r = 0. } Note the use of a try/finally block to ensure that the C1FlexGridBase. r++) { for (int c = 0. Tip 1: Use the BeginUpdate/EndUpdate Methods to Increase Performance Every time a cell value is changed. _flex.EndUpdate() End Try  C# // call BeginUpdate before updating the grid.Count. // Make the changes. r < _flex.Rows. For example:  Visual Basic ' call BeginUpdate before updating the grid. c] = r + c. Try Dim r As Integer = 0 Do While (r < _flex. _flex. some calculations are performed in order to recalculate the grid layout and update the display. or rows and columns are added or removed from the grid.EndUpdate(). BeginUpdate() ' Make the changes. 211 . In these cases.Count) _flex(r.EventArgs) Handles MyBase.ForeColor = Color. _flex.C1FlexGrid. _flex. Tip 3: Use the DrawMode Property to Assign Styles Dynamically Based on Cell Values The grid allows you to create cell styles and assign them to rows.Add("Red"). the Redraw property was used for the same purpose. cells that contain negative values can display them in red. 212 .000 in green:  Visual Basic Private Sub Form1_Load(ByVal sender As System. Tip 2: Use the AutoResize Property to Increase Performance When a bound grid retrieves data from a data source. it measures every cell and sets the column widths so they fit all the data.ForeColor = Color.Add("Green"). styles will be lost whenever the data source is reset (after sorting and filtering operations for example).Rows. and arbitrary cell ranges. you can either set the AutoResize property to True manually or simply call the AutoSizeCols methods after binding or populating the grid.OwnerDrawCell ' Check that the row and column contain integer data. you should consider setting the AutoResize property to False and setting the column widths in code. the code below shows negative values in red and values above 1. 1) = rnd. If your data source contains a relatively small number of items and you want the grid to resize the columns automatically.Win. based on the cell values.Styles.C1FlexGrid.Cols(1). if the grid is bound to a data source. but it can be timeconsuming if the data source is large (say more than a few thousand rows). 10000) r += 1 Loop ' Create style used to show negative values. This change was made to increase performance in cases where the grid is bound to large data sources.DrawModeEnum.Green ' Enable OwnerDraw by setting the DrawMode property. but in this case you have to update the style whenever the cell value changes. For example. _flex. You can use this capability to format cells based on their values.Load ' Fill a column with random values. This ensures the grid layout is optimal to display the data in the data source.Win.NOTE: The BeginUpdate and EndUpdate methods were added in the 2010/v1 release of the C1FlexGrid. ByVal e As C1. In previous versions. columns. ByVal e As System.OwnerDrawCellEventArgs) Handles _flex. NOTE: Starting with the 2010/v1 release of the C1FlexGrid. _flex.Object. Also.DataType = GetType(Integer) Dim rnd As New Random Dim r As Integer = 1 Do While (r < _flex.OwnerDraw End Sub Private Sub _flex_OwnerDrawCell(ByVal sender As Object.Red ' Create style used to show values >= 1000.Next(-10000. You can do this by assigning styles to cells with the SetCellStyle method. A better alternative in these cases is to use the grid's OwnerDraw feature and select styles dynamically.Styles. the AutoResize property defaults to False. For example. This change was made to increase source compatibility with other controls that use the BeginUpdate and EndUpdate pattern.DrawMode = C1. Win. r++) { _flex[r.Count.Rows. 1] = rnd.Add("Red").DataType Is GetType(Integer))) Then ' Get value in cell about to be painted.Style = _flex.Next(-10000.DataType == typeof(int)) { // Get value in cell about to be painted. e.Styles.OwnerDrawCellEventArgs e) { // Check that the row and column contain integer data.Style = _flex.OwnerDrawCellEventHandler(_flex_OwnerDrawCell). EventArgs e) { // Fill a column with random values. // Enable OwnerDraw by setting the DrawMode property.Add("Green").DrawModeEnum.DrawMode = C1. e.C1FlexGrid.Row. e. } 213 . } // Create style used to show negative values.Styles("Red") ElseIf (value >= 1000) Then ' If the Cell value >= 1000.Win. _flex.OwnerDrawCell += new C1. use the Red style.C1FlexGrid. if (value < 0) { // If the Cell value < 0.Cols[e. C1.Win. int value = (int)_flex[e.Red.Styles("Green") End If End If End Sub  C# private void Form1_Load(object sender. 10000).Cols[1].Col)) If (value < 0) Then ' If the Cell value < 0. _flex.ForeColor = Color.ForeColor = Color. _flex. e. Random rnd = new Random(). r < _flex. use the Red style.DataType = typeof(int). e.Col).Cols(e.Col]. Dim value As Integer = CInt(_flex(e. if (e. _flex. // Create style used to show values >= 1000.Style = _flex.Row.If ((e. use the Green style.Row > 0) AndAlso (_flex. for (int r = 1.Green.Styles["Red"].Styles. _flex.Col].Row > 0 && _flex.C1FlexGrid. } private void _flex_OwnerDrawCell(object sender.OwnerDraw. Style = _flex. ByVal e As C1.Style. C1.OwnerDrawCellEventArgs) Handles _flex.OwnerDrawCellEventArgs) Handles _flex. } Contrast this with the following:  Visual Basic ' ** WRONG APPROACH: Private Sub _flex_OwnerDrawCell(ByVal sender As Object. you could.C1FlexGrid.Col). e.Row.Win.C1FlexGrid. ByVal e As C1. C1.else if (value >= 1000) { // If the Cell value >= 1000.OwnerDrawCell ' Select style to use when painting this cell: ' This is bad because changing any CellStyle objects invalidates the ' grid. use the Green style.Styles["Green"].Style = MyStyleSelector(e.Col) End Sub  C# // ** CORRECT APPROACH: private void _flex_OwnerDrawCell(object sender.Col) End Sub  C# // ** WRONG APPROACH: private void _flex_OwnerDrawCell(object sender.OwnerDrawCellEventArgs e) { // Select style to use when painting this cell: // This is bad because changing any CellStyle objects invalidates the // grid. it assigns a new value to the e.Style = MyStyleSelector(e.Row.OwnerDrawCell ' Select style to use when painting this cell: e. That is important because the CellStyle passed to the event handler is often used by other cells.Row. which would cause this event handler to be called over and 214 .Win. e. For example. which would cause this event handler to be called over and ' over again. Instead.C1FlexGrid. e. e. unintentionally change the grid's normal style.Win. The examples below illustrate the difference:  Visual Basic ' ** CORRECT APPROACH: Private Sub _flex_OwnerDrawCell(ByVal sender As Object. } } } Tip 4: Do Not Modify Styles in the OwnerDrawCell Event Note that the code in Tip 3 does not modify the CellStyle object passed as a parameter in the OwnerDrawCell event.OwnerDrawCellEventArgs e) { // Select style to use when painting this cell: e.C1FlexGrid. which would affect most cells in the grid.Style parameter.Color = MyColorSelector(e.Win. e. e.Style. 215 . or EllipsisPath.StyleNew. _flex. use the WordWrap and Height properties.Rows.WordWrap = true. Character. Tip 6: Use the WordWrap Property to Show Multiple Line Text in a Cell When showing multiple lines of text in a cell. The algorithm keeps as much of the last slash-delimited segment of the line as possible. _flex(1.WordWrap = True ' Set the row height.CrLf & " This is the second line.EllipsisCharacter C# _flex.Col). To determine how long strings are trimmed to fit the cell.Cols[1]."  C# // Set the WordWrap property. Specifies no trimming.Rows(1)." & ControlChars. the Trimming property can be set to either None. The center is removed from the trimmed lines and replaced by an ellipsis. EllipsisWord None Word The following code sets the Trimming property to show ellipses at the end of the second column.Height = 2 * fg.Trimming =StringTrimming. EllipsisCharacter. see Word Wrapping in a Header or Fixed Row (page 208). _flex.Color = MyColorSelector(e. Strings that contain hard line breaks (vbCrLf or "\n\r") are always displayed in multiple lines.StyleNew. EllipsisWord. Specifies that the text is trimmed to the nearest word and an ellipsis is inserted at the end of a trimmed line. } Tip 5: Use the Trimming Property to Show Ellipses in a Single Column of the Grid The Trimming property should be used to show ellipses in a single column of the grid.Trimming StringTrimming. e.Cols(1). The following table describes each of the be trimming options: Member Name Character EllipsisCharacter EllipsisPath Description Specifies that the text is trimmed to the nearest character. Multiple line text can be displayed in both fixed and scrollable cells.DefaultSize ' Add text to the cell.Row. Specifies that the text is trimmed to the nearest word. and an ellipsis is inserted at the end of a trimmed line. Specifies that the text is trimmed to the nearest character. 2) = "This is the first line. The WordWrap property determines whether the grid should automatically break long strings that contain spaces and display them in multiple lines. For an example setting multiple line text in a fixed cell.// over again. _flex. with the text trimmed to the nearest character:   Visual Basic _flex. The following code sets display multiple line text in a scrollable cell:  Visual Basic ' Set the WordWrap property. Word.Styles["Normal"].EllipsisCharacter.Styles("Normal"). Setting the sort expression at run time immediately reflects the changes in the data view. ByVal e As System.Products) End Sub Private Sub btn_Sort_Click(ByVal sender As System.Rows.Sort = "UnitsInStock ASC. _flex[1.// Set the row height. EventArgs e) { // Sort the data by the UnitsInStock column then by the ProductID column. Tip 7: Use the Sort Property to Retrieve Data Sorting when Bound to a DataTable If the grid is bound to a DataTable.Fill(this. } Tip 8: Control the Number of Characters to be Entered in a Column with the SetupEditor Event 216 .Height = 2 * fg.Rows[1].Click ' Sort the data by the UnitsInStock column then by the ProductID column. the user can maintain the way the grid is sorted when data is refreshed.EventArgs) Handles btn_Sort. 2] = "This is the first line. this. \r\n This is the second line.EventArgs) Handles btn_ClearSort. By default.ProductsBindingSource.Load Me.". System.Object.nwindDataSet.productsBindingSource. ProductID ASC" End Sub Private Sub btn_ClearSort_Click(ByVal sender As System. ByVal e As System.Sort = "".productsBindingSource.productsTableAdapter.Object. EventArgs e) { // Clear the sort. ProductID ASC".Object. A sort expression can include names of grid columns or a calculation.NwindDataSet. _flex. } private void btn_Sort_Click(object sender. Me. The Sort property uses a string containing the column name followed by ASC (to sort the column in ascending order) or DESC (to sort the column in descending order).Sort = "" End Sub  C# private void Form1_Load(object sender. columns are sorted in ascending order.Products).DefaultSize.  Visual Basic Private Sub Form1_Load(ByVal sender As System. Me.ProductsBindingSource.EventArgs e) { this. ByVal e As System. // Add text to the cell.Sort = "UnitsInStock ASC. This can be achieved by using the default view's Sort property and a sort expression.Fill(Me.EventArgs) Handles MyBase. Multiple columns can be sorted by entering each column name separated by a comma.Click ' Clear the sort. this.ProductsTableAdapter. } private void btn_ClearSort_Click(object sender. MaxLength = 20.Win.Editor.StartEdit _flex. } 217 .To set the maximum number of characters a user can enter for any given column use the SetupEditor event.Col == 2) c1TextBox. C1TextBox).RowColEventArgs) Handles _flex. For this example a C1TextBox has been set as the editor for C1FlexGrid.C1FlexGrid.RowColEventArgs) Handles _flex.Editor. if (e.SetupEditor ' Set the 3rd column to allow 20 characters and the rest only 10.Col = 2 Then CType(fg.RowColEventArgs e) { _flex.Win.Editor = C1TextBox End Sub C# private void _flex_StartEdit(object sender. else c1TextBox.C1FlexGrid.MaxLength = 20 Else CType(fg. ByVal e As C1. ByVal e As C1. RowColEventArgs e) { // Set the 3rd column to allow 20 characters and the rest only 10. C1TextBox).Editor = c1TextBox.Object. You must declare an external editor to be used with C1FlexGrid in the StartEdit event:  Visual Basic Private Sub _flex_StartEdit(ByVal sender As System.MaxLength = 10 End If End Sub  C# private void _flex_SetupEditor(object sender. If e.Win. C1.MaxLength = 10. }  Now that you have the grid's editor set up you can use the following code to allow 20 characters to be entered in the 3rd column and only 10 characters to be entered in the rest of the grid's columns (remember the following code must be entered in the SetupEditor event):  Visual Basic Private Sub _flex_SetupEditor(ByVal sender As Object.C1FlexGrid.
Copyright © 2024 DOKUMEN.SITE Inc.