spread windows forms developer's guide
TRANSCRIPT
Developer's Guide
Thisguideprovidesintroductoryconceptualmaterialandhow-toexplanationsforroutinetasksfordevelopersusingSpreadWindowsForms.ItdescribeshowanapplicationdeveloperwouldusethepropertiesandmethodsinSpreadtocreatespreadsheetsonWindowsForms,bindtodatabases,andotherwisecreateagridondata-intensiveapplicationsforthe.NETplatform.
GettingStartedUnderstandingtheProductUnderstandingtheSpreadsheetObjectsUnderstandingtheUnderlyingModelsCustomizingtheSheetAppearanceCustomizingRow,Column,andCellAppearanceCustomizingSheetInteractionCustomizingRoworColumnInteractionCustomizingInteractionwithCellTypesCustomizingInteractioninCellsManagingDataBindingManagingDataonaSheetManagingKeyboardInteractionManagingEventsfromUserActionsManagingFileOperationsManagingPrintingWorkingwiththeChartControlUsingTouchSupportwiththeComponent
Formoreinformation,besuretolookattheadditionalhelpfulresources:
Forsampleinformation,refertoGettingStarted.
ForcompleteAPIreferenceinformation,refertotheAssemblyReference(on-linedocumentation).
Foracompletelistofdocumentation,refertotheSpreadWindowsFormsDocumentation(on-linedocumentation).
Spread Windows Forms Developer’s Guide 0
Copyright © GrapeCity, Inc. All rights reserved.
1 Table of Contents
Developer'sGuide 0
1. TableofContents 1-20
GettingStarted 21
HandlingInstallation 21
InstallingtheProduct 21
LicensingaTrialProjectafterInstallation 21
End-UserLicenseAgreement 21-22
CreatingaBuildLicense 22-23
HandlingRedistribution 23-25
ProductRequirements 25
UsingWindowsRegionalSettingsorOptions 25-26
UsingSatelliteAssembliesforLanguages 26
WorkingwiththeComponent 26
AddingaComponenttoaVisualStudio2015or2017Project 26-28
AddingaComponenttoaVisualStudio2013Project 28-30
AddingaComponenttoaProject 30-32
UnderstandingPartsoftheComponent 32
UsingSmartTagsDrop-Down 32-34
UsingVerbsinthePropertyWindow 34-36
WorkingwithCollectionEditors 36-37
AddingSupportforHighDPISettings 37-39
UnderstandingtheSpreadWizard 39-40
StartingtheSpreadWizard 40
UsingtheSpreadWizard 40-41
GettingMorePractice 41
FindingtheDocumentation 41-43
GettingTechnicalSupport 43
Tutorial:CreatingaCheckbookRegister 43-44
Spread Windows Forms Developer’s Guide 1
Copyright © GrapeCity, Inc. All rights reserved.
AddingSpreadtotheCheckbookProject 44
SettingUpRowsandColumnoftheRegister 44-46
SettingtheCellTypesoftheRegister 46-48
AddingFormulastoCalculateBalances 48-49
UnderstandingtheProduct 50
ProductOverview 50-51
FeatureOverview 51-52
CameraShapes 52-53
CellTypesforCellFunctionality 53
ChartControlsonaSheet 53
ChildControlsonaSheet 53
ColumnFootersandGroupFooters 53
ConditionalFormatting 53
DataBinding 53
ExcelSupportwithImportandExportCapabilities 53-54
FilteringDataonaSheet 54
FormulaTextBox(FormulaBar) 54
FormulaProviderControl 54
FunctionsandFormulas 54-55
GradientsforButtonCells,Headers,andMore 55
GroupingRowsintheDisplay 55
GroupingRowsorColumnsinanOutline 55
HeaderswithMultipleColumnsandRows 55
HierarchicalDisplay 55
HitTestforLocatingtheCursor 55
IndicatorsandIconsintheInterface 55-56
InkNotationSupport 56
KeyboardActionMapping 56
MultipleSheets 56
Spread Windows Forms Developer’s Guide 2
Copyright © GrapeCity, Inc. All rights reserved.
NameBoxControl 56
NotesforCells 56-57
PanesorViewports 57
PrintingandPDF 57
QuickStartWizard 57
Right-to-LeftLayouts 57
RowPreview 57
SearchingandSearchDialog 57
Shapes,Drawing,andAnnotations(FreehandDrawing) 57-58
SortingRowsorColumns 58
SpannableCells 58
Sparklines 58
SpreadDesigner 58
StylesandSkinsforCustomizedAppearance 58-59
Tables 59
TabStripandSheetNameTabs 59
TextRenderingwithGDI 59-60
TitleandSubTitle 60
TouchSupport 60
UndoandRedoActions 60
VisualStylesforXPThemes 60
NamespaceOverview 60-61
ConceptsOverview 61
ShortcutObjects 61-64
ObjectParentage 64
FormattedversusUnformattedData 64-65
CellTypes 65-67
UnderlyingModels 67
UnderstandingtheSpreadsheetObjects 68
Spread Windows Forms Developer’s Guide 3
Copyright © GrapeCity, Inc. All rights reserved.
WorkingwithSheets 68
WorkingwiththeActiveSheet 68-69
WorkingwithMultipleSheets 69-70
AddingaSheet 70-71
CopyingandInsertingaSheet 71-72
MovingaSheet 72-73
RemovingaSheet 73-74
ShowingorHidingaSheet 74-75
WorkingwithRowsandColumns 75-76
CustomizingtheNumberofRowsorColumns 76-77
AddingaRoworColumn 77-78
RemovingaRoworColumn 78-79
ShowingorHidingaRoworColumn 79-80
WorkingwithHeaders 80-81
UnderstandingHeaders 81
CreatingaHeaderwithMultipleRowsorColumns 81-84
ShowingorHidingHeaders 84-86
WorkingwithCells 86
WorkingwiththeActiveCell 86-87
CreatingaRangeofCells 87-88
UnderstandingtheUnderlyingModels 89
UnderstandingtheTypesofSheetModels 89
UnderstandingtheSheetModelClassesandInterfaces 89-91
FindingMoreDetailsontheSheetModels 91-92
UnderstandingtheDataModel 92-93
UnderstandingtheAxisModel 93-94
UnderstandingtheSelectionModel 94-95
UnderstandingtheSpanModel 95
UnderstandingtheStyleModel 95-98
Spread Windows Forms Developer’s Guide 4
Copyright © GrapeCity, Inc. All rights reserved.
CreatingaCustomSheetModel 98-99
UnderstandingtheOptionalInterfaces 99-100
CustomizingtheSheetAppearance 101
CustomizingtheAppearanceoftheOverallComponent 101
SettingtheComponenttotheOriginalAppearance 101-103
ApplyingaSkintotheComponent 103-104
CreatingaCustomSkinforaComponent 104-107
CustomizingtheRenderers 107-111
CustomizingtheDimensionsoftheComponent 111-112
CustomizingtheOutlineoftheComponent 112-113
CustomizingtheDisplayofthePointer 113-114
CustomizingPaintingofPartsoftheComponent 114-115
UsingXPThemeswiththeComponent 115-116
HandlingRight-to-LeftLayouts 116-117
CustomizingtheIndividualSheetAppearance 117
SettingtheBackgroundColorsforaSheet 118-119
SettingaBackgroundImageforaSheet 119-120
DisplayingGridLinesonaSheet 120-122
AddingaTitleandSubtitletoaSheet 122-123
DisplayingaFooterforColumnsorGroups 123-127
ApplyingaSkintoaSheet 128-129
CreatingaCustomSkinforaSheet 129-131
CustomizingtheSheetCornerAppearance 131-132
GeneralStyleoftheSheetCorner 132-135
TextDisplayintheSheetCorner 135-136
TableDisplayintheSheetCorner 136-137
CustomizableCellintheSheetCorner 137-138
CellSpansintheSheetCorner 138-139
HeaderCountSynchronizationintheSheetCorner 139-140
Spread Windows Forms Developer’s Guide 5
Copyright © GrapeCity, Inc. All rights reserved.
Drawing(Rendering)Style 140-142
CustomizingRow,Column,andCellAppearance 143
CustomizingtheRoworColumnAppearance 143
SettingtheRowHeightorColumnWidth 143-145
ResizingtheRoworColumntoFittheData 145-146
FindingRowsandColumnThatHaveData 146-147
CreatingAlternatingRows 147-149
CustomizingtheAppearanceofHeaders 149-150
CustomizingtheDefaultHeaderLabels 150-152
CustomizingHeaderLabelText 152-154
CustomizingtheStyleofHeaderCells 154-156
AddingaGradienttoHeaderCells 156-157
CustomizingtheHeaderGridLines 157-160
SettingtheHeightorWidthofHeaderCells 160-161
CreatingaSpaninaHeader 161-163
CustomizingtheAppearanceofaCell 163-164
ColoringaCell 164-166
SettingaBackgroundImagetoaCell 166-168
AligningCellContents 168-170
ResizingtheCelltoFittheData 170-171
ResizingtheDatatoFittheCell 171-172
CustomizingCellBorders 172
CreatingandCustomizingCellBorders 172-176
CreatingBorderswithDiagonalLines 176-178
CreatingaComplexBorderwithMultipleLines 178-180
CreatingaSpanofCells 180-182
AllowingCellstoMergeAutomatically 182-184
AllowingCellDatatoOverflow 184-186
CreatingandApplyingaStyleforCells 186-189
Spread Windows Forms Developer’s Guide 6
Copyright © GrapeCity, Inc. All rights reserved.
UsingSparklines 189
AddingaSparklinetoaCell 189-191
CustomizingMarkersandPointers 191-193
SpecifyingHorizontalandVerticalAxes 193-194
WorkingwithSparklines 194-197
CustomizingSheetInteraction 198
CustomizingInteractionwiththeOverallComponent 198
CustomizingtheScrollBarsoftheComponent 198-202
CustomizingtheScrollBarTips 202-204
CustomizingtheSheetNameTabsoftheComponent 204-209
CustomizingtheUserInterfaceImages 209-211
AllowingtheUsertoZoomtheDisplayoftheComponent 211
CustomizingtheScaleMode 211-212
AddingaContextMenutoaComponent 212-213
HostingtheComponentonaWebPage 213
CustomizingClipboardOperationOptions 213-215
CustomizingUndoandRedoActions 215-216
LocatingthePointerUsingHitTest 216-217
CustomizingInteractionBasedonEvents 217
HandlingEventsofSubeditors 217-218
CustomizingtheUserErrorMessages 218
CustomizingInteractionwithaSheet 218
CustomizingViewports 218-222
CustomizingSplitBoxes 222-224
CustomizingthePositionintheDisplay 224-225
PlacingChildControlsonaSheet 225-226
CreatingTables 226-227
AddingaTable 227-228
UsingTableFilters 228-231
Spread Windows Forms Developer’s Guide 7
Copyright © GrapeCity, Inc. All rights reserved.
ResizingaTable 231-232
SortingaTable 232-233
SettingTableStyles 233-236
AddingaTableFormula 236-237
UnderstandingStructuredReferences 237-238
UsingOperatorsandSpecialItems 238-239
UnderstandingStructuredReferenceSyntaxRules 239-240
UsingStructuredReferences 240
CustomizingUserSearchingofData 240-241
AllowingtheUsertoPerformaStandardSearch 241-242
AllowingtheUsertoPerformanAdvancedSearch 242
SearchingforDatawithCode 242-243
CustomizingUserSelectionofData 243
SpecifyingWhattheUserCanSelect 244-247
CustomizingtheSelectionAppearance 247-250
WorkingwithSelections 250-251
HidingtheSelectionWhenFocusisLost 251
UsingApplicationTags 251
AddingaTagtoaSheet 251
AddingaTagtoaRoworColumn 251-252
AddingaTagtoaCell 252-253
SettingandResettingUserInteraction 253
AllowingUserFunctionality 253-255
ResettingPartsoftheInterface 255-257
ClearingorRemovingPartsoftheInterface 257
CustomizingDrawing 257-258
WorkingwithShapesinCode 258-260
WorkingwithAnnotations 260-261
AllowingtheUsertoDrawwithaTabletPC 261-262
Spread Windows Forms Developer’s Guide 8
Copyright © GrapeCity, Inc. All rights reserved.
CreatingCameraShapes 262-264
CustomizingRoworColumnInteraction 265
AllowingUserInteractionwithRowsandColumns 265
AllowingtheUsertoEnterDatainRowsorColumns 265-266
AllowingtheUsertoMoveRowsorColumns 266-268
AllowingtheUsertoResizeRowsorColumns 268-269
SettingFixed(Frozen)RowsorColumns 269-271
SettingupPreviewRows 271-273
ManagingFilteringofRowsofUserData 273-275
AllowingtheUsertoFilterRows 275-276
CustomizingSimpleFiltering 276
UnderstandingSimpleRowFiltering 276-277
SettingtheAppearanceofFilteredRows 277-280
CustomizingtheFilterList 280
DefiningtheContentsoftheFilterItemList 280-284
DefiningtheOrderoftheItemsintheFilterItemList 284-285
SettingtheAppearanceoftheDisplayoftheFilterItemList 285-287
CreatingaCompletelyCustomFilter 287
SettingtheAppearanceofFilterIndicators 287
UseCustomFilterIndicatorImages 287-289
ShowingorHidingFilterIndicators 289
DeterminingWhichHeaderRowDisplaystheIndicators 289-290
CustomizingEnhancedFiltering 290
UnderstandingEnhancedRowFiltering 290-293
CustomizingtheFilterBar 294-295
ManagingGroupingofRowsofUserData 295
AllowingtheUsertoGroupRows 295-296
UsingGrouping 296-297
SettingtheAppearanceofGroupedRows 297-298
Spread Windows Forms Developer’s Guide 9
Copyright © GrapeCity, Inc. All rights reserved.
CustomizingtheGroupBar 298-299
CreatingaCustomGroup 299
InteroperabilityofGroupingwithOtherFeatures 299-300
ManagingOutlines(RangeGroups)ofRowsandColumns 300
UsinganOutline(RangeGroup)ofRowsorColumns 300-302
CustomizingtheAppearanceofanOutline(RangeGroup) 302-303
InteroperabilityofOutlineswithOtherFeatures 303-304
ManagingSortingofRowsofUserData 304-305
AllowingtheUsertoAutomaticallySortRows 305-307
UsingAutomaticSorting 307
SortingRows,Columns,orRanges 307-309
SettingtheAppearanceofSortIndicators 309-311
CustomizingInteractionwithCellTypes 312
UnderstandingHowCellTypesWork 312
UnderstandingCellTypeBasics 312-313
DeterminingtheCellTypeoftheActiveCell 313
UnderstandingHowCellTypesDisplayandFormatData 313-316
UnderstandingHowCellTypeAffectsModelData 316-317
WorkingwithEditableCellTypes 317-318
SettingaCurrencyCell 318-319
SettingaDate-TimeCell 319-321
SettingaGcDateTimeCell 321-323
SettingaGcNumberCell 323-325
SettingaGcTextBoxCell 325-327
SettingaGeneralCell 327-329
SettingaMaskCell 329-330
SettingaNumberCell 330-335
SettingaPercentCell 335-337
SettingaRegularExpressionCell 337-338
Spread Windows Forms Developer’s Guide 10
Copyright © GrapeCity, Inc. All rights reserved.
SettingaTextCell 338-339
WorkingwithGraphicalCellTypes 339-340
SettingaBarcodeCell 340-345
SettingaButtonCell 345-349
SettingaCheckBoxCell 349-352
SettingaColorPickerCell 352-356
SettingaComboBoxCell 356-359
SettingaHyperlinkCell 359-363
SettinganImageCell 363-365
SettingaListBoxCell 365-367
SettingaMultiple-ColumnComboBoxCell 367-370
SettingaMultipleOptionCell 370-372
SettingaProgressIndicatorCell 372-374
SettingaRichTextCell 374-378
SettingaSliderCell 378-381
UnderstandingAdditionalFeaturesofCellTypes 381-382
DisplayingSpinButtons 382-383
AllowingaComboBoxCelltoHandleaDouble-Click 383-385
LimitingValuesforaNumericCell 385-386
CustomizingthePop-UpDate-TimeControl 386-388
CustomizingthePop-UpCalculatorControl 388-390
CustomizingAutomaticCompletion(TypeAhead) 390
WorkingwithaSubEditor 390-391
CreatingaCustomCellType 391-395
CustomizingInteractioninCells 396
UsingEditModeandFocus 396
UnderstandingEditModeinaCell 396-397
LockingaCell 397-399
AllowingtheDisplayofButtonsinaCell 399-400
Spread Windows Forms Developer’s Guide 11
Copyright © GrapeCity, Inc. All rights reserved.
CustomizingtheFocusIndicatorforaCell 400-403
UsingDragOperationstoFillCells 403
FillingCellswithDragandDrop 403-404
FillingCellswithDragandFill 404-408
FillingCellswithDragandMove 408
UsingVisibleIndicatorsintheCell 408
DisplayingTextTipsinaCell 408-410
AddingaNotetoaCell 410-413
PreventingaCellfromHavingFocus 413
GettingInformationofaClickedCell 413-414
DisplayingErrorIconsinCellsorRows 414-415
UsingConditionalFormattingofCells 415
CreatingConditionalFormattingwithRules 415-416
ColorScaleRules 416-417
DataBarRule 417-419
HighlightingRules 419-421
IconSetRule 421-422
Top,Bottom,orAverageRules 422-423
SettingupConditionalFormattingofaCell 423-426
ManagingFormulasinCells 426
PlacingaFormulainCells 426-428
SpecifyingaCellReferenceinaFormula 428-430
SpecifyingaSheetReferenceinaFormula 430-431
UsingaCircularReferenceinaFormula 431-432
NestingFunctionsinaFormula 432-433
RecalculatingandUpdatingFormulasAutomatically 433-434
FindingaValueusingGoalSeek 434-435
AllowingtheUsertoEnterFormulas 435-436
CreatingandUsingaCustomName 436-437
Spread Windows Forms Developer’s Guide 12
Copyright © GrapeCity, Inc. All rights reserved.
CreatingandUsingaCustomFunction 437-440
UsingtheAdditionalSpreadControls 440
SettinguptheFormulaTextBox 440-442
SettinguptheFormulaProvider 442-443
SettinguptheNameBox 443-445
ManagingDataBinding 446
BindingtoData 446
BindingSpreadtoanExternalDataSet 446-447
BindingaCellRangeinSpreadtoanExternalDataSource 447-449
BindingaCellRangeinSpreadasaDataSourcetoanExternalControl 449-451
CustomizingColumnandFieldBinding 451-454
BindingaComboBoxtoaDataReader 454-455
AddingtoBoundData 455
AddingaRowtoaBoundSheet 455-456
AddinganUnboundRowtotheSheet 456-458
AddinganUnboundColumntoaBoundSheet 458-459
CustomizingDataBinding 459
CustomizingColumnHeadersforBoundSheets 459-461
CustomizingCellTypesforBoundSheets 461-463
WorkingwithHierarchicalDataDisplay 463-469
CreatingaHierarchicalDisplayManually 469-471
CreatingCustomHierarchyIcons 471
Tutorial:BindingtoaCorporateDatabase 471
AddingSpreadtoaDataBindProject 471
SettinguptheDatabaseConnection 471-472
SpecifyingtheDatatoUse 472-473
CreatingtheDataSet 473-474
BindingSpreadtotheDatabase 474
ImprovingtheDisplaybyChangingtheCellType 474-475
Spread Windows Forms Developer’s Guide 13
Copyright © GrapeCity, Inc. All rights reserved.
ManagingDataonaSheet 476
PlacingandRetrievingData 476
HandlingDataUsingSheetMethods 476-479
HandlingDataUsingCellProperties 479-480
RepeatedlyFillingaRangeofCellswithCopiedCells 480-481
ValidatingUserInput 481-485
RearrangingDataonaSheet 485
CopyingDataonaSheet 485
MovingDataonaSheet 485-486
SwappingDataonaSheet 486-487
RemovingDatafromaSheet 487-488
ImprovingPerformancebySuspendingtheLayout 488-491
ManagingKeyboardInteraction 492
UnderlyingKeystrokeProcessing 492-493
FactorsofKeyboardMapUsage 493-495
DefaultKeyboardNavigation 495-501
DefaultKeyboardMaps 501-502
DefaultMapforExcelCompatibility 502-503
DefaultMapforNormalandWhenFocused 503
DefaultMapforNormalandWhenAncestorOfFocused 503-505
DefaultMapforReadOnlyandWhenFocused 505
DefaultMapforReadOnlyandWhenAncestorOfFocused 505-506
DefaultMapforRowModeandWhenFocused 506
DefaultMapforRowModeandWhenAncestorOfFocused 506-507
DefaultMapforSingleSelectandWhenFocused 507
DefaultMapforSingleSelectandWhenAnscestorFocused 507-508
DefaultMapforMultiSelectandWhenFocused 508
DefaultMapforMultiSelectandWhenAncestorOfFocused 508
DefaultMapforExtendedSelectandWhenFocused 508
Spread Windows Forms Developer’s Guide 14
Copyright © GrapeCity, Inc. All rights reserved.
DefaultMapforExtendedSelectandWhenAncestorOfFocused 508-509
DeactivatingtheDefaultKeyboardMap 509-510
ChangingtheDefaultKeyboardMap 510-511
UsingInputMapswithActionMaps 511-515
CustomizingtheInputMaps 515-517
ChanginganInputMapforaChildView 517-520
UsingtheExcelCompatibilityInputMaps 520
SavingandLoadingMapFiles 520-521
ManagingEventsfromUserActions 522
ClickingActions 522-525
SelectingActions 525-526
EnteringDataActions 526
Sheet-LevelActions 526-527
InteractivityActions 527
ShapeActions 527
PrintActions 527-528
ManagingFileOperations 529
SavingDatatoaFile 529
SavingtoaSpreadXMLFile 529-530
SavingtoanExcelFile 530-531
SavingtoaTextFile 531-532
SavingtoanHTMLTable 532-533
SavingSpreadsheetDatatoSimpleXML 533-534
OpeningExistingFiles 534
OpeningaSpreadXMLFile 534-535
OpeninganExcelFile 535-536
OpeningaSpreadCOMFile 536-537
OpeningaCustomTextFile 537-538
UsingSerialization 538
Spread Windows Forms Developer’s Guide 15
Copyright © GrapeCity, Inc. All rights reserved.
ImplementingaSerializerClass 538-544
ParsingFormulasinCustomXMLDeserialization 544
SavingandLoadingaSkin 544-545
SavingaSkin 545
LoadingaSkin 545-546
ManagingPrinting 547
SpecifyingWhattoPrint 547
PrintinganEntireSheet 547-548
PrintingtoPDF 548-550
PrintingaChildViewofaHierarchicalDisplay 550
PrintingParticularPages 550-552
PrintingthePortionoftheSheetwithData 552-553
PrintingaRangeofCellsonaSheet 553-555
PrintinganAreaoftheSheet 555-556
PrintingaSheetwithCellNotes 556-557
PrintingaSheetwithShapes 557-558
CustomizingtheAppearanceofthePrinting 558
UnderstandingthePrintingOptions 558-563
CustomizingthePrintJobSettings 563-564
CustomizingthePrintedPageLayout 564-565
CustomizingthePrintedPageHeaderorFooter 565-570
RepeatingRowsorColumnsonPrintedPages 570-571
AddingaPageBreak 571-572
AddingaWatermarktoaPrintedPage 572-573
OptimizingthePrinting 573
OptimizingthePrintingUsingRules 573-576
OptimizingthePrintingUsingSize 576
DisplayingDialogsforUsers 576-577
DisplayingaPrintDialogfortheUser 577
Spread Windows Forms Developer’s Guide 16
Copyright © GrapeCity, Inc. All rights reserved.
DisplayinganAbortMessagefortheUser 577
ProvidingaPreviewofthePrinting 578-579
WorkingwiththeChartControl 580
UnderstandingCharts 580
ChartUserInterfaceElements 580-581
ChartObjectModel 581-582
ChartTypesandViews 582-584
PlotTypes 584
YPlotTypes 584-585
AreaCharts 585-587
BarCharts 587-590
LineCharts 590-591
MarketData(High-Low)Charts 591-593
PointCharts 593-594
StripeCharts 594-595
XYPlotTypes 595
XYBubbleCharts 595-596
XYLineCharts 596
XYPointCharts 596-597
XYStripeCharts 597
XYZPlotTypes 597-598
XYZPointCharts 598-599
XYZLineCharts 599-600
XYZSurfaceCharts 600-601
XYZStripeCharts 601
PiePlotTypes 601
DoughnutCharts 601-602
PieCharts 602
PolarPlotTypes 602-603
Spread Windows Forms Developer’s Guide 17
Copyright © GrapeCity, Inc. All rights reserved.
PolarPointCharts 603-604
PolarLineCharts 604-605
PolarAreaCharts 605-606
PolarStripeCharts 606
RadarPlotTypes 606-607
RadarPointCharts 607-608
RadarLineCharts 608-609
RadarAreaCharts 609
RadarStripeCharts 609-610
DataPlotTypes 610-611
PlotsandSeries 611-613
Walls 613-614
AxisandOtherLines 614-615
FillEffects 615-618
ChartLineStyle 618-620
ElevationandRotation 620-621
Lighting,Shapes,andBorders 621-623
Size-Height,Width,andDepth 623-624
Labels 624-625
Legends 625-626
CreatingCharts 626
CreatingPlotTypes 626-627
CreatingaYPlot 627-629
CreatinganXYPlot 629-631
CreatinganXYZPlot 631-634
CreatingaPiePlot 634-636
CreatingaPolarPlot 636-639
CreatingaRadarPlot 639-642
CombiningPlotTypes 642-644
Spread Windows Forms Developer’s Guide 18
Copyright © GrapeCity, Inc. All rights reserved.
ConnectingtoData 644
UsingaBoundDataSource 644-646
UsinganUnboundDataSource 646
UsingRawandRepresentedData 646-647
SavingorLoadingaChart 647-648
UsingtheChartDesigner 648-649
OpeningtheChartDesigner 649-650
CreatingaChartControl 650-653
ChartCollectionEditors 653
LabelCollectionEditor 653-654
LegendCollectionEditor 654
PlotCollectionEditor 654-655
LightCollectionEditor 655-656
SeriesCollectionEditor 656
ChartDesignerToolbar 656-657
UsingtheChartControl 657
AddingaChartControl 657-664
ChangingChartOptions 664-666
UsingtheChartDesigner 666-667
BindingtheChartControl 667-669
AllowingtheUsertoChangetheChart 669-670
AddingaContextMenu 671
UsingTouchSupportwiththeComponent 672
UnderstandingTouchSupport 672
UnderstandingTouchGestures 672
UnderstandingTouchMessages 672
UsingTouchSupport 672-673
UsingaTouchKeyboard 673-674
UsingtheTouchMenuBar 674-676
Spread Windows Forms Developer’s Guide 19
Copyright © GrapeCity, Inc. All rights reserved.
UsingTouchSupportwithAutoFit 676
UsingTouchSupportwithCellNotes 676
UsingTouchSupportwithCharts 676-677
UsingTouchSupportwithClipboardOperations 677
UsingTouchSupportwithDragandFill 677-679
UsingTouchSupportwithDrop-DownElements 679-680
UsingTouchSupportwithEditableCells 680-681
UsingTouchSupportwithInputManCells 681-684
UsingTouchSupportwithFiltering 684
UsingTouchSupportwithGrouping 684-685
UsingTouchSupportwithRangeGrouping 685-686
UsingTouchSupportwhenMovingColumnsorRows 686-688
UsingTouchSupportwhenResizingColumnsorRows 688-689
UsingTouchSupportwithScrolling 689-690
UsingTouchSupportwithSelections 690-692
UsingTouchSupportwithShapes 692
UsingTouchSupportwhenSorting 692-693
UsingTouchSupportwithViewports 693
UsingTouchSupportwiththeTabStrip 693
UsingTouchSupportwithZooming 693-694
2. Index 695-749
Spread Windows Forms Developer’s Guide 20
Copyright © GrapeCity, Inc. All rights reserved.
Getting Started
ThistopicdescribeshowtogetstartedwiththeSpreadcomponent.Itincludes:
HandlingInstallationWorkingwiththeComponentUnderstandingtheSpreadWizardGettingMorePracticeTutorial:CreatingaCheckbookRegister
Formorein-depthexplanationoftheproduct,refertoUnderstandingtheProduct.
Handling Installation
Thefollowingtasksinvolveinstallingandredistributingtheproduct:
InstallingtheProductLicensingaTrialProjectafterInstallationEnd-UserLicenseAgreementCreatingaBuildLicenseHandlingRedistributionProductRequirementsUsingWindowsRegionalSettingsorOptionsUsingSatelliteAssembliesforLanguages
Installing the Product
InstallationinstructionsandalistofinstalledfilesforSpreadWindowsFormsisprovidedintheReadMefilethataccompaniesthisproduct.ToviewtheReadMefile,dooneofthefollowing:
1. FromtheStartmenuchoosePrograms->GrapeCity->Spread.NET11->SpreadWindowsForms->SpreadWindowsFormsReadMe.SelecttheReadMeundertheGrapeCitynameontheStartscreenwithMicrosoftWindows8,8.1,or10.
2. Ifyouperformedadefaultinstallation,inWindowsExplorerbrowseto\GrapeCity\Spread.NET11\Docs\WindowsFormsundertheprogramfilesdirectoryandthendouble-clickthereadme.chmfile.
YoucanalsoaccesstheReadMeonthewebsite.
Licensing a Trial Project after Installation
TolicenseWindowsFormsprojectsmadewiththetrialversiondothefollowing:
1. EnsurethatSpreadislicensedonthemachinebyfollowingtheinstallationstepsintheReadMeonthewebsite.2. OpentheprojectinMicrosoftVisualStudio.3. OpentheVisualStudioBuildmenuandselectRebuildSolution.4. Theexecutableapplicationisnowlicensedandnonagscreensorevaluationbannersappearwhenyourunit.You
candistributetheapplicationtounlicensedmachinesandnonagscreensorevaluationbannersappear.
Ifyouhaveinstalledatrialversionoftheproduct,youcanlicensetheproductusingtheproductsplashscreenintheMicrosoftVisualStudioproject.
Spread Windows Forms Developer’s Guide 21
Copyright © GrapeCity, Inc. All rights reserved.
End-User License Agreement
TheGrapeCitylicensinginformation,includingtheGrapeCityend-userlicenseagreements,frequentlyaskedlicensingquestions,andtheGrapeCitylicensingmodel,isavailableonlineathttps://www.grapecity.com/en/licensing/spreadandhttps://www.grapecity.com/en/legal/eula.
Creating a Build License
Youcancreateabuildlicensetouseonabuildmachine.
Licensesarebuiltusingthelicensecompilertool(lc.exe)toproduceaspecialresourcefilewiththe.licensesfileextension.VisualStudioVB.NETandC#projectsautomaticallyhandlecompilingthelicenses.licxintheprojecttoproducethe.licensesresourcefile,whichislinkedintothetargetexecutable.Thecomponents’run-timelicensekeysinthatlicensesresourcefileareloadedandverifiedwhenthefirstinstanceofeachcomponentwiththeLicenseProviderattributeiscreatedintheapplication.Youcanremovethelicenses.licxfromyourVisualStudioprojectandaddthe.licensesresourceinitsplaceusingthefollowingsteps:
1. Buildtheprojectusingthelicensedcomponentsonadevelopermachinewhichislicensedfordevelopmentwithallthecomponentsreferencedintheproject(thiscreatesthe.licensesresource).
2. Findthelicenses.licxintheSolutionExplorerwindow.YoucanusetheShowAllFilestoolbarbuttontoseeitorexpandthePropertiesfolder.
3. Right-clickthelicenses.licxintheSolutionExplorerwindow,andthenselectExcludeFromProject.
4. UseWindowsExplorer(outsideVisualStudio)tofindthe.licensesfileintheobj\{configuration}folder(obj\Debugorobj\Release).Thefileshouldhavethename{target}.{ext}.licenses(forexample:project1.exe.licenses).
5. Copythatfiletotheprojectfolderandrenameittoremovethetargetname(renameitfrom{target}.{ext}.licensesto{ext}.licenses).Forexample:project1.exe.licensestoexe.licenses.
6. IntheVisualStudioSolutionExplorerwindow,findthe{ext}.licenses(youmightneedtorefreshthewindow),thenright-clickthefileandselectIncludeInProject.
Spread Windows Forms Developer’s Guide 22
Copyright © GrapeCity, Inc. All rights reserved.
7. ChangetheBuildActionforthe{ext}.licensesfromContenttoEmbeddedResource.
8. Theprojectcannowbebuiltwithoutrequiringadeveloperlicenseonthemachine,sincethelicensehasalreadybeenbuiltandlinkedintotheproject.
Notethefollowingrestrictions:
Thelicensesresourcecontainsthenameofthetargetmoduleencodedinitscontents,sothatlicensesresourceisspecifictothatparticularproject.Thestepsdescribedabovewillnotbypassanypartofthedesign-timelicenseenforcement.Thedeveloperlicenseisstillrequiredtoopenformscontaininginstancesofthelicensedcontrols.Ifthelicensedcomponentsintheprojectchange,thenspecialcareshouldbetaken.Thelicenses.licxshouldbeaddedbacktotheprojectfirst,sothatitdoesnotgetrecreated(empty)byVisualStudioandcausetypereferences(andembeddedlicensesintheresource)tobelost.Afterthenewlicensedcomponentsareaddedorchangedinthelicx,theabovestepsshouldberepeated.Theabovestepsonlyapplyfor.NETmanagedcodeapplicationswhichusethestandard.NETFrameworkcomponentlicensingmodel(ActiveXcontrollicensinginmanaged.NETapplicationsdoesnotusethismechanism).
Handling Redistribution
WhenyoudeployapplicationsthatyouhavedevelopedusingSpreadWindowsForms,yourusers'systemsmustmeet
Spread Windows Forms Developer’s Guide 23
Copyright © GrapeCity, Inc. All rights reserved.
thefollowingrequirementsandyoumustdistributethefileslistedinthefollowingsections:
SystemRequirements
Yourusers'systemsmustmeetthefollowingrequirements:
Operating SystemMustbeoneofthefollowing:
MicrosoftWindows98MicrosoftWindows98SEMicrosoftWindowsMEMicrosoftWindows2000(SP3)MicrosoftWindowsServer2003MicrosoftWindowsServer2008MicrosoftWindowsServer2012R2MicrosoftWindowsXP(SP2)MicrosoftWindowsVistaMicrosoftWindows7MicrosoftWindows8MicrosoftWindows8.1MicrosoftWindows10
SoftwareYoumusthavetheMicrosoft.NETFrameworkinstalled.
FilestoDistribute
Youmustdistributethefollowingfilestoyourusers'systems:
ThefollowingassembliesthatcomewithSpreadWindowsForms:FarPoint.CalcEngine.dllFarPoint.Excel.dllFarPoint.PluginCalendar.WinForms.dllFarPoint.Win.dllFarPoint.Win.Spread.dllFarPoint.Localization.dll
InstallationforyourapplicationmustcopytheseDLLsfromtheSpreadWindowsFormsdirectorytothedirectorywheretheapplication'sexecutablefileresidesorinstallthemintheglobalassemblycache(GAC).FormoreinformationontheGAC,refertotheMicrosoftVisualStudio.NETand.NETFrameworkdocumentation.
The.NETFrameworkredistributablepackage,iftheusersdonothavethe.NETFrameworkontheirsystems.Formoreinformationonthispackage,refertothe.NETFrameworkdocumentation.IfyouusetheinknotationfeatureinyourprojectthenyouwillalsoneedtodistributetheFarPoint.Win.Ink.dll.ThisDLLwouldneedtobeinstalledtothedirectorywheretheapplication'sexecutablefileresidesorbeinstalledintheglobalassemblycache(GAC).ThisalsorequirestheruntimecomponentsoftheMicrosoftTabletPCSDK.TheFarPoint.Win.Inkassemblyiscurrentlybuiltwithversion1.7oftheMicrosoftTabletPCSDK.IfyouusethetextrendererfeatureinyourprojectthenyouwillalsoneedtodistributetheFarPoint.Win.TextRenderer.dll.ThisDLLwouldneedtobeinstalledtothedirectorywheretheapplication'sexecutablefileresides.Thisfeatureisonlyavailablewiththe.NET2.0Framework.IfyouusetheexporttoPDFfeatureinyourprojectthenyouwillalsoneedtodistributetheFarPoint.PDF.dll.IfyouusetheexporttoHTMLfeatureinyourprojectthenyouwillalsoneedtodistributethe
Spread Windows Forms Developer’s Guide 24
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Spread.Html.dllandtheSystem.Web.dll.IfyouuseaSpreaddesignerdialogatruntimethenyoualsoneedtodistributetheFarPoint.Win.Spread.Design.dll.IfyouusethechartcontrolinyourprojectthenyouneedtodistributetheFarPoint.Win.Chart.dll.
HostingtheControlonaWebPage
IfyouarehostingtheSpreadWindowsFormscontrolasausercontrolonaWebpageinMicrosoftInternetExplorer(IE),makethesesecuritypermissionadjustments:
1. InIE,selectTools->InternetOptions->SecurityandselectTrustedSites.ClicktheSitesbuttonandaddtheWebsitewhereyourusercontrolresides(forexample,http://localhost).
2. InWindows,selectStart->Settings->ControlPanelandselectAdministrativeTools.SelectMicrosoft.NETFrameworkConfiguration.Inthe.NETFrameworkConfigurationwindow,selectRuntimeSecurityPolicyandclickAdjustZoneSecurity.IntheAdjustZoneSecurityWizard,answerthefirstscreen(whichcomputeritappliesto)andinthenextscreen,clickTrustedSitesandslidetheindicatortogivethatzoneFullTrust.FinishthewizardbyclickingNext.
Product Requirements
Developingapplicationswiththe.NET4.0versionofSpreadWindowsForms
Fordevelopingapplicationswiththe.NET4.0versionofSpreadWindowsForms,youmusthavethefollowingsystemandsoftwarespecifications:
Operating SystemOneofthefollowing:
MicrosoftWindows2000Professional(SP4)
MicrosoftWindows2000Server
MicrosoftWindows2003Server(SP1)
MicrosoftWindowsServer2012R2
MicrosoftWindows2008
MicrosoftWindowsXP(SP2)
MicrosoftWindowsVista
MicrosoftWindows7
MicrosoftWindows8
MicrosoftWindows8.1
MicrosoftWindows10
SoftwareThereleaseversionoftheMicrosoft.NET4.0Frameworkorlater.
Theseareminimumrequirementstoruntheproduct.
IfyouwanttotakeadvantageoftheinkcapabilitiesofSpreadWindowsForms,youwillneedtoinstalltheruntimecomponentsoftheMicrosoftTabletPCSDK.TheFarPoint.Win.Inkassemblyiscurrentlybuiltwithversion1.7oftheMicrosoftTabletPCSDK.
Spread Windows Forms Developer’s Guide 25
Copyright © GrapeCity, Inc. All rights reserved.
Using Windows Regional Settings or Options
TheSpreadcomponentreadstheWindowsregionalsettingsoroptions,whicharesetbytheuserthroughtheControlPanel,butduetovariationsinhowWindowshandlesthosesettings,yourusermightexperienceunexpectedresults.
IngeneralinWindowsoperatingsystems,theSpreadcomponentdoesnotrecognizechangesmadetotheWindowsregionalsettingsuntilyourestartyourdevelopmentenvironmentoryourapplicationorperformanyoperationthatunloadsandreloadsthecurrentassemblyanddependentassemblies.Thisisbecausehandlingtheregionalsettingsisveryprocessorintensive.Tooptimizeperformancethesesettingsarenotcheckedeachtimeasimpleoperationisperformed.
InmostWindowsoperatingsystems,theregionaloptionsarereadfromthesystemregistry.Incertainsituations,Windowsdoesnotclearpreviousregionaloptionswhenreadingchangesfromthesystemregistry.Beawareofthiswhenworkingwithregionalsettings.
Using Satellite Assemblies for Languages
Youcanplaceresourcesfordifferentlanguagesusingsatelliteassemblies.Theassemblyisthenloadedinmemoryiftheuserviewstheapplicationinthatlanguage.Theresourcesmustbeplacedinspecificlocationssotheycanbelocatedandused.Iftheresourcecannotbefound,thedefaultresourceisused.
Usethefollowingstepstoaddalanguageresource:
1. Findtheresourcesinthelocalizationfolderundertheinstalledbinfolder(forexample,ko-KRorzh-CN).
2. CopythefoldertothebinfolderoftheapplicationorinstalltotheGAC.
3. SetthecurrentUIculturetothelanguage(forexample,Korean)usingthefollowingcode.System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("ko-KR")
Ifyouwishtousetheresourceatdesigntime,installthesatelliteassembliestotheGACandselectthelanguageinVisualStudio.NET.
Thestand-alonedesignerusestheresourcesintheGACiftheoperatingsystemandtheGACresourcesusethesamelanguage.Ifthelanguageisdifferent,thedefaultresourceisapplied(English).
Working with the Component
ThetasksinvolvedwithusingtheSpreadcomponentonaWindowsFormare:
AddingaComponenttoaVisualStudio2015or2017ProjectAddingaComponenttoaVisualStudio2013ProjectAddingaComponenttoaProjectUnderstandingPartsoftheComponentUsingSmartTagsDrop-DownUsingVerbsinthePropertiesWindowWorkingwithCollectionEditorsAddingSupportforHighDPISettings
Adding a Component to a Visual Studio 2015 or 2017 Project
UsethefollowingstepstoaddthecomponenttoaprojectinVisualStudio.NET.
ThefirststepistocreateanewprojectinVisualStudio.NET,andtoaddaSpreadWindowsFormscomponenttotheproject.
Spread Windows Forms Developer’s Guide 26
Copyright © GrapeCity, Inc. All rights reserved.
1. StartVisualStudio.NET.2. FromtheFilemenu,chooseNew,Project.3. IntheNewProjectdialog,intheInstalledarea,selectaprojecttypedependingonthelanguageenvironment
inwhichyouaredeveloping.Forexample,chooseWindowsunderVisualBasic.a. ChoosethetypeofprojectsuchasWindowsFormsApplication.b. IntheNamebox,typethenameofthenewproject.ThedefaultisWindowsApplication1forthefirst
WindowsFormsapplication.c. IntheLocationbox,leavethelocationpathasthedesignatedpath,orclickBrowsetochangethepathtoanewdirectory.
d. ClickOK.IfyourprojectdoesnotdisplaytheSolutionExplorer,fromtheViewmenu,chooseSolutionExplorer.
4. IntheSolutionExplorer,right-clickontheformname,Form1.ChooseRenamefromthepop-upmenu,thentypethenewformnameyoupreferforthenewformname.
Usethefollowingstepstoaddthecomponenttothetoolboxifthecomponentisnotlistedinthetoolbox.
1. IftheToolboxisnotdisplayed,fromtheViewmenuchooseToolbox.2. OncetheToolboxisdisplayed,lookintheGrapeCitySpreadcategory(orinanyothercategoryifyouhave
installedSpreadandplacedthetoolboxiconinadifferentcategory).3. IftheSpreadcomponentisnotintheToolbox:
a. Right-clickintheToolbox,andfromthepop-upmenuchooseChooseItems.b. IntheChooseToolboxItemsdialog,clickthe.NETFrameworkComponentstab.c. Inthe.NETFrameworkComponentstab,theFpSpreadcomponent(intheFarPoint.Win.Spreadnamespace)shouldbedisplayedinthelistofcomponents.SelecttheSpreadcomponentcheckboxandclickOK.SelectfpChart(FarPoint.Win.Chartnamespace)forthechartcontrol.IftheSpreadcomponentisnotdisplayedinthelistofcomponents,clickBrowseandbrowsetotheinstallationpathfortheSpreadWindowsFormscomponent.Oncethere,selecttheFarPoint.Win.Spread.dllandclickOpen.TheSpreadcomponentisnowdisplayedinthelistofcomponents.SelectitandclickOK.SelectFarPoint.Win.Chart.dllforthechartcontrol.
d. Youcantestthatthecomponenthasbeenaddedbyopeningaprojectandinsertingthecomponent.
ThenextstepistoaddtheSpreadcomponenttoaproject.
1. Withanopenproject,intheToolboxunderGrapeCitySpread(orwhatevercategorytowhichyouaddedit),selecttheFpSpreadcomponent.
2. OnyourWindowsFormspage,drawaSpreadcomponentbydraggingarectanglethesizethatyouwouldliketheinitialcomponentorsimplydouble-clickonthepage.TheSpreadcomponentappears.TheSpreadDesigneralsoappearsbydefault.Closethedesigner.
Yourprojectshouldlooksimilartothefollowingpicture.
Spread Windows Forms Developer’s Guide 27
Copyright © GrapeCity, Inc. All rights reserved.
YouhaveaddedtheSpreadcomponenttotheproject.
Adding a Component to a Visual Studio 2013 Project
Ifyouarenewtothe.NETplatform,youmightbeunfamiliarwithhowtostartanewprojectusingacomponent.TousetheSpreadWindowsFormsproduct,youneedtoaddthecomponenttoaprojectinVisualStudio.NET.
ThefirststepistocreateanewprojectinVisualStudio.NET,andtoaddaSpreadWindowsFormscomponenttotheproject.
1. StartVisualStudio.NET.2. FromtheFilemenu,chooseNew,ProjectorselectNewProject...underStart.3. IntheNewProjectdialog,intheInstalledarea,selectaprojecttypedependingonthelanguageenvironmentin
whichyouaredeveloping.Forexample,chooseWindowsunderVisualBasic.
Spread Windows Forms Developer’s Guide 28
Copyright © GrapeCity, Inc. All rights reserved.
a. ChoosethetypeofprojectsuchasWindowsFormsApplication.b. IntheNamebox,typethenameofthenewproject.ThedefaultisWindowsApplication1forthefirst
WindowsFormsapplication.c. IntheLocationbox,leavethelocationpathasthedesignatedpath,orclickBrowsetochangethepathtoanewdirectory.
d. ClickOK.IfyourprojectdoesnotdisplaytheSolutionExplorer,fromtheViewmenu,chooseSolutionExplorer.
4. IntheSolutionExplorer,right-clickontheformname,Form1.ChooseRenamefromthepop-upmenu,thentypethenewformnameyoupreferforthenewformname.
ThenextstepistoaddtheSpreadcomponenttothetoolbox.Thisonlyhastobedoneonce.
1. IftheToolboxisnotdisplayed,fromtheViewmenuchooseToolbox.2. OncetheToolboxisdisplayed,lookintheGrapeCitySpreadcategory(orinanyothercategoryifyouhaveinstalled
Spreadandplacedthetoolboxiconinadifferentcategory).3. IftheSpreadcomponentisnotintheToolbox:
a. Right-clickintheToolbox,andfromthepop-upmenuchooseChooseItems.b. IntheChooseToolboxItemsdialog,clickthe.NETFrameworkComponentstab.c. Inthe.NETFrameworkComponentstab,theFpSpreadcomponent(intheFarPoint.Win.Spreadnamespace)shouldbedisplayedinthelistofcomponents.SelecttheSpreadcomponentcheckboxandclickOK.SelectfpChart(FarPoint.Win.Chartnamespace)forthechartcontrol.IftheSpreadcomponentisnotdisplayedinthelistofcomponents,clickBrowseandbrowsetotheinstallationpathfortheSpreadWindowsFormscomponent.Oncethere,selecttheFarPoint.Win.Spread.dllandclickOpen.TheSpreadcomponentisnowdisplayedinthelistofcomponents.SelectitandclickOK.SelectFarPoint.Win.Chart.dllforthechartcontrol.
Spread Windows Forms Developer’s Guide 29
Copyright © GrapeCity, Inc. All rights reserved.
d. Youcantestthatthecomponenthasbeenaddedbyopeningaprojectandinsertingthecomponent.
ThenextstepistoaddtheSpreadcomponenttoaproject.
1. Withanopenproject,intheToolboxunderGrapeCitySpread(orwhatevercategorytowhichyouaddedit),selecttheFpSpreadcomponent.
2. OnyourWindowsFormspage,drawaSpreadcomponentbydraggingarectanglethesizethatyouwouldliketheinitialcomponentorsimplydouble-clickonthepage.TheSpreadcomponentappears.TheSpreadDesigneralsoappearsbydefault.Closethedesigner.
Yourprojectshouldnowlooksimilartothepictureshownhere.
YouhaveaddedtheSpreadcomponenttotheproject.
Adding a Component to a Project
Ifyouarenewtothe.NETplatform,youmightbeunfamiliarwithhowtostartanewprojectusingacomponent.TousetheSpreadWindowsFormsproduct,youneedtoaddthecomponenttoaprojectinVisualStudio.NET.
ThefollowinggeneralstepsareforMicrosoftVisualStudio2012orearlier.
ThefirststepistocreateanewprojectinVisualStudio.NET,andtoaddaSpreadWindowsFormscomponenttotheproject.
1. StartVisualStudio.NET.2. FromtheFilemenu,chooseNew,Project.3. IntheNewProjectdialog,intheProjectTypearea,selectaprojecttypedependingonthelanguage
environmentinwhichyouaredeveloping.Forexample,intheProjectTypeslist,chooseVisualC#Projects.4. IntheNewProjectdialog,
a. IntheProjectTypeslist,chooseVisualC#ProjectsorVisualBasicProjectsdependingonthelanguageyouareusing.
b. IntheTemplateslist,chooseWindowsApplication.c. IntheNamebox,typethenameofthenewproject.ThedefaultisWindowsApplication1forthefirstWindowsFormsapplication.
Spread Windows Forms Developer’s Guide 30
Copyright © GrapeCity, Inc. All rights reserved.
d. IntheLocationbox,leavethelocationpathasthedesignatedpath,orclickBrowsetochangethepathtoanewdirectory.
e. ClickOK.IfyourprojectdoesnotdisplaytheSolutionExplorer,fromtheViewmenu,chooseSolutionExplorer.
5. IntheSolutionExplorer,right-clickontheformname,Form1.ChooseRenamefromthepop-upmenu,thentypethenewformnameyoupreferforthenewformname.
ThenextstepistoaddtheSpreadcomponenttotheToolbox.Thisonlyhastobedoneonce.
1. IftheToolboxisnotdisplayed,fromtheViewmenuchooseToolbox.2. OncetheToolboxisdisplayed,lookintheGrapeCitySpreadcategory(orinanyothercategoryifyouhave
installedSpreadandplacedthetoolboxiconinadifferentcategory).3. IftheSpreadcomponentisnotintheToolbox,right-clickintheToolbox,andfromthepop-upmenuchooseCustomizeToolbox,Add/RemoveItems,orChooseItems(dependingontheversionofVisualStudio).
4. IntheCustomizeToolboxdialog,clickthe.NETFrameworkComponentstab.5. Inthe.NETFrameworkComponentstab,theFpSpreadcomponent(intheFarPoint.Win.Spreadnamespace)shouldbedisplayedinthelistofcomponents.SelecttheFpSpreadcomponentcheckboxandclickOK.SelectfpChart(FarPoint.Win.Chartnamespace)forthechartcontrol.IftheSpreadcomponentisnotdisplayedinthelistofcomponents,clickBrowseandbrowsetotheinstallationpathfortheSpreadWindowsFormscomponent.Oncethere,selecttheFarPoint.Win.Spread.dllandclickOpen.TheSpreadcomponentisnowdisplayedinthelistofcomponents.SelectitandclickOK.SelectFarPoint.Win.Chart.dllforthechartcontrol.
6. Youcantestthatthecomponenthasbeenaddedbyopeningaprojectandinsertingthecomponent.
ThenextstepistoaddtheSpreadcomponenttoaproject.
1. Withanopenproject,intheToolboxunderWindowsForms(orwhatevercategorytowhichyouaddedit),selecttheSpreadcomponent.
2. OnyourWindowsFormspage,drawaSpreadcomponentbydraggingarectanglethesizethatyouwouldliketheinitialcomponentorsimplydoubleclickonthepage.TheSpreadcomponentappears.
Spread Windows Forms Developer’s Guide 31
Copyright © GrapeCity, Inc. All rights reserved.
Yourprojectshouldnowlooksimilartothepictureshownhere.
YouhaveaddedtheSpreadcomponenttotheproject.
Understanding Parts of the Component
TheSpreadcomponentismadeupofthespreadsheetthatdisplaysthedataalongwithscrollbarsand,ifmultiplesheets,sheettabsinatabstrip.ThefigurebelowshowsthemajorpartsoftheSpreadcomponent.Severalofthesecanbehidden,butthisshowsthedefaultdisplay.
Formoreinformationon... Referto...sheetcorner CustomizingtheSheetCornerAppearance
sheettabs CustomizingtheSheetNameTabsoftheComponent
scrollbars CustomizingtheScrollBarsoftheComponent
rowandcolumnheaders CustomizingtheAppearanceofHeaders
focusindicator(ofactivecell) CustomizingtheFocusIndicatorforaCell
selections CustomizingUserSelectionofData
activesheet WorkingwiththeActiveSheet
Using Smart Tags Drop-Down
Youcanperformanyofseveraltasks,launchvariouseditors,andsetvariouspropertiesfromthesmarttagsdrop-downavailablefromtheSpreadcomponentonaForminVisualStudio.NET.Thesmarttagisthearrowiconatthetop,rightedgeofthecontrol.TheSpreadtasksavailableinthesmarttagsaresummarizedbelow.
Spread Windows Forms Developer’s Guide 32
Copyright © GrapeCity, Inc. All rights reserved.
Task ExplanationorReferenceChooseDataSource RefertoManagingDataBinding.
EditSheets RefertoCustomizingtheIndividualSheetAppearanceandCustomizingSheetInteraction.
EditCells RefertoCustomizingtheAppearanceofaCellandCustomizingInteractioninCells.
ComponentName ThisisthenameoftheSpreadcomponent.
OperationMode RefertoSpecifyingWhattheUserCanSelect.
UserOptionsEditModePermanent
RefertoAllowingtheUsertoMoveRowsorColumns,AllowingtheUsertoZoomtheDisplayoftheComponent,FillingCellswithDragandDrop,
Spread Windows Forms Developer’s Guide 33
Copyright © GrapeCity, Inc. All rights reserved.
EditModeReplaceAllowColumnMoveAllowRowMoveAllowUserZoomAllowDragDropAllowDragFillAllowUserFormulas
FillingCellswithDragandFill,AllowingtheUsertoEnterFormulas,andUnderstandingEditModeinaCell.
AutoClipboard Thisallowstheshortcutkeystowork.
ClipboardOptions Thisdetermineswhatcanbecopiedandpasted.
VisualStyles Whethertoallowthevisualstyles.
EditSheetSkins Thiscanbeusedtoeditsheetskins.
EditNamedStyles Thiscanbeusedtoeditnamedstyles.
SpreadDesigner Thiscanbeusedtobringupthedesigner.
QuickStartWizard Thiscanbeusedtobringupthewizard.RefertoUnderstandingtheSpreadWizard.
AutoLaunchSpreadDesigner Thiscanbeuncheckedtopreventtheautolaunchofthedesigner.
DockinginParentContainer Thissetsthedockingtofill.
ProductVersion Versionoftheproduct.
Thesheettasksavailableinthesmarttagaresummarizedbelow.
Tasks DescriptionEditCells
ThisopenstheCellEditorandallowsyoutoeditvariouspropertiesoftheselectedcellorcellsofasheet.Formoreinformationonsettingcellproperties,refertoCustomizingtheAppearanceofaCell.
ResetSheet
Thisrestoresallthesettingsoftheselectedsheettotheirdefaultvalues.Formoreinformationonresettingproperties,refertoResettingPartsoftheInterface.
EditSkins
ThisopenstheSpreadSkinEditorandallowsyoutoeditvariouspropertiesoftheskinthatapplytothespreadsheet.Formoreinformationonmanagingskins,refertoCreatingaCustomSkinforaComponentandApplyingaSkintotheComponent.
EditCharts
ThisopenstheSpreadChartCollectionEditor.Formoreinformation,refertoSpreadChartCollectionEditor(on-linedocumentation).
Using Verbs in the Properties Window
YoucanlaunchvariouseditorsorresetvaluesfromtheverbsinthepropertywindowinVisualStudio.NETasaquickwayofhandlingsomesettings.Therearedifferentverbsavailabledependingontheitemselected.
Right-clickonthePropertieswindowandselectCommandstoseetheverbs.
Spread Windows Forms Developer’s Guide 34
Copyright © GrapeCity, Inc. All rights reserved.
ThefollowingimagedisplaysSpreadverbs.
ThefollowingtablesummarizestheSpreadcomponentverbs:
Verb DescriptionSpreadDesigner
ThisopenstheSpreadDesignerandallowsyoutoeditvariouspropertiesofmostofthespreadsheetanditspartsaswellastheoverallcomponent.FormoreinformationontheuseoftheSpreadDesigner,refertoSpreadDesignerGuide(on-linedocumentation).
ResetControl
ThisrestoresallthesettingsfortheSpreadcomponenttotheirdefaultvalues.Formoreinformationonresettingproperties,refertoResettingPartsoftheInterface.
EditSkins
ThisopenstheSpreadSkinEditorandallowsyoutoeditvariouspropertiesoftheskinthatapplytothespreadsheet.Formoreinformationonmanagingskins,refertoCreatingaCustomSkinfora
Spread Windows Forms Developer’s Guide 35
Copyright © GrapeCity, Inc. All rights reserved.
ComponentandApplyingaSkintotheComponent.
Thefollowingimagedisplaysthesheetverbs.
Thefollowingtablesummarizesthesheetverbs:
Verbs DescriptionEditCells
ThisopenstheCellEditorandallowsyoutoeditvariouspropertiesoftheselectedcellorcellsofasheet.Formoreinformationonsettingcellproperties,refertoCustomizingtheAppearanceofaCell.
ResetSheet
Thisrestoresallthesettingsoftheselectedsheettotheirdefaultvalues.Formoreinformationonresettingproperties,refertoResettingPartsoftheInterface.
EditSkins
ThisopenstheSpreadSkinEditorandallowsyoutoeditvariouspropertiesoftheskinthatapplytothespreadsheet.Formoreinformationonmanagingskins,refertoCreatingaCustomSkinforaComponentandApplyingaSkintotheComponent.
EditCharts
ThisopenstheSpreadChartCollectionEditor.Formoreinformation,refertoSpreadChartCollectionEditor(on-linedocumentation).
Working with Collection Editors
SeveralpropertiesthatappearinthePropertieswindowareassociatedwithcollections.Toviewandmodifythesesettings,clickontheBrowsebutton(...)andaseparateCollectionEditorwindowappears.ThisisthecasefortheNamedStyles('NamedStylesProperty'intheon-linedocumentation)propertyandtheSheets('SheetsProperty'intheon-linedocumentation)propertyintheSpreadcomponent.
Spread Windows Forms Developer’s Guide 36
Copyright © GrapeCity, Inc. All rights reserved.
Withthesecollectioneditors,youmustclickOKtoseetheresultsofachangetoasetting.(ThecollectioneditorsrelyonpartoftheMicrosoft.NETframeworkanddonothaveanApplybutton.)
Adding Support for High DPI Settings
SpreadsupportshighDPIsettingsprovidedthattheapplicationhashighDPIsupportenabled.
RefertoMicrosoft'swebsiteformoreinformationaboutenablingDPIsupportforyourapplication.
EnablingDPIsupportin.NET4.5.2
YoucanrefertothefollowingstepsforageneralexampleofhowtoenableDPIsupportin.NET4.5.2.
1. UsetheWindowsAPIwiththefollowingcode.
Codestatic class Program{ /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { SetProcessDPIAware(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } [System.Runtime.InteropServices.DllImport("user32.dll")] public extern static IntPtr SetProcessDPIAware();}
Note:TheSetProcessDPIAwareAPImustbecalledbeforeanywindowiscreated;otherwise,awindowcreatedbeforeusingthisAPIwillhavethewrongsizeandfont.
2. AddSpreadcode:
Code//add code in InitializeComponent() of cs filethis.fpSpread1.SpreadScaleMode = FarPoint.Win.Spread.ScaleMode.ZoomDpiSupport;this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
Spread Windows Forms Developer’s Guide 37
Copyright © GrapeCity, Inc. All rights reserved.
3. EnableWindowsFormsHighDPIsupportbyaddingcodetotheApp.config.
Code<?xml version="1.0" encoding="utf-8" ?><configuration> <appSettings> <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" /> </appSettings></configuration>
EnablingHDPIfor.NETFramework4.7
UsethefollowingstepstoenableDPIsupport.
1. Installthe.NET4.7Framework.2. Createanewwindowsformsapplication.3. AddanApp.configwiththefollowinginformationtotherootdirectoryoftheform(samedirectoryas
Program.cs).
Code<?xml version="1.0" encoding="utf-8"?><configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7"/> </startup> <System.Windows.Forms.ApplicationConfigurationSection> <add key="DpiAwareness" value="PerMonitorV2"/> <!-- Uncomment each value to disable the fixes one by one. --> <!-- <add key="Form.DisableSinglePassScalingOfDpiForms" value="true"/> <add key="ToolStrip.DisableHighDpiImprovements" value="true"/> <add key="CheckedListBox.DisableHighDpiImprovements" value="true"/> <add key="MonthCalendar.DisableHighDpiImprovements" value="true"/> <add key="AnchorLayout.DisableHighDpiImprovements" value="true"/> <add key="DataGridView.DisableHighDpiImprovements" value="true"/> --> </System.Windows.Forms.ApplicationConfigurationSection></configuration>
4. AddanApp.manifestwiththefollowinginformationtotherootdirectoryoftheform(samedirectoryasProgram.cs).
Code<?xml version="1.0" encoding="utf-8"?><assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"> <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <!-- UAC Manifest Options If you want to change the Windows User Account Control level replace the requestedExecutionLevel node with one of the following. <requestedExecutionLevel level="asInvoker" uiAccess="false" /> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Spread Windows Forms Developer’s Guide 38
Copyright © GrapeCity, Inc. All rights reserved.
<requestedExecutionLevel level="highestAvailable" uiAccess="false" /> Specifying requestedExecutionLevel element will disable file and registry virtualization. Remove this element if your application requires this virtualization for backwards compatibility. --> <requestedExecutionLevel level="asInvoker" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo> <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> <application> <!-- A list of the Windows versions that this application has been tested on and is is designed to work with. Uncomment the appropriate elements and Windows will automatically selected the most compatible environment. --> <!-- Windows 10 --> <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" /> </application> </compatibility> <!--<application xmlns="urn:schemas-microsoft-com:asm.v3"> <windowsSettings> <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware> </windowsSettings> </application>--> </assembly>
5. VerifythatProgram.cshasthefollowingsettings.
Codestatic class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } }
6. CheckthatForm1.designer.cshasthefollowingsettings.
Codethis.fpSpread1.SpreadScaleMode = FarPoint.Win.Spread.ScaleMode.ZoomDpiSupport;this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
Spread Windows Forms Developer’s Guide 39
Copyright © GrapeCity, Inc. All rights reserved.
Understanding the Spread Wizard
YoucanusetheSpreadWizardtoquicklyandeasilybinddata,setupthecolumnstructure,andcustomizetheappearanceofaspreadsheet.Seethefollowingtopicsformoreinformation:
StartingtheSpreadWizardUsingtheSpreadWizard
Starting the Spread Wizard
YoucanlaunchtheSpreadWizardfromtheSmartTagsontheFpSpreadcomponentontheforminVisualStudioasshowninthisfigure.Thesmarttagisthearrowiconatthetop,rightedgeofthecontrol.
Using the Spread Wizard
YoucanusetheSpreadWizardtobindtoadatasource,setcolumnproperties,settheoperationmode,specifytitles,selectaskin,andperformmanyothertasks.
Selectthemenuoptionofthefeatureyouwishtocustomize,locatedontheleftsideofthedialog.SelectthevariousoptionsforthatfeatureandthenclickNexttogotothenextstep.Whenyouarefinished,clickFinish.
Spread Windows Forms Developer’s Guide 40
Copyright © GrapeCity, Inc. All rights reserved.
Getting More Practice
IfyouneedmoretipsaboutcustomizingSpreadandtakingadvantageofitsmanyfeatures,wehaveprovidedtheseadditionalsourcesofinformationtohelpyougetstarted.
FindingtheDocumentationGettingTechnicalSupport
Finding the Documentation
ThereareseveraldifferentwaystoaccomplishthesameresultwhencreatingaWindowsFormspagewithaSpreadcomponent.Inthisdocumentation,theproceduresoftendescribemorethanoneway,includingusingthePropertieswindowinVisualStudio.NET,writingcodeincludingusingshortcutobjects,andusingtheSpreadDesigner.TheSpreadDesignersetspropertiesandcallsmethodsfortheSpreadcomponent,includingpropertiesnotavailableatdesigntimethroughVisualStudio.NET,withoutproducinganyeditablecode.
Eachofthesehasitsadvantagesanddisadvantages.Usingshortcutobjectsistheshortest,quickestwayofaddingcodeusingdotnotationandsettingapropertyofashortcutobject.Usingcodewithoutusingshortcutobjectsgenerallymeansdeclaringobjectsandsettingpropertiesforthem.
Spread Windows Forms Developer’s Guide 41
Copyright © GrapeCity, Inc. All rights reserved.
DocumentationProvided
TheSpreadWindowsFormsdocumentationprovidesintroductoryinformationabouttheproduct,conceptualinformation,how-totopics,andadetailedassemblyandformulafunctionreferenceinahelpfileandinPDFfiles.AdditionalinformationisprovidedintheReadmefile.
AccessingtheHelp
YoucanaccessthehelpthroughF1supportprovidedinVisualStudioNET.WhiletheSpreadcomponentoroneofitsmembershasfocus,pressF1todisplaytheSpreadWindowsFormshelp.
Youcanalsoaccessthehelpfileinastand-alonewindowbychoosingPrograms‑>GrapeCity‑>...->ProductNameandthenselectingthehelp.
DocumentationConventions
TheformatofthehelpissimilartothehelpprovidedforVisualStudio.NET.Referencematerialformembersprovidesmultiplelanguagereferenceforthemember.Youcanchangewhichlanguage'ssyntaxisdisplayedbyclickingtheLanguagesbuttoninthetitleofthetopic.
ListofHow-To’s
HereisalistoftheHowTo’s:
AddingaNotetoaCellAddingaRoworColumnAddingaSheetAllowingtheUsertoEnterFormulasAllowingtheUsertoAutomaticallySortRowsAllowingtheUsertoPerformaStandardSearchApplyingaSkintoaSheetCreatingaCustomSkinforaSheetCreatingandUsingaCustomFunctionCreatingandUsingaCustomNameCreatingAlternatingRowsCustomizingtheOutlineoftheComponentCustomizingtheInputMapsCustomizingtheScrollBarsoftheComponentCustomizingSplitBoxesCustomizingtheDimensionsoftheComponentCustomizingtheNumberofRowsorColumnsCustomizingViewportsCustomizingtheSelectionAppearanceCustomizingtheSheetCornerAppearanceDisplayingGridLinesonaSheetCustomizingtheSheetNameTabsoftheComponentDisplayingTextTipsinaCellLockingaCellNestingFunctionsinaFormulaOpeningExistingFiles
Spread Windows Forms Developer’s Guide 42
Copyright © GrapeCity, Inc. All rights reserved.
OptimizingthePrintingUsingRulesUsingAutomaticSortingPlacingaFormulainCellsPlacingChildControlsonaSheetPrintinganEntireSheetPrintingParticularPagesPrintingaRangeofCellsonaSheetPrintinganEntireSheetProvidingaPreviewofthePrintingRemovingaRoworColumnRemovingaSheetSavingDatatoaFileSearchingforDatawithCodeSettingtheBackgroundColorsforaSheetSettingtheRowHeightorColumnWidthSortingRows,Columns,orRangesSpecifyingaCellReferenceinaFormulaSpecifyingWhattheUserCanSelectUsingaCircularReferenceinaFormulaUsingDragOperationstoFillCellsWorkingwithEditableCellTypesWorkingwithGraphicalCellTypesWorkingwithSelections
Getting Technical Support
Ifyouhaveatechnicalquestionaboutthisproduct,consultthefollowingsources:
Helpandotherdocumentationfilesinstalledwiththeproduct.Forinstructionsforaccessingthehelpandotherdocumentation,seeFindingtheDocumentation.Productforumathttp://sphelp.grapecity.com/forums/forum/spreadsheets/
Ifyoucannotfindtheanswerusingthesesources,pleasecontactTechnicalSupportusingoneofthesemethods:
Website: http://sphelp.grapecity.com/
E-mail: [email protected]
Fax: (412)681-4384
Phone (412)681-4738
TechnicalSupportisavailablebetweenthehoursof9:00a.m.and5:00p.m.Easterntime,MondaythroughFriday.
Tutorial: Creating a Checkbook Register
ThefollowingtutorialwalksyouthroughcreatingaprojectinVisualStudio.NETusingtheSpreadWindowsFormscomponent.Bycreatingacheckbookregister,youwilllearnhowtomodifytheappearanceofaspreadsheet,workwithcelltypes,andaddsomeformulasforperformingcalculations.
Inthistutorial,themajorstepsare:
AddingSpreadtotheCheckbookProject
Spread Windows Forms Developer’s Guide 43
Copyright © GrapeCity, Inc. All rights reserved.
SettingUptheRowsandColumnsoftheRegisterSettingtheCellTypesoftheRegisterAddingFormulastoCalculateBalances
Adding Spread to the Checkbook Project
UsethefollowingstepstoaddSpreadtotheproject.
1. StartanewVisualStudio.NETproject.
2. Nametheprojectcheckbook.Nametheformintheprojectregister.
3. AddtheFpSpreadcomponenttoyourproject,andthenplacethecontrolontheform.
IfyoudonotknowhowtoaddtheFpSpreadcomponenttotheproject,completethestepsinAddingaComponenttoaProject.
GotoSettingUptheRowsandColumnsoftheRegistertocontinuethetutorial.
Setting Up the Rows and Columns of the Register
TheSpreadcontrolonyourformalreadyhasasheet,readyforyoutoconfigure.Inthisstep,youaregoingtosetupthecolumnsandcellsinthesheettoresembleacheckbookregister.
UsingCode
1. Double-clickontheforminyourprojecttoopenthecodewindow.2. IntheFormLoadevent,typethefollowingcode:
Thiscodesetsupthecontroltobe300pixelshighand763pixelswide,andthesheettohave8columnsand100rows.
Example
C#// Set up control and rows and columns in sheet.fpSpread1.Height = 330;fpSpread1.Width = 765;fpSpread1.Sheets[0].ColumnCount = 8;fpSpread1.Sheets[0].RowCount = 100;
VB' Set up control and rows and columns in sheet.FpSpread1.Height = 330FpSpread1.Width = 765FpSpread1.Sheets(0).ColumnCount = 8FpSpread1.Sheets(0).RowCount = 100
3. Nextsetupthecolumnstoaddcustomheadings.AddthefollowingcodebelowthecodeyouaddedinStep2:
Example
C#// Add text to column heading.
Spread Windows Forms Developer’s Guide 44
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.Sheets[0].ColumnHeader.Cells[0, 0].Text = "Check #";fpSpread1.Sheets[0].ColumnHeader.Cells[0, 1].Text = "Date";fpSpread1.Sheets[0].ColumnHeader.Cells[0, 2].Text = "Description";fpSpread1.Sheets[0].ColumnHeader.Cells[0, 3].Text = "Tax?";fpSpread1.Sheets[0].ColumnHeader.Cells[0, 4].Text = "Cleared?";fpSpread1.Sheets[0].ColumnHeader.Cells[0, 5].Text = "Debit";fpSpread1.Sheets[0].ColumnHeader.Cells[0, 6].Text = "Credit";fpSpread1.Sheets[0].ColumnHeader.Cells[0, 7].Text = "Balance";
VB' Add text to column heading.FpSpread1.Sheets(0).ColumnHeader.Cells(0, 0).Text = "Check #"FpSpread1.Sheets(0).ColumnHeader.Cells(0, 1).Text = "Date"FpSpread1.Sheets(0).ColumnHeader.Cells(0, 2).Text = "Description"FpSpread1.Sheets(0).ColumnHeader.Cells(0, 3).Text = "Tax?"FpSpread1.Sheets(0).ColumnHeader.Cells(0, 4).Text = "Cleared?"FpSpread1.Sheets(0).ColumnHeader.Cells(0, 5).Text = "Debit"FpSpread1.Sheets(0).ColumnHeader.Cells(0, 6).Text = "Credit"FpSpread1.Sheets(0).ColumnHeader.Cells(0, 7).Text = "Balance"
4. Nowsetupthecolumnwidthstoproperlydisplaytheheadingsandthedatayouwilladd.AddthefollowingcodebelowthecodeyouaddedinStep3:
Example
C#// Set column widths.fpSpread1.Sheets[0].Columns[0].Width = 50;fpSpread1.Sheets[0].Columns[1].Width = 50;fpSpread1.Sheets[0].Columns[2].Width = 175;fpSpread1.Sheets[0].Columns[3].Width = 40;fpSpread1.Sheets[0].Columns[4].Width = 65;fpSpread1.Sheets[0].Columns[5].Width = 100;fpSpread1.Sheets[0].Columns[6].Width = 100;fpSpread1.Sheets[0].Columns[7].Width = 125;
VB' Set column widths.FpSpread1.Sheets(0).Columns(0).Width = 50FpSpread1.Sheets(0).Columns(1).Width = 50FpSpread1.Sheets(0).Columns(2).Width = 175FpSpread1.Sheets(0).Columns(3).Width = 40FpSpread1.Sheets(0).Columns(4).Width = 65FpSpread1.Sheets(0).Columns(5).Width = 100FpSpread1.Sheets(0).Columns(6).Width = 100FpSpread1.Sheets(0).Columns(7).Width = 125
5. Saveyourproject,thenclicktheStartbuttoninthetoolbartorunyourproject.6. Yourformshouldlooksimilartothefollowingpicture.
Spread Windows Forms Developer’s Guide 45
Copyright © GrapeCity, Inc. All rights reserved.
GotoSettingtheCellTypesoftheRegistertocontinuethetutorial.
Setting the Cell Types of the Register
Tosetcelltypes,foreachcustomcelltype,youhavetocreateacelltypeobject,setthepropertiesforit,andthenassignthatobjecttotheCellType('CellTypeProperty'intheon-linedocumentation)propertyforacellorrangeofcells.
1. SetthecelltypefortheCheck#columnbyaddingthefollowingcodebelowthecodeyouhavealreadyadded:
Example
C#// Create Check # column of number cells.FarPoint.Win.Spread.CellType.NumberCellType objNumCell = new FarPoint.Win.Spread.CellType.NumberCellType();objNumCell.DecimalPlaces = 0;objNumCell.MinimumValue = 1;objNumCell.MaximumValue = 9999;objNumCell.ShowSeparator = false;fpSpread1.Sheets[0].Columns[0].CellType = objNumCell;
VB' Create Check # column of number cells.Dim objNumCell As New FarPoint.Win.Spread.CellType.NumberCellType()objNumCell.DecimalPlaces = 0objNumCell.MinimumValue = 1objNumCell.MaximumValue = 9999objNumCell.ShowSeparator = FalseFpSpread1.Sheets(0).Columns(0).CellType = objNumCell
2. SetthecelltypefortheDatecolumnbyaddingthefollowingcodebelowthecodeyouhavealreadyadded:
Example
Spread Windows Forms Developer’s Guide 46
Copyright © GrapeCity, Inc. All rights reserved.
C#// Create Date column of date-time cells.FarPoint.Win.Spread.CellType.DateTimeCellType objDateCell = new FarPoint.Win.Spread.CellType.DateTimeCellType();objDateCell.DateTimeFormat = FarPoint.Win.Spread.CellType.DateTimeFormat.ShortDate;fpSpread1.Sheets[0].Columns[1].CellType = objDateCell;
VB' Create Date column of date-time cells.Dim objDateCell As New FarPoint.Win.Spread.CellType.DateTimeCellType()objDateCell.DateTimeFormat = FarPoint.Win.Spread.CellType.DateTimeFormat.ShortDateFpSpread1.Sheets(0).Columns(1).CellType = objDateCell
3. SetthecelltypefortheDescriptioncolumnbyaddingthefollowingcodebelowthecodeyouhavealreadyadded:
Example
C#// Create Description column of text cells.FarPoint.Win.Spread.CellType.TextCellType objTextCell = new FarPoint.Win.Spread.CellType.TextCellType();objTextCell.MaxLength = 100;fpSpread1.Sheets[0].Columns[2].CellType = objTextCell;
VB' Create Description column of text cells.Dim objTextCell As New FarPoint.Win.Spread.CellType.TextCellType()objTextCell.MaxLength = 100FpSpread1.Sheets(0).Columns(2).CellType = objTextCell
4. SetthecelltypefortheTax?andCleared?columnsbyaddingthefollowingcodebelowthecodeyouhavealreadyadded:
Example
C#/// Create Tax? and Cleared? columns of check box cells.FarPoint.Win.Spread.CellType.CheckBoxCellType objCheckCell = new FarPoint.Win.Spread.CellType.CheckBoxCellType();objCheckCell.ThreeState = false;fpSpread1.Sheets[0].Columns[3].CellType = objCheckCell;fpSpread1.Sheets[0].Columns[4].CellType = objCheckCell;
VB' Create Tax? and Cleared? columns of check box cells.Dim objCheckCell As New FarPoint.Win.Spread.CellType.CheckBoxCellType()objCheckCell.ThreeState = FalseFpSpread1.Sheets(0).Columns(3).CellType = objCheckCellFpSpread1.Sheets(0).Columns(4).CellType = objCheckCell
Spread Windows Forms Developer’s Guide 47
Copyright © GrapeCity, Inc. All rights reserved.
5. SetthecelltypefortheDebit,Credit,andBalancecolumnsbyaddingthefollowingcodebelowthecodeyouhavealreadyadded:
Example
C#// Create the Debit, Credit, and Balance columns of currency cells.FarPoint.Win.Spread.CellType.CurrencyCellType objCurrCell = new FarPoint.Win.Spread.CellType.CurrencyCellType();objCurrCell.LeadingZero = FarPoint.Win.Spread.CellType.LeadingZero.Yes;objCurrCell.NegativeRed = true;objCurrCell.FixedPoint = true;fpSpread1.Sheets[0].Columns[5].CellType = objCurrCell;fpSpread1.Sheets[0].Columns[6].CellType = objCurrCell;fpSpread1.Sheets[0].Columns[7].CellType = objCurrCell;
VB' Create the Debit, Credit, and Balance columns of currency cells.Dim objCurrCell As New FarPoint.Win.Spread.CellType.CurrencyCellType()objCurrCell.LeadingZero = FarPoint.Win.Spread.CellType.LeadingZero.YesobjCurrCell.NegativeRed = TrueobjCurrCell.FixedPoint = TrueFpSpread1.Sheets(0).Columns(5).CellType = objCurrCellFpSpread1.Sheets(0).Columns(6).CellType = objCurrCellFpSpread1.Sheets(0).Columns(7).CellType = objCurrCell
6. Saveyourproject,thenclicktheStartbuttoninthetoolbartorunyourproject.7. Yourformshouldlooksimilartothefollowingpicture.
GotoAddingFormulastoCalculateBalancestocontinuethetutorial.
Adding Formulas to Calculate Balances
Spread Windows Forms Developer’s Guide 48
Copyright © GrapeCity, Inc. All rights reserved.
Yourcheckbookregisterisnowsetuptolooklikeacheckbookregister;however,itdoesnotbalancethecurrencyfiguresyouenterintheregister.Thisstepsetsuptheformulaforbalancingthefigures.
1. ProvidethefollowingcodeintheFormLoadeventafterthecodeyouhavealreadyadded:
Example
C#// Set formula for calculating balance.fpSpread1.Sheets[0].ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.R1C1;int i;for (i = 0; i <= fpSpread1.ActiveSheet.RowCount - 1; i++){if (i == 0)fpSpread1.Sheets[0].Cells[i, 7].Formula = "RC[-1] - RC[-2]" ;elsefpSpread1.Sheets[0].Cells[i, 7].Formula = "RC[-1] - RC[-2] + R[-1]C";}
VB' Set formula for calculating balance.FpSpread1.Sheets(0).ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.R1C1Dim i As IntegerFor i = 0 To FpSpread1.ActiveSheet.RowCount - 1If i = 0 ThenFpSpread1.Sheets(0).Cells(i, 7).Formula = "RC[-1] - RC[-2]"ElseFpSpread1.Sheets(0).Cells(i, 7).Formula = "RC[-1]-RC[-2]+R[-1]C"End IfNext
2. Saveyourproject,thenclicktheStartbuttoninthetoolbartorunyourproject.3. Yourformshouldlooksimilartothefollowingpicture.Typedataintoyourcheckbookregistertotestitandseehowit
operates.
4. YouhavecreatedacheckbookregisterusingSpread.Youhavecompletedthistutorial.
ReviewthelistofstepsforTutorial:CreatingaCheckbookRegister.
Spread Windows Forms Developer’s Guide 49
Copyright © GrapeCity, Inc. All rights reserved.
Understanding the Product
SpreadWindowsFormsprovidesacustomizable,extendable,andobject-orientedspreadsheetcomponentforuseintheMicrosoftNETframework.SpreadWindowsFormsalsoprovidesExcelsupportandcustomizationdowntothecelllevel,withacapableuser-interfacedesignandback-endcalculationefficiency.Thefollowingsectionsexplainsomeoftheunderlyingconceptsforthisuniqueandpowerfulproduct.
ProductOverviewFeatureOverviewNamespacesOverviewConceptsOverview
Product Overview
SpreadWindowsFormsisacomprehensivespreadsheetcomponentforWindowsFormsapplicationsthatcombinesgridcapabilities,spreadsheetfunctionality,andincludestheabilitytobindtodatasources.AsingleSpreadcomponentsupportsmanysheets,rows,andcolumns.Cross-sheetreferencingallowscalculationstomakeuseofdataandformulasonavarietyofsheets.SpreadWindowsFormsusesdotnotationforobject-orientedcodingin.NET.
TheSpreadcomponentmaybedroppedonaWindowsFormandcustomizedforarangeofapplications.Youcancustomizetheappearanceandtheuserinteractioninavarietyofways.Withabuilt-inDesigner,youcanquicklycreateaprototypeorcustomizeyourfinisheddesign.WithmostoftheSpread’sappearanceandfunctionalitybasedonunderlyingmodels,theadvanceddeveloperhascompletecontroloverthecomponent.FordetailsontheSpreadDesigner,refertoSpreadDesignerGuide(on-linedocumentation).
Importandexportcapabilitiesprovideanothersourceofflexibilitywhendevelopingandexchangingdesigns.SpreadWindowsFormscanhandledatafromcomma-delimitedtextfilesaswellasmultiplespreadsheetsfromMicrosoftExcelfiles.ThecontentsofasheetmaybesavedasaBIFF8ortextfilecompatiblewithMicrosoftExcelorasaSpreadXMLfile.Formoreinformationonexportingto(andimportingfrom)afile,refertotheImportandExportReference(on-linedocumentation).
ThefollowingfigureprovidesaconceptualoverviewofSpreadWindowsForms.
Spread Windows Forms Developer’s Guide 50
Copyright © GrapeCity, Inc. All rights reserved.
InSpread,youcanusethedefaultmodelsorextendthemthroughinheritance.Formoreinformationonmodels,refertoUnderlyingModels.
Stylesforcellsandskinsforsheetsprovidewaystosavecustomizedappearancesthatcanbeappliedtoothergroupsofcellsoranentiresheet.Formoreinformationonstylesforcells,refertoCreatingandApplyingaStyleforCells.Formoreinformationonskinsforsheets,refertoCreatingaCustomSkinforaSheet.
Formoreinformationaboutshapes,refertoCustomizingDrawing.
Formoreinformationontheformulasandfunctionsthatcanbeenteredinacell,refertotheManagingFormulasinCells.
Formoreinformationonthepartsoftheinterface,refertoUnderstandingPartsoftheComponent.
Foralistofmanyofthefeatures,seeFeatureOverview.
Feature Overview
SpreadWindowsFormsintroducessomepowerfulfeatures,asdescribedinthefollowingtopics.Eachtopicreferstoothertopicsinthedocumentationthatprovidemoreinformation.
CameraShapesCellTypesforCellFunctionality
Spread Windows Forms Developer’s Guide 51
Copyright © GrapeCity, Inc. All rights reserved.
ChartControlsonaSheetChildControlsonaSheetColumnFootersandGroupFootersConditionalFormattingDataBindingExcelSupportwithImportandExportCapabilitiesFilteringDataonaSheetFormulaTextBox(FormulaBar)FormulaProviderControlFunctionsandFormulasGradientsforButtonCells,Headers,andMoreGroupingRowsintheDisplayGroupingRowsorColumnsinanOutlineHeaderswithMultipleColumnsandRowsHierarchicalDisplayHitTestforLocatingtheCursorIndicatorsandIconsintheInterfaceInkNotationSupportKeyboardActionMappingMultipleSheetsNameBoxControlNotesforCellsPanesorViewportsPrintingandPDFQuickStartWizardRight-To-LeftLayoutsRowPreviewSearchingandSearchDialogShapes,Drawings,andAnnotations(FreehandDrawing)SkinsandStylesforCustomizedAppearanceSortingRowsorColumnsSpannableCellsSparklinesSpreadDesignerStatusBar(on-linedocumentation)TablesTabStripandSheetNameTabsTextRenderingwithGDITitleandSubTitleTouchSupportUndoandRedoActionsValidation(on-linedocumentation)VisualStylesforXPThemes
Camera Shapes
Youcanaddcamerashapestothesheet.Camerashapesarecreatedbytakingasnapshotofthecontentinarangeof
Spread Windows Forms Developer’s Guide 52
Copyright © GrapeCity, Inc. All rights reserved.
cells.Changesinthecellrangewillupdatethecontentofthecamerashape.
Formoreinformation,refertoCreatingCameraShapes.
Cell Types for Cell Functionality
Youcanusethefeature-richsetofcelltypesorextendthefunctionalitybydefiningyourown.Useanyofthemorethan20pre-definedcelltypesorcreateyourowntodeterminewhatkindofdatacanbeenteredintoacell,avoidingunnecessarychecksandvalidationsbythedeveloper,andprovidinganaturalwayforyourusertoenterdata.
Youcansetbarcodecelltypesfordisplayingbarcodes,fractionsincellsusingthepropertiesaddedtothenumbercelltype,andallowyouruserstoselectacolorfromacolorpickercell.
GcDateTime,GcNumber,GcTextBox,andothercelltypesarenowavailableinadditiontothestandardSpreaddate-time,number,andtextcells.
Formoreinformationaboutcelltypes,refertoCustomizingInteractionwithCellTypes.
Chart Controls on a Sheet
Youcanaddchartcontrolstoasheet.Therearemanydifferenttypesandviewsofchartsthatyoucancreate.YoucanusetheChartDesigner,SpreadDesigner,orcodetoaddachartcontrol.
Formoreinformation,refertoUsingtheChartControl.
Child Controls on a Sheet
Youcanhostchildcontrolsonasheettoprovidemoreinteractionwiththeuser.
Formoreinformation,refertoPlacingChildControlsonaSheet.
Column Footers and Group Footers
Youcanaddcolumnandgroupfooterstothesheet.Youcanputinformationinthefootersuchasformulasortext.
Formoreinformation,refertoDisplayingaFooterforColumnsorGroups.
Conditional Formatting
Youcansetupconditionalformatswithincellsthatdeterminetheformattingofthecellbasedontheoutcomeofaconditionaloperation.Youcanuserulesorcomparisonoperatorsintheconditionalformat.
Formoreinformation,refertoUsingConditionalFormattingofCells.
Data Binding
WithSpreadWindowsForms,youhavemanydatabindingoptions.
Youcanbindthespreadsheettoadatasettodisplayandallowyouruserstoeditinformation.Spreadcanautomaticallyupdatethedatasetwiththechanges.
Youcanalsoallowpartofyourspreadsheettobeunbound.Youcanalsobindtoarangeofcells.
Formoreinformation,refertoManagingDataBinding.
Spread Windows Forms Developer’s Guide 53
Copyright © GrapeCity, Inc. All rights reserved.
Excel Support with Import and Export Capabilities
Youcanimportdatafromandexportdata(andformatting)toMicrosoftExcel,bothinindividualspreadsheetsandentireworkbooks.Youcanimportandexportentirespreadsheet(s)withdataandformattingtoandfromXML.SeveralversionsofExcelaresupportedandseveralfiletypes,includingXLS,XLSX,CSV,andTXT.
Formoredetailsaboutwhathappensduringimportingorexporting,refertotheImportandExportReference(on-linedocumentation).
Formoreinformationaboutsavingandloadingfiles,refertoSavingDatatoaFileandOpeningExistingFiles.
Filtering Data on a Sheet
Youcancustomizetheuserexperienceforfilteringdataonasheet.Withrowfiltering,youcanallowtheusertofilterthedataincolumnsonasheetanddisplayonlytherowsofdatawhichmeetcriteriafromadrop-downlistorchangetheappearanceofrowsbasedonthatfiltering.
Formoreinformation,refertoManagingFilteringofRowsofUserData.
Formula Text Box (Formula Bar)
Youcanaddaformulatextboxforeditingformulas.Theformulatextboxissimilartotheformulaeditoravailabletothedeveloperandhastheappearanceofatextbox.Theformulabarprovidesalistofcalculationfunctionsandprovidesavisualmethodofselectingcellrangesfortheformula.
Formoreinformation,refertoUsingtheAdditionalSpreadControls.
Formula Provider Control
Youcanaddaformulaprovidercontroltotheformthatwillprovideformulasforothercontrolsontheform.
Formoreinformation,refertoUsingtheAdditionalSpreadControls.
Functions and Formulas
Youcanusebuilt-infunctionsandoperatorstodevelopformulasandperformcalculations.Addcalculationsquicklytoyourapplicationsbyusinganyofover300pre-definedfunctionsoraddyourowncustomfunctions.Choosefromanyofthesetypesoffunctions:
DatabaseDateandTimeEngineeringFinancialInformationLogicLookupandReferenceMathandTrigonometryStatisticsTextVolatile
Spreadalsooffersafloatingformulabarthatyoucanprovidetoyourenduserstoallowthemtopickfunctions.
Spread Windows Forms Developer’s Guide 54
Copyright © GrapeCity, Inc. All rights reserved.
Youcanalsocreatecustomformulasorcustomnamestouseinformulas.RefertoCreatingandUsingaCustomFunctionandCreatingandUsingaCustomNameformoreinformation.
FormoreinformationonenteringformulasusingtheSpreadDesigner,refertotheSpreadDesignerGuide(on-linedocumentation).
Formoreinformationonformulasingeneral,refertoManagingFormulasinCellsandtotheFormulaReference.
Gradients for Button Cells, Headers, and More
Youcansetgradientsforbuttoncellsandheaders.
Formoreinformationsee,AddingaGradienttoHeaderCells.
Formoreinformationsee,SettingaButtonCell.
Grouping Rows in the Display
Youcansetupthespreadsheettogiveuserstheabilitytogrouprowsofdatabasedonaparticularcolumnnamebydraggingthecolumnheadertothegroupingbar.Thisisusefulfordisplayinglargeamountsofdatainorganizedgroupsandorganizingrowsbasedonthecategoryofacolumn.ThisissometimesreferredtoasOutlook-stylegrouping.
Formoreinformationaboutoutlinessee,ManagingGroupingofRowsofUserData.
Grouping Rows or Columns in an Outline
Youcansetupthespreadsheettogiveuserstheabilitytoformarangeofexpandableandcollapsiblerowsorcolumns.Thisisusefulforhandlingrowsorcolumnsofdatathatdonotneedtobevisibleallthetimebutarerelatedtoadjacentrowsorcolumns.ThisissometimesreferredtoasrangegroupingorExcel-likegroupingoroutlines.
Formoreinformationaboutgroupingsee,ManagingOutlines(RangeGroups)ofRowsandColumns.
Headers with Multiple Columns and Rows
Youcanhavemultiplecolumnheadersandrowheaders.Youcanalsospanheadercells.Useheaderswithmultiplecolumnsorrowstoorganizeyourcolumnandrowinformation.
Formoreinformationaboutheaders,refertoCreatingaHeaderwithMultipleRowsorColumns.
Hierarchical Display
Youcancreateasheetwithinarowtodisplayrelationaldatahierarchically,withparentrowsandchildviewsofrelateddata.
Formoreinformationabouthierarchicaldisplayofdata,refertoWorkingwithHierarchicalDataDisplay.
HitTest for Locating the Cursor
YoucanusetheHitTestmethodforfindingthelocationofthecursor(pointer)onthespreadsheetcomponenttohelpwithdevelopmentofapplicationswhereaccessibilityissuesareconcerned.
FormoreinformationabouttheHitTestmethodofthespreadsheetcomponent,refertoLocatingthePointerUsingHitTest.
Spread Windows Forms Developer’s Guide 55
Copyright © GrapeCity, Inc. All rights reserved.
Indicators and Icons in the Interface
Youcancreatecustomrowfilteringindicatorsandcustomsortingindicatorstodisplayinthecolumnheader.Youcanalsocreatecustomimagesforthehierarchydisplayiconsforexpandingandcollapsingthehierarchy.
Youcanalsomakeamarquee(animated)focusindicatoraswellasotherenhancedfocusindicators.
Formoreinformation,refertoCustomizingtheUserInterfaceImages.
Ink Notation Support
YoucanusetheinknotationforwritingordrawingonSpreadwithyourTabletPC.Withasimplemethod,youcanturnonsupportforthisinkingfeature.
FormoredetailsaboutinknotationandsupportfortheTabletPC,refertoAllowingtheUsertoDrawwithaTabletPC.
Keyboard Action Mapping
SpreadWindowsFormsprovidesmultiplewaystocustomizenavigationwithinthecomponent,includingkeyboardnavigationandactionkeys.Withinputmapsandactionmaps,youcandetermineactionsintheSpreadcomponentthatoccurwhentheuserpresseskeys.Adefaultmappingofkeysandrelatedactionsisprovided;however,youcancustomizethesemapsthatdefinethemappingofkeystoactions.Forexample,youcanmaptheEnterkeysothatthecomponentmovesthefocustothecellbelowthecurrentcell.
YoucanloadanExcelcompatibilityinputactionmaporothermapfile.Youcanalsosaveaninputactionmaptoafile.
Formoreinformationaboutnavigationkeys,inputmaps,andactionmaps,refertothedescriptionsinManagingKeyboardInteraction.
Multiple Sheets
SpreadWindowsFormssupportsmultiplesheetsinasinglecomponenteachuniquelynamed.Usemultiplesheetstocategorizeyourinformation,similartousingworksheetsinMicrosoftExcel.
Sheetscanhavemanyrowsandcolumnsaswell.Youcandefinestylesforsheetsandapplythosestylesacrossmultiplesheets.
Formoreinformationaboutsheets,refertoCustomizingtheSheetAppearanceandCustomizingSheetInteraction.
Name Box Control
Thenameboxcontrolcanbeusedtocreateordisplaycustomnamesatruntime.
Formoreinformation,refertoSettinguptheNameBox.
Notes for Cells
SpreadWindowsFormsallowscellstohavenotesattachedtoprovideadditionalinformationtousers.Thecellnotehasthefollowingfunctionality:
automaticallysizescellnotesbasedoncontentsprintscellnotes
Spread Windows Forms Developer’s Guide 56
Copyright © GrapeCity, Inc. All rights reserved.
providescustomizablelocationsforthecellnotesletsyoucustomizethenoteindicatorcolorprovidesstickynotesthatstaywheretheyareplaced
Formoreinformation,refertoAddingaNotetoaCell.
Panes or Viewports
Youcanallowmorethanonepaneorviewportinthespreadsheettoallowyoutoviewdatafromdifferentpartsofthespreadsheetinonedisplay.Displaydatainmultipleviewportsandallowyourusertocustomizetheirownviewportviewbyprovidingsplitboxesalongwithscrollbars.
Formoreinformationaboutscrollableviewportsandsplitbars,refertoCustomizingViewports.
Printing and PDF
Youcancustomizetheprintingofyourspreadsheetswithmanydifferentprintingoptions.Forexample,youcanhavecolorsandimagesinheadersandfooters.Formoreinformation,seeCustomizingtheAppearanceofthePrinting.
Youcanprintpartsofthesheetasneeded.YoucanalsoprintafiletoaPortableDocumentFormat(PDF)file.Formoreinformation,seeSpecifyingWhattoPrint.
TherearemanyeventsrelatedtoprintingincludingthePrintPreviewShowing('PrintPreviewShowingEvent'intheon-linedocumentation)event.Formoreinformation,refertoProvidingaPreviewofthePrinting.YoucanalsosetyourownPrintPreviewDialogwiththeSetPrintPreview('SetPrintPreviewMethod'intheon-linedocumentation)method.
Quick Start Wizard
Youcanusethewizardtoquicklysetupdatabindingandotherareasofthecontrol.
Formoreinformation,refertoUnderstandingtheSpreadWizard.
Right-To-Left Layouts
Youcanhandlesupportforright-to-leftlayoutsintheSpreadcomponent.
Formoreinformation,refertoHandlingRight-to-LeftLayouts.
Row Preview
Youcanaddapreviewrowthatcontainsextrainformationaboutarow.Thepreviewrowisdisplayedbelowtherowitprovidesinformationfor.Youcanspecifycolorsandotherformattingforthepreviewrowaswell.
Formoreinformation,refertoSettingupPreviewRows.
Searching and Search Dialog
Youcanperformsearchesincodeorprovideasearchdialogwithvariousoptionstoyouruser.
Formoreinformation,refertoCustomizingUserSearchingofData.
Shapes, Drawings, and Annotations (Freehand Drawing)
Spread Windows Forms Developer’s Guide 57
Copyright © GrapeCity, Inc. All rights reserved.
Youcandrawshapesandcustomizedrawingobjectsontopofasheettohighlightpartsofthesheetorpointtheuserthroughtheuseofaform.
Youcanallowtheusertodrawinfreehandonthesheetwithannotations.Thedrawingisdoneonthesamelayerasshapes.Thisabilityiscalledannotationmode.
Formoreinformationaboutshapes,refertotheDesigningShapes(on-linedocumentation)andCustomizingDrawing.
Sorting Rows or Columns
Youcanprogrammaticallysortrowsorcolumnsorarangeofcells.Youcanspecifytheorderofsortingandthecomparisonmethodforsorting.Youcanallowyouruserstosortrowsautomaticallysimplybyclickingonthecolumnheader.Usemethodsatthesheetleveltoperformthesekindsofsorting:
automaticallysortingbycolumnmanuallysortingcolumnsorrowssortingdatainarangeofcells
Formoreinformationaboutsorting,refertoManagingSortingofRowsofUserData.
Spannable Cells
Youcanspancells.Createcellspanstojoincellstogether,allowingonecelltospanacrossmultiplecellstoinclude,forexample,yourcompanylogo.Youcanspandatacellsorheaders.YoucanalsohaveSpreadautomaticallymergecellsthatarethesamevalue.
Formoreinformationaboutspanningcells,refertoCreatingaSpanofCells.Formoreinformation,refertoAllowingCellstoMergeAutomatically.
Sparklines
Youcanaddsparklinestoacell.Asparklineisasmallgraphthatfitsinsideacellandusesdatafromarangeofcells.
Formoreinformation,refertoUsingSparklines.
Spread Designer
YoucanusetheSpreadDesignertodesignyourcomponentandtocreateaprototypequickly.UsetheSpreadDesignertoreducedevelopmenttimebyallowingyoutocustomizethelookandfeeloftheSpreadcomponentatdesigntimeusinganintuitive,easy-to-useinterface.
YoucanalsoshowtheSpreadDesignerinyourapplicationatruntime.
Formoreinformation,refertotheSpreadDesignerGuide(on-linedocumentation).
Skins and Styles for Customized Appearance
EasilyandquicklyconfiguretheappearanceofSpreadusingpredefinedskinsorcreateandsaveyourowncustomskinsthatdefinemanyoftheappearancesettingsforasheet.Customskinscanbesharedwitheveryoneinyourdevelopmentteam,allowingaconsistentlookofthecomponentacrossapplications.Youcanalsocreatespecificstylesthatcontainmanyoftheappearancesettingsforindividualcells.Namedstyleshelpyouquicklycustomizetheappearanceofacellorrangeofcells.
Spread Windows Forms Developer’s Guide 58
Copyright © GrapeCity, Inc. All rights reserved.
Forinformationonmanagingskins(thatapplytostylesandrenderersofthecomponent),refertoApplyingaSkintotheComponentandCreatingaCustomSkinforaComponent.
Forinformationaboutskinsforsheets(usingtheolderwayofsettingstylesforindividualsheets),refertoApplyingaSkintoaSheetandCreatingaCustomSkinforaSheet.
Forinformationonsavingtheskintoafile,refertoSavingandLoadingaSkin.
Formoreinformationonstylesforindividualcells,refertoCreatingandApplyingaStyleforCells.
FormoreinformationonVisualStyles(andXPThemes),refertoUsingXPThemeswiththeComponent.
Tables
Youcanaddtablestothesheet.Youcanalsosortorfilterthetabledata.
Formoreinformation,refertoCreatingTables.
Tab Strip and Sheet Name Tabs
Youcancustomizethepaintingofvariouspartsoftheinterfaceincludingthesheetnametabsandthetabstripthatcontainsthem.
Formoreinformationaboutthetabstrip,refertoCustomizingtheSheetNameTabsoftheComponentandCustomizingPaintingofPartsoftheComponent.
Text Rendering with GDI
YoucanuseGDI(insteadofGDI+)fordrawingtextinVisualStudio2005byusingthespecialFarPoint.Win.TextRendererDLLandaddingittothereferencesinaproject.IfyouusethetextrendererfeatureinyourprojectfortextdrawingthatisGDI-basedratherthanGDI+-based,inversion2.0ofthe.NETFramework,thenyoumustdistributetheFarPoint.Win.TextRenderer.dllfile.OnlyuserswhoareusingVisualStudio2005canbenefitfromthisfile,asthatenvironmentisrequiredtotargetversion2.0ofthe.NETFramework.
TheFarPoint.Win.TextRenderer.dllisathinwrapperforthenewSystem.Windows.FormsTextRendererclassin.NET2.0.TheSpreadcomponenttriestolocatetheFarPoint.Win.TextRendererassemblyifitcanfindtheframeworkSystem.Windows.Forms.TextRendererclassintheSystem.Windows.Formsassembly(thatis,ifSpreadisrunningunder.NET2.0).Ifitcan,SpreadloadstheFarPointTextRendererandusesreflectiontomakedynamiccallsintoittodothetextdrawingwithSystem.Windows.Forms.TextRendererinsteadofSystem.Drawing.Graphics.DrawString.SpreadusesdynamiccallsthroughreflectionsothattheFarPointSpreadassemblyisnotdependentontheFarPoint.Win.TextRendererassembly;iftheFarPointassemblyisnotfound,oriftheSystem.Windows.Forms.TextRendererclassisnotfoundintheSystem.Windows.Formsassembly,thenSpreadusesGraphics.DrawStringtodrawtextasithasalwaysdone.FormoreinformationabouthowthenewTextRendererclassin.NET2.0differsfromthewaytheGraphicsobjectdrawstext,inparticularhowTextRendererusesGDIdrawingAPIsinWindowsinsteadofGDI+APIsinthe.NETframework,refertothe.NETframeworkdocumentationaboutusingTextRendererclass.
SpreadcanuseGDI+drawingwhileothertextdrawingintheapplicationusesGDIwiththenewTextRendererclass;SpreadcanusethenewTextRendererclassforGDIdrawingwhileothertextdrawingintheapplicationusesGDI+.Thedifferencesareverysmall(afewpixelsinthespacingandalignment)andnotverynoticeable.
ThisDLLmustbeinstalledtothedirectorywheretheapplication’sexecutablefileresides(thebinfolder)onsystemswhereGDIdrawingintheSpreadispreferred.ThefilemaybeinstalledtotheGACtoensurethatallSpreadcontrolsinallapplicationsthatuseversion2.0ofthe.NETFrameworkwillusetheTextRendererfortextdrawing.Thefilecanbeinstalledtothebinfolderonanapplication-by-applicationbasis,andtheFrameworkwillfinditthere.
FormoreinformationonGDI-basedtextdrawing,refertothewebsite,HowtoDrawTextwithGDI.
Spread Windows Forms Developer’s Guide 59
Copyright © GrapeCity, Inc. All rights reserved.
FormoreinformationintheMicrosoft.NETFrameworkdocumentation,refertoMicrosoft.NETTextRendererClass.
Title and SubTitle
Youcanaddaspeciallyformattedareaatthetopofthespreadsheetthatincludesatitleandsubtitle.
Formoreinformation,refertoAddingaTitleandSubtitletoaSheet.
Touch Support
Spreadsupportstouchgesturesinmanyareasofthecontrol.
Formoreinformation,refertoUsingTouchSupportwiththeComponent.
Undo and Redo Actions
Youcanallowtheendusertoundoandredovarioustypesofuseractions.Thisincludescellediting,copying,andpastingfromtheClipboard,andotheractions.
Formoreinformation,refertoCustomizingUndoandRedoActions.
Visual Styles for XP Themes
YoucanassignvisualstylestotheSpreadcomponenttoachievethelookandfeelofXPthemes.
Formoreinformation,refertoUsingXPThemeswiththeComponent.
Namespaces Overview
InSpreadWindowsForms,namespacesareorganizedtocontainobjectsaccordingtohowtheyareusedinthecomponentandthefeaturestheyprovide.TheobjectsintheSpreadWindowsFormscomponentfallintothreecategories:
objectsthatrepresentpartsofthespreadsheet,likecolumn,rows,andcellsobjectsthatrepresentcelltypesandtheformattingofdatainthosecellsobjectsthatareconceptualrepresentationsofunderlyingaspectsofthespreadsheet
Foreachofthesethereisaspecificnamespace.Thenamespacesareorganizedasfollows:
Namespace DescriptionFarPoint.Win.Spread('FarPoint.Win.SpreadNamespace'intheon-linedocumentation)
Providesthebaseclasses,interfaces,enumerations,anddelegatesforthepartsofthespreadsheetinSpread.
FarPoint.Win.Spread.CellType('FarPoint.Win.Spread.CellTypeNamespace'intheon-linedocumentation)
Providesthebaseclasses,interfaces,andenumerationsforthecelltypes.
FarPoint.Win.Spread.DrawingSpace('FarPoint.Win.Spread.DrawingSpaceNamespace'intheon-linedocumentation)
Providesthebaseclasses,interfaces,andenumerationsforthevariousshapesandobjectsthatcanbedrawninthedrawingspace.
FarPoint.Win.Spread.Model('FarPoint.Win.Spread.ModelNamespace'intheon-linedocumentation)
Providesthebaseclasses,interfaces,andenumerationsforthemodelsinSpread.
Spread Windows Forms Developer’s Guide 60
Copyright © GrapeCity, Inc. All rights reserved.
Thespreadsheetandcelltypeobjectscallthemodelobjects.IfyouarenewtoworkingwithSpread,orarenewtodevelopinginanobject-orientedenvironment,youmightwanttousethespreadsheetandcelltypeobjectsatfirst,asyoubecomefamiliarwithfeaturesofSpread.However,intensiveuseoftheseobjectscandegradeyourapplication’sperformance.
Ifyouareanexperiencedprogrammer,youmightwanttousethemodelobjectsdirectly,insteadofaccessingthemthroughtheshortcutobjects.IfyouwanttoextendSpreadWindowsForms,youmustusethemodelobjectstodoso.
ThespreadsheetobjectsandeventargumentsareinclassesinthemainFarPointSpreadnamespace.Foradiscussionofhowtoworkwiththeseobjects,refertoShortcutObjects.
Thecelltypeobjectsprovidewaysforyoutosetupdifferenttypesofcellstohelptheuserorlimitthetypesofinput.Theyareseparatedintotheirownnamespace,theCellTypenamespacemainlytoallowyoutoseeallthecelltypeinformationinoneplace,separatefromthespreadsheetobjects.Fordetailsonthedifferentcelltypes,refertoCustomizingInteractionwithCellTypes.
Theconceptualobjects,themoreabstractobjects,arereferredtoas"models."Thesemodelsareresponsibleformanagingthestyleinformation,formatting,anddatainthecomponent.ThesearefoundintheModelnamespace.InSpread,youcanusethedefaultmodelsorextendthemthroughinheritance.RefertoUnderlyingModelsformoreinformationonmodels.
Concepts Overview
UserswhoarenewtousingSpreadproductsmightwanttoreviewthefollowingtopicsregardingobjectorientation.
ShortcutObjectsObjectParentageFormattedversusUnformattedDataCellTypesUnderlyingModels
Shortcut Objects
ThespreadsheetobjectsintheFarPointSpreadnamespace,whichrepresentvariouspartsofthespreadsheet,canbeaccessedthroughabuilt-insetofshortcutobjects.Cells,rows,columnsandothersarewrapperstootherobjects,andmakecustomizationeasierbyallowingyoutomanipulatethem.Theshortcutobjectsrepresentpartsofavisiblespreadsheet,suchascolumns,rows,andcells;andthereareconceptualrepresentationsofunderlyingpiecesofthespreadsheetwhichareimplementedintheunderlyingmodels.TounderstandmoreabouttheobjectsinSpread,lookatthesimplifiedobjectmodeldiagramsfortheFpSpread('FpSpreadClass'intheon-linedocumentation)classandtheSheetView('SheetViewClass'intheon-linedocumentation)classasshownhere.
Spread Windows Forms Developer’s Guide 61
Copyright © GrapeCity, Inc. All rights reserved.
TheSpreadWindowsFormscomponentprovidesthefollowingshortcutobjectsintheFpSpread('FpSpreadClass'intheon-linedocumentation)class:
Shortcut CorrespondingClasses
Spread Windows Forms Developer’s Guide 63
Copyright © GrapeCity, Inc. All rights reserved.
Objectcell Cell('CellClass'intheon-line
documentation)Cells('CellsClass'intheon-linedocumentation)
column Column('ColumnClass'intheon-linedocumentation)
Columns('ColumnsClass'intheon-linedocumentation)
header ColumnHeader('ColumnHeaderClass'intheon-linedocumentation)
RowHeader('RowHeaderClass'intheon-linedocumentation)
row Row('RowClass'intheon-linedocumentation)
Rows('RowsClass'intheon-linedocumentation)
alternatingrow
AlternatingRow('AlternatingRowClass'intheon-linedocumentation)
AlternatingRows('AlternatingRowsClass'intheon-linedocumentation)
sheet SheetView('SheetViewClass'intheon-linedocumentation)
SheetViewCollection('SheetViewCollectionClass'intheon-linedocumentation)
Tousetheshortcutobjects,settheirpropertiesorcalltheirmethods.Manyoftheobjectsprovideindexesforspecifyingthesheet,row,column,orcellwithwhichyouwanttowork.
Usetheshortcutobjectsfortheireaseofuse.Theshortcutobjectsarefairlyself-documenting;however,inVisualStudio.NET,theIntellisensefeatureprovidesadditionalinformationthathelpyouusetheseobjects.
Object Parentage
FortheobjectsintheSpreadcomponent,suchasthesheet,column,andcell,thereareformattingandotherpropertiesthateachobjectinheritsfromwhatiscalledits"parent."Acellmayinheritsomeformatting,forexamplethebackgroundcolor,fromthesheet.Ifyousetthealignmentoftextforallthecellsinacolumn,thecellinheritsthataswell.Becauseofthisobjectparentage,manypropertiesandmethodscanbeappliedindifferentwaystodifferentpartsofaspreadsheet.
Ofcourse,youcanoverridetheformattingthatanindividualcellinherits.Butbydefault,objectsinheritpropertiesfromtheirparents.Soinagivencontext,thesettingsofanyobjectarethecompositeofthesettingsofitsparentsthatarebeingappliedtothatobject.Forexample,youmaysetthetextcolorforacellatthecelllevel,butitmayinherittheverticalalignmentfromtherowandtheborderfromitscolumn,andthebackgroundcolorfromthesheet.Sincethebackgroundcolormaybesetatseveraloftheselevels,certainrulesofprecedencemustapply.
Theclosertothecelllevel,thehighertheprecedence.Soifyousetthebackgroundcolorofthecell,thesettingsinheritedfromtheparentsareoverridden.Refertothelisttoseetheorderofprecedenceoftheseproperties.Theclosertothecell(thelowerthenumber)thehighertheprecedence.
1. Cell2. Row3. Column4. AlternatingRow5. Sheet6. Component
FormoreinformationonthesettingofpropertiesofanobjectandhowtousetheParentpropertyofanobject,refertoCustomizingtheAppearanceofaCellandCustomizingInteractioninCells.Forinformationoncelltypes,whichissetinadifferentwaythaninheritingfromaparent,refertoCustomizingInteractionwithCellTypes.
Formatted versus Unformatted Data
TheSpreadWindowsFormscomponentprovidesbothtext(formatteddata)andvalue(unformatteddata)propertiesforacell.Forexample,inacurrencycell,theformatteddatacouldbe$1,432.56,butthevaluewouldbe1432.56.TheText
Spread Windows Forms Developer’s Guide 64
Copyright © GrapeCity, Inc. All rights reserved.
propertyofthecellwouldreturntheentireformattedstringwithcurrencysymbolandthousandseparator.TheValuepropertyofthecellcouldbeusedinformulasorothercalculations.Everycellhasbothproperties.Dependingonthecelltype,thedatainacellmaybehandleddifferently.Forcelltypesthathavebuttonsorcheckboxes,thedistinctionisimportant.
Formoredetailedinformationonthedifferencebetweenformattedandunformatteddata,andasummaryoftheresultsforspecificcelltypes,refertoHandlingDataUsingSheetMethods.
Cell Types
Thereareseveraldifferenttypesofcellsthatcanbesetinasheettocustomizehowtheuserinteractswiththeinformationinthatcell.Youcanspecifythecelltypeforindividualcells,columns,rows,arangeofcells,oranentiresheet.Foreachcelltypetherearepropertiesofacellthatcanbeset.Ingeneral,workingwithcelltypesincludesdefiningthecelltype,settingtheproperties,andapplyingthatcelltypetocells.
Spread Windows Forms Developer’s Guide 65
Copyright © GrapeCity, Inc. All rights reserved.
Ingeneralthecelltypesaregroupedintotwobroadcategories:editablecelltypes(suchastext,currency,andnumber)andgraphicalorcontrolcelltypes(suchasbutton,progress,andslider).Foralistofcelltypesanddetailsaboutusingthem,refertoCustomizingInteractionwithCellTypes.
HeaderCells
Whileyoucanassignacelltypetothecellsintherowheaderorcolumnheader,thecelltypeisonlyusedforpaintingpurposes.Itisrarethatyouwouldsetthecelltypesofheadercells.
Details
InSpread,acellhasbothaneditor,whichdetermineshowtheuserinteractswiththevalueinthecell,aformatter,whichdetermineshowthevalueisdisplayed,andarendererwhichdoesthepaintingofthecell.Theeditorisanactual
Spread Windows Forms Developer’s Guide 66
Copyright © GrapeCity, Inc. All rights reserved.
controlinstancethatSpreadcreatesandplacesinthelocationofthecellwhenyougointoeditmode.Theformatterdecideshowthedisplayedtextappears.Therendererissimplycodethatpaintsthatcontrolinsidethecellrectanglewhentheeditorisnotthere.
Formoredetailedinformationontheseobjects,refertotheindividualinterfacesintheAssemblyReference.Formoregeneralinformationaboutcelltypesandapplyingthemtocells,columns,rows,orwholesheets,refertoCustomizingInteractionwithCellTypes.
Underlying Models
TheSpreadcomponentprovidesthemodelsthatprovideabasisformuchofthecustomizationthatispossiblewiththecomponent.Themodelsaretheunderlyingtemplatefromwhichthemorecommonlyusedshortcutobjectsarederived.
Theshortcutobjectsaccesstheunderlyingmodels.Whenyouworkwithshortcutobjects,youareactuallyworkingwiththemodelsinthecomponent.Forexample,ifyouchangethenumberofcolumnsinasheetusingtheSheetsshortcutobject,themodelforthis(thedefaultsheetaxismodel)isupdatedwiththatinformation.
Toprovidedifferentfeaturesorcustomizethebehaviororappearanceofyourapplication,youcanextendthemodelstocreatenewclasses.Forexampleyoumaydothistocreateatemplatecomponentforallthedevelopersinyourorganization.Bycreatingyourownclassbasedononeofthemodels,youcancreateacustomizedclassandprovideittoallthedeveloperstouse.
Usetheobjectmodelsforthefollowingbenefits:
Forbetterperformance:ifyouaresettingseveralproperties,forexample,yourapplicationwillbefasterifyousetthepropertiesforanobject,andthenassignthatobjecttoSpread.Forspecializedfeatures:ifyouwanttocreateyourowncustomizedfeatures,suchasextendingthedatamodeltobringinatab-delimitedfile,youcanextendtheBaseSheetDataModeltodoso.Ifyouwanttocreateyourowncelltypeorcustomizethebehaviorofhowusersselectcells,youcandothatthroughthemodels.Forconsistencyindevelopment:ifyouareadevelopmentteamthatwouldliketohaveconsistencyinsomecustomstyleandcustombehavior,makethechangesinthemodelsandtheentireteamcanbenefit.Formorecompleteunderstandingoftheproduct:ifyouareusingmanyofthefeaturesofthecomponent,themostefficientwaytocustomizethecomponentisbyfirstunderstandingtheworkingsofthemodelsuponwhichtheobjectsarebased.
Formoreinformationabouttheunderlyingmodelsandhowtousethem,refertoUnderstandingtheUnderlyingModels.
Spread Windows Forms Developer’s Guide 67
Copyright © GrapeCity, Inc. All rights reserved.
Understanding the Spreadsheet Objects
YoucancustomizetheappearanceofvariouspartsoftheSpreadcomponent.Roughlyspeaking,theobjectsintheSpreadWindowsFormscomponentfallintotwocategories:objectsthatrepresentrealworldthingsinaspreadsheet,likecolumn,rows,andcells,andobjectsthatareconceptualrepresentationsofunderlyingpiecesofthespreadsheet,suchasdataandagrid.
Therealworldobjectscanbeaccessedthroughabuilt-insetofshortcutobjects.TheshortcutobjectshelpyouinteractwiththeSpreadWindowsFormscomponentinawaythatisprobablyfamiliartoyoufromworkingwithothercomponentsorapplications.Theconceptualobjects,themoreabstractobjects,arereferredtoas"models."Thesemodelsareresponsibleformanagingthestyleinformation,formatting,anddataintheSpreadcomponent.
Inactuality,theshortcutobjectscallthemodelobjects.However,theshortcutobjectsallowyoutointeractwiththeSpreadWindowsFormscomponentwithoutdealingtoomuchwiththeunderlyingobjectmodels.IfyouarenewtoworkingwithSpread,orarenewtodevelopinginanobject-orientedenvironment,youmightwanttousetheshortcutobjectsatfirst,asyoubecomefamiliarwithfeaturesofSpreadWindowsForms.However,intensiveuseoftheshortcutobjectscandegradeyourapplication’sperformance.
ThetasksthatrelatetosettingtheappearanceofobjectsintheSpreadcomponentinclude:
WorkingwithSheetsWorkingwiththeRowsandColumnsWorkingwithHeadersWorkingwithCells
ForinformationoncustomizingtheappearanceusingtheSpreadDesigner,refertotheSpreadDesignerGuide(on-linedocumentation).
Working with Sheets
Youcanhavemultiplesheetswithinaworkbook.Eachsheetisaseparatespreadsheetandcanhaveitsownappearanceandsettingsforuserinteraction.Eachsheethasauniquenameandsheetnametabforeasynavigationbetweensheets.
ThesetasksrelatetoworkingwithandsettingtheappearanceofthesheetsinsidetheSpreadcomponent:
WorkingwiththeActiveSheetWorkingwithMultipleSheetsAddingaSheetCopyingandInsertingaSheetMovingaSheetRemovingaSheetShowingorHidingaSheet
Whenyouworkwithsheets,youcanworkwiththeobjectsusingtheshortcutobjectsincode,(SheetView('SheetViewClass'intheon-linedocumentation)andSheetViewCollection('SheetViewCollectionClass'intheon-linedocumentation)classes)oryoucanworkdirectlywiththemodel.Mostdeveloperswhoarenotcreatingextensivecustomizationsfinditeasiertoworkwiththeshortcutobjects.Formoreinformationonmodels,refertoUnderstandingtheUnderlyingModels.
Settingsappliedtoaparticularroworcolumnorcellcanoverridethesettingsthataresetatsheetlevel.RefertoObjectParentage.
Formoredetailsontheobjectsinvolved,refertotheSheetView('SheetViewClass'intheon-linedocumentation)classandSheetViewCollection('SheetViewCollectionClass'intheon-linedocumentation)class.
Working with the Active Sheet
Spread Windows Forms Developer’s Guide 68
Copyright © GrapeCity, Inc. All rights reserved.
Theactivesheetisthesheetthatcurrentlyreceivesanyuserinteraction.YoucanspecifytheactivesheetprogrammaticallybyusingtheActiveSheet('ActiveSheetProperty'intheon-linedocumentation)propertyoftheFpSpread('FpSpreadClass'intheon-linedocumentation)object.YoucanalsospecifytheindexoftheactivesheetbyusingtheActiveSheetIndex('ActiveSheetIndexProperty'intheon-linedocumentation)property.
Usually,theactivesheetisdisplayedontopofothersheets.
UsingaShortcut
YoucanuseActiveSheetasashortcutobjectfortheactivesheetwhenspecifyingpropertiesofthesheet.
Example
Setpropertiesoftheactivesheetandassigntheactivesheettosheetnumber2.
C#// Create three sheets in the component.fpSpread1.Sheets.Count = 3;// Set third sheet (in zero-based index) be set to active sheet.fpSpread1.ActiveSheetIndex = 2;// Set some properties of the active sheet.fpSpread1.ActiveSheet.ColumnCount = 8;fpSpread1.InterfaceRenderer = NULL;fpSpread1.ActiveSheet.GrayAreaBackColor = Color.Purple;
VB' Create three sheets in the component.FpSpread1.Sheets.Count = 3' Set third sheet (in zero-based index) be set to active sheet.FpSpread1.ActiveSheetIndex = 2' Set some properties of the active sheet.FpSpread1.ActiveSheet.ColumnCount = 8FpSpread1.InterfaceRenderer = NothingFpSpread1.ActiveSheet.GrayAreaBackColor = Color.Purple
Working with Multiple Sheets
Thecomponentallowsmultiplesheets.YoucanspecifythenumberofsheetswiththeCount('CountProperty'intheon-linedocumentation)propertyoftheSheetViewCollection('SheetViewCollectionClass'intheon-linedocumentation)class.Forexample,youcansettheSpreadtohave5sheets(andeachsheethasasheetnametab)usingthiscode:
fpSpread1.Sheets.Count = 5;
Youcanspecifypropertiesforanindividualsheetorforseveralsheetsatatime.UsetheSheetViewclassortheActiveSheetshortcutincode.Formoreinformation,refertoCustomizingtheIndividualSheetAppearance.
Youcannamethesheetsorusethedefaultsheetnames.Thedefaultsheetnameis"Sheet1"andasothersheetsareadded,thesheetarenamedincrementally"Sheet2","Sheet3",andsoon.UsetheSheetName('SheetNameProperty'intheon-linedocumentation)propertyintheSheetView('SheetViewClass'intheon-linedocumentation)classtonamethesheetprogrammatically.
Toaddanewsheet,refertoAddingaSheet.Toremoveasheet,refertoRemovingaSheet.
Spread Windows Forms Developer’s Guide 69
Copyright © GrapeCity, Inc. All rights reserved.
YoucanusecodesuchasthefollowingtocopyasheettoanotherSpreadcomponent.
FpSpread2.Sheets(0) = FpSpread1.Sheets(1)
SincethetwosheetsusethesameSheetViewobject,anychangesmadeinonesheetareautomaticallyreflectedintheother.
Toreturnasheetbyname,youcanusetheSheetViewCollection.Find('FindMethod'intheon-linedocumentation)methodasshowninthefollowingcode.
FpSpread1.Sheets.Find("Sheet1").Cells(0,0).Value = "test"
TheFpSpread.Sheets('SheetsProperty'intheon-linedocumentation)propertycanbeusedwhenyouwishtouseanintegerforthesheetvalue.ThismethodhasaSheetViewCollection('SheetViewCollectionClass'intheon-linedocumentation)objectasitsvalueandtakesanintegerastheindexerinsteadofastringforasheetname.
Forinformationaboutthedisplayofthesheetnamesinthesheetnamebuttons,refertoCustomizingtheSheetNameTabsoftheComponent.
Adding a Sheet
YoucanaddasheetoraddseveralsheetstotheSpreadcomponent.Bydefault,thecomponenthasonesheet,namedSheet1andreferencedassheetindex0.Thesheetindexiszero-based.Incode,youcansimplychangethesheetcountoryoucanexplicitlyaddthesheet(s).Ifyouareusingcustomsheetnamesbesuretospecifythenameofthesheet.
Theuserisallowedtoaddnewsheetsbydefault.Theycandothisbyclickingonthenewsheeticononthetabstripnexttothesheetname(providedthetabstripisvisible).Ifthesheetcountisgreaterthan1,thetabstripisdisplayedbydefault.YoucanchangethisbysettingtheTabStripPolicy('TabStripPolicyProperty'intheon-linedocumentation)property.YoucanpreventtheuserfromaddingnewsheetsbysettingtheTabStripInsertTab('TabStripInsertTabProperty'intheon-linedocumentation)propertytofalse.
YoucanusetheAdd('AddMethod'intheon-linedocumentation)methodtoaddanewsheettotheSheetViewCollection('SheetViewCollectionClass'intheon-linedocumentation)forthecomponent.YoucanalsousetheAddNewSheetView('AddNewSheetViewMethod'intheon-linedocumentation)methodaddasheet.
Formoreinformationonhowthesheetnamesappearinthesheettabs,andhowtocustomizethesheettabs,refertoCustomizingtheSheetNameTabsoftheComponent.
Toaddasheettothecomponent,completethefollowinginstructions.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. ClicktheAddbuttontoaddasheettothecollection.
AnewsheetnamedSheetViewn(wherenisaninteger)isaddedtothecomponent.
5. Ifyouwanttochangethenameofthenewsheet,clicktheSheetNamepropertyinthepropertylist,andthentypethenewnameforthesheet.
6. ClickOKtoclosetheeditor.
UsingaShortcut
1. CreateanewSheetView('SheetViewClass'intheon-linedocumentation)object.2. Ifyouwanttodoso,setpropertiesforthesheet,suchasitsname.3. CalltheSheetsshortcutobjectAdd('AddMethod'intheon-linedocumentation)methodtoaddthenew
sheettotheSheetViewCollection('SheetViewCollectionClass'intheon-linedocumentation)forthe
Spread Windows Forms Developer’s Guide 70
Copyright © GrapeCity, Inc. All rights reserved.
component.
Example
Thisexamplecodeaddsanewsheettothecomponent,thennamesthesheet"North"andsetsittohave10columnsand100rows.
C#// Create a new sheet.FarPoint.Win.Spread.SheetView newsheet = new FarPoint.Win.Spread.SheetView();newsheet.SheetName = "North";newsheet.ColumnCount = 10;newsheet.RowCount = 100;// Add the new sheet to the component.fpSpread1.Sheets.Add(newsheet);
VB' Create a new sheet.Dim newsheet As New FarPoint.Win.Spread.SheetView()newsheet.SheetName = "North"newsheet.ColumnCount = 10newsheet.RowCount = 100' Add the new sheet to the component.FpSpread1.Sheets.Add(newsheet)
Copying and Inserting a Sheet
YoucancopyandinsertasheettothesameSpreadcomponentoranotherSpreadcomponentontheform.Spreaddoesnotprovideawaytocopythesheet,butwiththecodegivenbelowyoucaneasilycreateyourownCopySheetmethod.Tocopyasheetandinsertitinthecomponent,simplycreateanewmethod,calledCopySheet,asshownhereandthenusetheAdd('AddMethod'intheon-linedocumentation)orInsert('InsertMethod'intheon-linedocumentation)methodsintheSheetViewCollection('SheetViewCollectionClass'intheon-linedocumentation)class.
TheCopySheetmethodalsocopiesallshapesonthatsheet.
CopyingasheetusingtheCopySheetmethodalsocopiestheNamedStyleCollectioninthesheet,andcreatesseparatecopiesofanyNamedStyleobjectsinthecollectionthatareprivatetothecopyandnotsharedwiththeoriginalNamedStyleCollectioninthecopiedsheet.Ifyouwanttosharethenamedstylesinsteadofcreatingseparatecopies,youcanassigntheNamedStyleCollectionyouwanttosharetotheNamedStylespropertyofthecopy.YoumightalsowanttotemporarilyremovetheNamedStyleCollectionfromthesheetbeingcopied,sothatitisnotcopiedunnecessarily.ThiscanbedonebyassigningtheNamedStyleCollectiontoavariable,thensettingtheNamedStylespropertytoNothing(nullinC#),thenmakingthecopy,thenassigningthevariablebacktotheNamedStylesproperty.
TheSpreadDesignercanbeusedtocopyandpasteasheetatdesigntime.Right-clickonthesheettabiconinthedesignertobringuptheCopy,Cut,andPastecontextmenu.
TheSpreadActions('SpreadActionsClass'intheon-linedocumentation)classhasoptionsfortheclipboardcopy,cut,andpasteofasheet.
UsingCode
1. CreateanewCopySheetmethodtobeusedforcopyingsheets.2. Handlethenamedstylesforthatsheetasdescribedabove.3. CalltheSheetsshortcutobjectAdd('AddMethod'intheon-linedocumentation)methodtoaddthenewsheetortheInsertmethod
toinsertthesheettotheSheetViewCollection('SheetViewCollectionClass'intheon-linedocumentation)forthecomponent.
Example
ThisisthecodefortheCopySheetmethod.
C#private void Form1_Load(object sender, EventArgs e)
Spread Windows Forms Developer’s Guide 71
Copyright © GrapeCity, Inc. All rights reserved.
{ fpSpread1.Sheets.Count = 3;}
private void button1_Click(object sender, EventArgs e){ FarPoint.Win.Spread.SheetView s = new FarPoint.Win.Spread.SheetView(); s.Cells[0, 0].Text = "test"; FarPoint.Win.Spread.DrawingSpace.FourWayArrowShape sh = new FarPoint.Win.Spread.DrawingSpace.FourWayArrowShape(); sh.Name = "Arrow"; s.AddShape(sh); fpSpread1.Sheets.Add(CopySheet(s));}
public FarPoint.Win.Spread.SheetView CopySheet(FarPoint.Win.Spread.SheetView sheet) { FarPoint.Win.Spread.SheetView newSheet = null; if (sheet != null) { newSheet = (FarPoint.Win.Spread.SheetView)FarPoint.Win.Serializer.LoadObjectXml(typeof(FarPoint.Win.Spread.SheetView), FarPoint.Win.Serializer.GetObjectXml(sheet, "CopySheet"), "CopySheet"); } return newSheet; }
VBPrivate Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load FpSpread1.Sheets.Count = 3End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim s As New FarPoint.Win.Spread.SheetView() s.Cells(0, 0).Text = "test" Dim sh As New FarPoint.Win.Spread.DrawingSpace.FourWayArrowShape() sh.Name = "Arrow" s.AddShape(sh) FpSpread1.Sheets.Add(CopySheet(s))End Sub
Public Function CopySheet(sheet As FarPoint.Win.Spread.SheetView) As FarPoint.Win.Spread.SheetView Dim newSheet as FarPoint.Win.Spread.SheetView = Nothing If Not IsNothing(sheet) Then newSheet = FarPoint.Win.Serializer.LoadObjectXml(GetType(FarPoint.Win.Spread.SheetView), FarPoint.Win.Serializer.GetObjectXml(sheet, "CopySheet"), "CopySheet") End If Return newSheetEnd Function
Moving a Sheet
Ifyouhavemultiplesheets,youcanmoveasheet.Ifyoumovethefirstsheetlocationtothelastsheetlocation,thentheothersheetsaremovedtotheleft.Ifyoumovethesheetlocationtothelocationofthesheetnexttoit,thenthiseffectivelyswapsthesheets.
Specifythefromandtolocationusingthesheetindex.Thesheetindexiszero‑based.
Movingasheetdoesnotchangethesheetname.
TheAllowSheetMove('AllowSheetMoveProperty'intheon-linedocumentation)propertyoftheFpSpreadclasscanbesettotruetoallowtheusertomovethesheetsusingthesheettabs.Youcanalsohideasheet.Formoreinformation,refertoShowingorHidingaSheet.
YoucanpreventauserfrommovingaspecificsheetwiththeSheetDragMoving('SheetDragMovingEvent'inthe
Spread Windows Forms Developer’s Guide 72
Copyright © GrapeCity, Inc. All rights reserved.
on-linedocumentation)andSheetDragMoved('SheetDragMovedEvent'intheon-linedocumentation)events.Selectasheettabonthetabstrip,dragthesheettabtoanothertab,thenreleasethemousetomovethesheetfromtheoldindextothenewindex.TheSheetDragMoving('SheetDragMovingEvent'intheon-linedocumentation)eventoccurswhentheuserstartsdraggingthesheettabname.TheSheetDragMoved('SheetDragMovedEvent'intheon-linedocumentation)eventoccursrightaftertheusermovesthesheet.YoucanpreventspecificsheetsfrombeingmovedbysettingtheCancelpropertytotrueintheSheetDragMoving('SheetDragMovingEvent'intheon-linedocumentation)event.
Tomoveanexistingsheet,completethefollowinginstructions.
UsingaShortcut
CalltheSheetsMove('MoveMethod'intheon-linedocumentation)method(tomovethesheetfromonelocationtoanother).
Example
Thisexamplecodemovesthesecondsheettothelocationofthethirdsheet.
C#// Move sheet 2 to the location of sheet 3.FpSpread1.Sheets.Count = 5;FpSpread1.Sheets.Move(2, 3);
VB' Move sheet 2 to the location of sheet 3.FpSpread1.Sheets.Count = 5FpSpread1.Sheets.Move(2, 3)
Removing a Sheet
Ifyouhavemultiplesheets,youcanremoveasheetorremoveseveralsheetsfromtheSpreadcomponent.Theremustalwaysbeatleastonesheetinthecomponent.
Incode,youcansimplychangethesheetcountoryoucanexplicitlyremovethesheetsbyspecifyingtheirindexes.Thesheetindexiszero-based.
Removinganexistingsheetdoesnotchangethedefaultsheetnamesprovidedtotheothersheets.Forexample,aSpreadcomponentwiththreesheetswouldbydefaultnamethemSheet1,Sheet2,andSheet3.Ifyouremovethesecondsheet,thenamesfortheremainingsheetsareSheet1andSheet3.Theindexesforthesheetsare0and1,becausethesheetindexiszerobased.
Youcanalsohideasheet.Formoreinformation,refertoShowingorHidingaSheet.
Toremoveanexistingsheet,completethefollowinginstructions.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheettoremove.5. ClicktheRemovebuttontoremovethesheetfromthecollection.6. ClickOKtoclosetheeditor.
Spread Windows Forms Developer’s Guide 73
Copyright © GrapeCity, Inc. All rights reserved.
UsingaShortcut
CalltheSheetsshortcutobjectRemove('RemoveMethod'intheon-linedocumentation)method(toremovethesheetfromtheSheetViewCollection('SheetViewCollectionClass'intheon-linedocumentation)forthecomponent)andspecifythesheettoremove.
Example
ThisexamplecoderemovesthesecondsheetfromaSpreadcomponentthathastwoormoresheets.
C#// Remove the second sheet.fpSpread1.Sheets.Remove(fpSpread1.Sheets[1]);
VB' Remove the second sheet.FpSpread1.Sheets.Remove(FpSpread1.Sheets(1))
Showing or Hiding a Sheet
Ifyouhavemorethanonesheetinthecomponent,youcanhideasheetsothatitisnotdisplayedtotheuser.Eventhoughitisnotdisplayed,itisnotremovedfromthecomponent.Theremustbeatleastonesheetinthecomponent.Forinformationonaddingasheet,refertoAddingaSheet.
Hidingasheetdoesnotchangethedefaultsheetnamesprovidedfortheothersheets.Forexample,aSpreadcomponentwiththreesheetswouldbydefaultnamethemSheet1,Sheet2,andSheet3.Ifyouhidethesecondsheet,thenamesfortheremainingsheetsareSheet1andSheet3.
Hidingasheetdoesnotremoveitanddoesnotaffectformulasonthatsheetorreferencestothatsheet.Formoreinformationonremovingthesheetcompletely,refertoRemovingaSheet.
Forprogrammingdetails,refertotheVisible('VisibleProperty'intheon-linedocumentation)propertyoftheSheetView('SheetViewClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheettohide.5. SelecttheVisiblepropertyinthepropertylist,andthenselectfalse.6. ClickOKtoclosetheeditor.
UsingaShortcut
SettheSheetsshortcutobjectVisible('VisibleProperty'intheon-linedocumentation)propertyforthesheet.
Example
ThisexamplecodehidesthesecondandfourthsheetsinaSpreadcomponentthathaseightsheets.
C#private void Form1_Load(object sender, System.EventArgs e)
Spread Windows Forms Developer’s Guide 74
Copyright © GrapeCity, Inc. All rights reserved.
{ // Set the Spread to have eight sheets. fpSpread1.Sheets.Count = 8; // Hide the second and fourth sheets. fpSpread1.Sheets[1].Visible = false; fpSpread1.Sheets[3].Visible = false; }
VBPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Set the Spread to have eight sheets. FpSpread1.Sheets.Count = 8 ' Hide the second and fourth sheets. FpSpread1.Sheets(1).Visible = False FpSpread1.Sheets(3).Visible = FalseEnd Sub
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosetproperties.2. Inthepropertylist,selecttheVisibleproperty.3. SelectFalse.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Working with the Rows and Columns
Thesetasksrelatetosettingtheappearanceofcolumnsorrowsinthesheet:
CustomizingtheNumberofRowsorColumnsAddingaRoworColumnRemovingaRoworColumnShowingorHidingaRoworColumn
Whenyouworkwithrowsandcolumns,youcanworkwiththeobjectsusingtheshortcutsincode(Row,Rows,Column,Columns,AlternatingRow,andAlternatingRowsclasses)oryoucanworkdirectlywiththemodel.Mostdeveloperswhoarenotcreatingextensivecustomizationsfinditeasiertoworkwiththeshortcutobjects.Forinformationontheunderlyingmodelresponsibleforrowsandcolumns,refertotheUnderstandingtheAxisModel.
YoucaneditpropertiesoftheRowsandColumnsclassesinthePropertieswindow(inSpreadDesignerorinVisualStudio.NET).FormoreinformationontheCells,Columns,andRowsEditorthatisavailablefromthePropertieswindow,refertotheexplanationofthiseditorintheSpreadDesignerGuide.
Similartoothergridproductsyoumighthaveused,Spreaddoesnotallowin-celleditingofthecellsintherowandcolumnheaders.
Formoreinformationabouttheappearanceofrowsasaresultoffiltering,refertoSettingtheAppearanceofFilteredRows.
Settingsappliedtoaparticularroworcolumnoverridethesettingsthataresetatthesheetlevelandsettingsappliedatacellleveloverridetheroworcolumnsettings.RefertoObjectParentage.
Formoreinformation,refertotheRow('RowClass'intheon-linedocumentation),Rows('RowsClass'intheon-linedocumentation),AlternatingRow('AlternatingRowClass'intheon-linedocumentation),AlternatingRows('AlternatingRowsClass'intheon-linedocumentation),Column('ColumnClass'intheon-linedocumentation),andColumns('ColumnsClass'intheon-linedocumentation)objectsinthe
Spread Windows Forms Developer’s Guide 75
Copyright © GrapeCity, Inc. All rights reserved.
AssemblyReference.
Customizing the Number of Rows or Columns
Whenyoucreateasheet,itisautomaticallycreatedwithfivehundredcolumnsandfivehundredrows.Youcanchangethenumbertozerooruptotwobillioncolumnandrows.
Formoredetails,refertotheSheetView.RowCount('RowCountProperty'intheon-linedocumentation)propertyandSheetView.ColumnCount('ColumnCountProperty'intheon-linedocumentation)property.
Youcanalsorestricttheuserfromaccessingvariousrowsandcolumns.Formoreinformation,refertoAllowingUserInteractionwithRowsandColumns.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetforwhichtosetthenumberofcolumnsorrows.5. Inthepropertieslist,settheColumnCountpropertytosetthenumberofcolumnsandtheRowCountpropertytosetthenumberofrows.
6. ClickOKtoclosetheeditor.
UsingaShortcut
SettheColumnCountorRowCountpropertyfortheSheetsshortcutobject.
Example
Thisexamplecodesetsthefirstsheettohave10columnsand100rows.
C#fpSpread1.Sheets[0].ColumnCount = 10;fpSpread1.Sheets[0].RowCount = 100;
VBFpSpread1.Sheets(0).ColumnCount = 10FpSpread1.Sheets(0).RowCount = 100
UsingCode
SettheColumnCount('ColumnCountProperty'intheon-linedocumentation)orRowCount('RowCountProperty'intheon-linedocumentation)propertyforaSheetView('SheetViewClass'intheon-linedocumentation)object.
Example
Thisexamplecodesetsthefirstsheettohave10columnsand100rows.
C#FarPoint.Win.Spread.SheetView Sheet0;Sheet0 = fpSpread1.Sheets[0];
Spread Windows Forms Developer’s Guide 76
Copyright © GrapeCity, Inc. All rights reserved.
Sheet0.ColumnCount = 10;Sheet0.RowCount = 100;
VBDim Sheet0 As FarPoint.Win.Spread.SheetViewSheet0 = FpSpread1.Sheets(0)Sheet0.ColumnCount = 10Sheet0.RowCount = 100
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosetthenumberofcolumnsorrows.2. Fromthepropertylistforthesheet,intheAppearancecategory,selectColumnsorRowstoexpandthe
propertiesforthecolumnsorrowsinthesheet.3. Inthelistofpropertiesforthecolumnsorrows,settheCountproperty.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Adding a Row or Column
Youcanaddoneormorecolumnsorrowstoasheet,andspecifywherethecolumnorrowisadded.YoucanusethemethodsintheSheetView('SheetViewClass'intheon-linedocumentation)classorthemethodsintheDefaultSheetDataModel('DefaultSheetDataModelClass'intheon-linedocumentation)class.
Ifyousetthecelltypeforthecolumnandarowisinserted,thenewcellsinthecolumnusethecelltypefortheentirecolumn.Ifyousetthecelltypeforindividualcellsandanewrowisinserted,thenthenewcellsusethedefaultcelltype,andyouwouldneedtosetthecelltypeforeachofthenewcells.
FormoredetailsrefertotheSheetView.AddRows('AddRowsMethod'intheon-linedocumentation)methodorSheetView.AddColumns('AddColumnsMethod'intheon-linedocumentation)method.
UsingaShortcut
CalltheAddColumnsorAddRowsmethodfortheSheetsshortcutobject.Setthecolumnorrowparametertospecifythecolumnorrowbeforewhichtoaddthecolumnsorrows.Setthecountparametertospecifythenumberofcolumnsorrowstoadd.
Example
Thisexamplecodeaddstwocolumnsbeforecolumn6.
C#fpSpread1.Sheets[0].AddColumns(6,2);
VBFpSpread1.Sheets(0).AddColumns(6,2)
UsingCode
1. UsetheAddRows('AddRowsMethod'intheon-linedocumentation)orAddColumns('AddColumnsMethod'intheon-linedocumentation)methodforaSheetView('SheetViewClass'intheon-linedocumentation)object.
Spread Windows Forms Developer’s Guide 77
Copyright © GrapeCity, Inc. All rights reserved.
2. Setthecolumnorrowparametertospecifythecolumnorrowbeforewhichtoaddthecolumnsorrows.3. Setthecountparametertospecifythenumberofcolumnsorrowstoadd.
Example
Thisexamplecodeaddstwocolumnsbeforecolumn6.
C#FarPoint.Win.Spread.SheetView Sheet0;Sheet0 = fpSpread1.Sheets[0];Sheet0.AddColumns(6,2);
VBDim Sheet0 As FarPoint.Win.Spread.SheetViewSheet0 = FpSpread1.Sheets(0)Sheet0.AddColumns(6, 2)
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttoaddaroworcolumn.2. Selectarowabovewhichyouwanttoaddaroworacolumntotheleftofwhichyouwanttoaddacolumn.3. Right-clickontheroworcolumnandchooseInsert.
Anadditionalroworcolumnisaddedtothesheet.
4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Removing a Row or Column
Youcanremoveoneormorecolumnsorrowsfromasheet.YoucanusethemethodsintheSheetView('SheetViewClass'intheon-linedocumentation)classorthemethodsintheDefaultSheetDataModel('DefaultSheetDataModelClass'intheon-linedocumentation)class.
FormoredetailsrefertotheSheetView.RemoveRows('RemoveRowsMethod'intheon-linedocumentation)methodorSheetView.RemoveColumns('RemoveColumnsMethod'intheon-linedocumentation)method.
Ifyousimplywanttohidetheroworcolumnfromtheenduser,butnotremoveitfromthesheet,refertoShowingorHidingaRoworColumn.
UsingaShortcut
CalltheRemoveRowsorRemoveColumnsmethodfortheSheetsshortcutobject.Settheroworcolumnparametertospecifytheroworcolumnbeforewhichtoremovetherowsorcolumns.Setthecountparametertospecifythenumberofrowsorcolumnstoremove.
Example
Thisexamplecoderemovestwocolumnsbeforecolumn6.
C#fpSpread1.Sheets[0].RemoveColumns(6,2);
VB
Spread Windows Forms Developer’s Guide 78
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.Sheets(0).RemoveColumns(6,2)
UsingCode
1. CalltheRemoveRows('RemoveRowsMethod'intheon-linedocumentation)orRemoveColumns('RemoveColumnsMethod'intheon-linedocumentation)methodforaSheetView('SheetViewClass'intheon-linedocumentation)object.
2. Settheroworcolumnparametertospecifytheroworcolumnbeforewhichtoremovetherowsorcolumns.3. Setthecountparametertospecifythenumberofrowsorcolumnstoremove.
Example
Thisexamplecoderemovestwocolumnsbeforecolumn6.
C#FarPoint.Win.Spread.SheetView Sheet0;Sheet0 = fpSpread1.Sheets[0];Sheet0.RemoveColumns(6,2);
VBDim Sheet0 As FarPoint.Win.Spread.SheetViewSheet0 = FpSpread1.Sheets(0)Sheet0.RemoveColumns(6, 2)
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttoremovearoworcolumn.2. Selecttherow(s)orcolumn(s)toremovebyselectingtheheader(s).3. Right-clickontheroworcolumnandchooseDelete.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Showing or Hiding a Row or Column
Bydefault,rowsandcolumnsarevisibleonasheet.Youcanhiderowsorcolumnsinasheetsothattheyarenotdisplayed.Youcanalsohiderowheadersandcolumnheaders.YouhidearoworcolumnbysettingtheRow.Visible('VisibleProperty'intheon-linedocumentation)propertyorColumn.Visible('VisibleProperty'intheon-linedocumentation)propertytofalse.Thehiddenrowsorcolumnsarenotdisplayedatruntime,butduringdesigntime,theyarestillvisible.
Whenyouhidearoworcolumn,thesizeoftheroworcolumnisrememberedbytheSpreadcomponent.Ifyouredisplaytheroworcolumn,itisdisplayedatthesizeitwasbeforeitwashidden.Forexample,ifthewidthofacolumnis100pixelsandyouhidethecolumn,whenyouredisplayit,thewidthis100.
Ifyouwanttodetermineifaroworcolumnispresentlyvisibletotheuser,thatis,whetheritappearsintheviewportthatiscurrentlybeingdisplayed,youcanusethemethodsofthesheet.Forexample,tofindoutifacolumnappears,usetheGetViewportLeftColumn('GetViewportLeftColumnMethod'intheon-linedocumentation)andGetViewportRightColumn('GetViewportRightColumnMethod'intheon-linedocumentation)methodstodeterminetheleft-mostandright-mostcolumnsintheviewportandthendetermineifthecolumnfallswithinthoseindexes.
Forinformationonhidingrowsorcolumnsinheaders,refertoShowingorHidingHeaders.
FormoreinformationonhidingrowsorcolumnsusingtheSpreadDesigner,refertotheSpreadDesignerGuide
Spread Windows Forms Developer’s Guide 79
Copyright © GrapeCity, Inc. All rights reserved.
(on-linedocumentation).
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetcollection.3. SelecttheRoworColumncollection.4. Clickoraroworcolumntoselectitandthenselectanoptionfromthedrop-downcombolistfortheVisible
property.
UsingCode
UsetheSetColumnVisible('SetColumnVisibleMethod'intheon-linedocumentation)orSetRowVisible('SetRowVisibleMethod'intheon-linedocumentation)methodforthesheet.
Example
C#fpSpread1.Sheets[0].SetColumnVisible(0,true);fpSpread1.Sheets[0].SetRowVisible(0,false);//Another option is to use the Visible property.fpSpread1.Sheets[0].Columns[1].Visible = false;fpSpread1.Sheets[0].Rows[1].Visible = true;
VBfpSpread1.Sheets(0).SetColumnVisible(0, False)fpSpread1.Sheets(0).SetRowVisible(0, True)'Another option is to use the Visible property.FpSpread1.Sheets(0).Columns(1).Visible = TrueFpSpread1.Sheets(0).Rows(1).Visible = False
UsingtheSpreadDesigner
1. Selecttheroworcolumnbyclickingontheheader.2. SelectanoptionfromtheVisibledrop-downcombolist.3. FromtheFilemenu,selectSaveandExittosavethechanges.
Working with Headers
Youcancustomizetheappearanceofheadercells.Thesetasksrelatetosettingtheappearanceofheadersforrowsorcolumnsinthesheet:
UnderstandingHeadersCreatingaHeaderwithMultipleRowsorColumnsShowingorHidingHeaders
Youcanalsocustomizeheaderappearanceinotherways.
Youcansetthestartingnumberforthedefaultheaderlabels.Ifyouhavemultiplerowsinthecolumnheaders,youcanselectwhichrowdisplaysthesortindicatorandwhichrowdisplaystheautomatictext.
Formoreinformation,refertoCustomizingtheAppearanceofHeadersandtheCell('CellClass'intheon-
Spread Windows Forms Developer’s Guide 80
Copyright © GrapeCity, Inc. All rights reserved.
linedocumentation)andCells('CellsClass'intheon-linedocumentation)objects.
Understanding Headers
Thefollowingfigureshowsthesheetcorner,headers,andcellsandillustratesthecellcoordinatesinheaderswithmultiplerowsandcolumns.Thecoordinatesareshowninparentheses.
Whenyouworkwithrowheadersandcolumnheaders,youcanworkwiththeobjectsusingtheshortcutobjectsincode(RowHeader('RowHeaderClass'intheon-linedocumentation)andColumnHeader('ColumnHeaderClass'intheon-linedocumentation)classes),oryoucanworkdirectlywiththemodel.Mostdeveloperswhoarenotcreatingextensivecustomizationsfinditeasiertoworkwiththeshortcutobjects.
Creating a Header with Multiple Rows or Columns
Youcanprovidemultiplerowsinthecolumnheaderandmultiplecolumnsintherowheader.Asshowninthefollowingfigure,theheadersmayhavedifferentnumbersofcolumnsandrows.
Spread Windows Forms Developer’s Guide 81
Copyright © GrapeCity, Inc. All rights reserved.
Therowsorcolumnsintheheadercanalsocontainspans,forexample,ifyouwanttohaveaheadercellthatexplainstwocellsbeneathit(orsubheaders).Forinstructionsforcreatingaspaninaheader,seeCreatingaSpaninaHeader.
Youcancustomizethelabelsintheseheaders.Forinstructionsforcustomizingthelabels,seeCustomizingHeaderLabelText.Formoreinformationontheindividualproperties,refertotheColumn('ColumnClass'intheon-linedocumentation)Label('LabelProperty'intheon-linedocumentation)propertyortheRow('RowClass'intheon-linedocumentation)Label('LabelProperty'intheon-linedocumentation)property.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. Clickthesheetforwhichyouwanttochangetheheaderdisplay.5. SettheColumnHeaderRowCountpropertytothenumberorrowsyouwantinthecolumnheaderortheRowHeaderColumnCountpropertytothenumberofcolumnsyouwantintherowheader.
6. ClickOKtoclosetheeditor.
UsingaShortcut
SettheColumnHeaderRowCount('ColumnHeaderRowCountProperty'intheon-linedocumentation)propertyortheRowHeaderColumnCount('RowHeaderColumnCountProperty'intheon-linedocumentation)propertyforaSheetsobject.UsetheAddColumnHeaderSpanCell('AddColumnHeaderSpanCellMethod'intheon-linedocumentation)methodtospanthecellsintheheader.UsetheLabelandTextpropertiestoaddthelabelstotheheadercells.
Example
Thisexamplecodecreatesaspreadsheetshowninthefigureabove,withtwocolumnsintherowheaderandthreerowsinthecolumnheader.
C#// Set the number or rows and columns in the headers.fpSpread1.Sheets[0].ColumnHeaderRowCount = 3;
Spread Windows Forms Developer’s Guide 82
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.Sheets[0].RowHeaderColumnCount = 2;// Span the header cells as needed.fpSpread1.Sheets[0].AddColumnHeaderSpanCell(1, 0, 1, 2);fpSpread1.Sheets[0].AddColumnHeaderSpanCell(1, 2, 1, 2);fpSpread1.Sheets[0].AddColumnHeaderSpanCell(1, 4, 1, 2);fpSpread1.Sheets[0].AddColumnHeaderSpanCell(1, 6, 1, 2);fpSpread1.Sheets[0].AddColumnHeaderSpanCell(0, 0, 1, 8);fpSpread1.Sheets[0].AddRowHeaderSpanCell(0, 0, 12, 1);// Set the labels as needed -- using the Label property or// the cell Text property.fpSpread1.Sheets[0].ColumnHeader.Columns[0].Label = "East";fpSpread1.Sheets[0].ColumnHeader.Columns[1].Label = "West";fpSpread1.Sheets[0].ColumnHeader.Columns[2].Label = "East";fpSpread1.Sheets[0].ColumnHeader.Columns[3].Label = "West";fpSpread1.Sheets[0].ColumnHeader.Columns[4].Label = "East";fpSpread1.Sheets[0].ColumnHeader.Columns[5].Label = "West";fpSpread1.Sheets[0].ColumnHeader.Columns[6].Label = "East";fpSpread1.Sheets[0].ColumnHeader.Columns[7].Label = "West";fpSpread1.Sheets[0].ColumnHeader.Cells[0,0].Text = "Fiscal Year 2004";fpSpread1.Sheets[0].ColumnHeader.Cells[1,0].Text = "1st Quarter";fpSpread1.Sheets[0].ColumnHeader.Cells[1,2].Text = "2nd Quarter";fpSpread1.Sheets[0].ColumnHeader.Cells[1,4].Text = "3rd Quarter";fpSpread1.Sheets[0].ColumnHeader.Cells[1,6].Text = "4th Quarter";// Set the row header so that the label displays.fpSpread1.Sheets[0].RowHeader.Columns[0].Width = 45;fpSpread1.Sheets[0].RowHeader.Cells[0,0].Text = "Branch #";
VB’ Set the number or rows and columns in the headers.FpSpread1.Sheets(0).ColumnHeaderRowCount = 3FpSpread1.Sheets(0).RowHeaderColumnCount = 2’ Span the header cells as needed.FpSpread1.Sheets(0).AddColumnHeaderSpanCell(1, 0, 1, 2)FpSpread1.Sheets(0).AddColumnHeaderSpanCell(1, 2, 1, 2)FpSpread1.Sheets(0).AddColumnHeaderSpanCell(1, 4, 1, 2)FpSpread1.Sheets(0).AddColumnHeaderSpanCell(1, 6, 1, 2)FpSpread1.Sheets(0).AddColumnHeaderSpanCell(0, 0, 1, 8)FpSpread1.Sheets(0).AddRowHeaderSpanCell(0, 0, 12, 1)’ Set the labels as needed -- using the Label property or’ the cell Text property.FpSpread1.Sheets(0).ColumnHeader.Columns(0).Label = "East"FpSpread1.Sheets(0).ColumnHeader.Columns(1).Label = "West"FpSpread1.Sheets(0).ColumnHeader.Columns(2).Label = "East"FpSpread1.Sheets(0).ColumnHeader.Columns(3).Label = "West"FpSpread1.Sheets(0).ColumnHeader.Columns(4).Label = "East"FpSpread1.Sheets(0).ColumnHeader.Columns(5).Label = "West"FpSpread1.Sheets(0).ColumnHeader.Columns(6).Label = "East"FpSpread1.Sheets(0).ColumnHeader.Columns(7).Label = "West"FpSpread1.Sheets(0).ColumnHeader.Cells(0,0).Text = "Fiscal Year 2004"FpSpread1.Sheets(0).ColumnHeader.Cells(1,0).Text = "1st Quarter"FpSpread1.Sheets(0).ColumnHeader.Cells(1,2).Text = "2nd Quarter"FpSpread1.Sheets(0).ColumnHeader.Cells(1,4).Text = "3rd Quarter"FpSpread1.Sheets(0).ColumnHeader.Cells(1,6).Text = "4th Quarter"’ Set the row header so that the label displays.FpSpread1.Sheets(0).RowHeader.Columns(0).Width = 45FpSpread1.Sheets(0).RowHeader.Cells(0,0).Text = "Branch #"
Spread Windows Forms Developer’s Guide 83
Copyright © GrapeCity, Inc. All rights reserved.
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttodisplaymultipleheaderrowsorcolumns.2. Inthepropertieslist,intheAppearancecategory,double-clicktheColumnHeaderorRowHeaderproperty
todisplaythepropertiesforthecolumnorrowheader.3. SettheRowCountpropertytothenumberorrowsyouwantinthecolumnheaderortheColumnCount
propertytothenumberofcolumnsyouwantintherowheader.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Showing or Hiding Headers
Bydefault,Spreaddisplayscolumnheadersandrowheaders.Ifyouprefer,youcanturnthemoff,andhidefromviewtherowheadersorcolumnheadersorboth.Thefollowingfigureshowsasheetthatdisplaysonlycolumnheadersandhidestherowheaders.
Ifthesheethasmultipleheaders,usingtheseinstructionstohidetheheadershidesallheaderrowsorheadercolumnsorboth.Ifyouwanttohidespecificrowsorcolumnswithinaheader,youmustspecifytheroworcolumn.Formoredetailsonhidingspecificrowsorcolumns,refertoShowingorHidingaRoworColumn.
Thedisplayofheadersisdonebysimplysettingavisiblepropertyoftheheader.Thiscanbedoneincodewithanyoftheseproperties:
RowHeader('RowHeaderClass'intheon-linedocumentation)classVisible('VisibleProperty'intheon-linedocumentation)propertyColumnHeader('ColumnHeaderClass'intheon-linedocumentation)classVisible('VisibleProperty'intheon-linedocumentation)propertySheetView('SheetViewClass'intheon-linedocumentation)classRowHeaderVisible('RowHeaderVisibleProperty'intheon-linedocumentation)propertySheetView('SheetViewClass'intheon-linedocumentation)classColumnHeaderVisible('ColumnHeaderVisibleProperty'intheon-linedocumentation)property
Alternatively,youcancustomizetheheadersbyprovidingcustomtextorheaderswithmultiplecolumnsorrows,asexplainedinCustomizingtheDefaultHeaderLabelsandCreatingaHeaderwithMultipleRowsorColumns.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.
Spread Windows Forms Developer’s Guide 84
Copyright © GrapeCity, Inc. All rights reserved.
4. Clickthesheetforwhichyouwanttochangetheheaderdisplay.5. SettheColumnHeaderVisibleorRowHeaderVisiblepropertytofalsetoturnoffthedisplayoftheheader.6. ClickOKtoclosetheeditor.
UsingaShortcut
SettheColumnHeaderVisible('ColumnHeaderVisibleProperty'intheon-linedocumentation)orRowHeaderVisible('RowHeaderVisibleProperty'intheon-linedocumentation)propertyforaSheetsobjectortheVisible('VisibleProperty'intheon-linedocumentation)propertyoftheColumnHeaderorRowHeaderobject.
Example
Thisexampleturnsoffthedisplayofthecolumnheader.Youcanuseeitherlineofcode.
C#// Turn off the display of column headers.fpSpread1.Sheets[0].ColumnHeaderVisible = false;fpSpread1.Sheets[0].ColumnHeader.Visible = false;
VB' Turn off the display of column headers.FpSpread1.Sheets(0).ColumnHeaderVisible = FalseFpSpread1.Sheets(0).ColumnHeader.Visible = False
UsingCode
1. CreateanewSheetView('SheetViewClass'intheon-linedocumentation)object.2. SettheSheetView('SheetViewClass'intheon-linedocumentation)objectColumnHeaderVisible('ColumnHeaderVisibleProperty'intheon-linedocumentation)orRowHeaderVisible('RowHeaderVisibleProperty'intheon-linedocumentation)propertytofalse.
3. SetthesheetequaltotheSheetView('SheetViewClass'intheon-linedocumentation)objectyoujustcreated.
Example
Thisexamplecodesetsthefirstsheettonotdisplaycolumnheaders.
C#// Create a new sheet.FarPoint.Win.Spread.SheetView newsheet = new FarPoint.Win.Spread.SheetView();newsheet.ColumnHeaderVisible = false;// Set first sheet equal to SheetView object.fpSpread1.Sheets[0] = newsheet;
VB' Create a new sheet.Dim newsheet As New FarPoint.Win.Spread.SheetView()newsheet.ColumnHeaderVisible = False' Set first sheet equal to SheetView object.FpSpread1.Sheets(0) = newsheet
Spread Windows Forms Developer’s Guide 85
Copyright © GrapeCity, Inc. All rights reserved.
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttoturnoffheaderdisplay.2. Inthepropertieslist,intheAppearancecategory,double-clicktheColumnHeaderorRowHeaderproperty
todisplaythepropertiesforthecolumnorrowheader.3. SettheVisiblepropertytoFalsetoturnofftheheaderdisplay.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Working with Cells
Whenyouworkwithcellsinthedataareaofthespreadsheet,youcanworkwiththeobjectsusingtheshortcutobjectsincode(Cell('CellClass'intheon-linedocumentation)andCells('CellsClass'intheon-linedocumentation)classes),oryoucanworkdirectlywiththemodel.Mostdeveloperswhoarenotcreatingextensivecustomizationsfinditeasiertoworkwiththeshortcutobjects.
Thesetasksrelatetoworkingwithcellsinthedataareaofthespreadsheet:
WorkingwiththeActiveCellCreatingaRangeofCells
Note:Theword"appearance"isusedtomeanthegenerallookofthecell,notjustthesettingsintheAppearanceclass,whichcontainsonlyafewsettingsandisusedfortheappearanceofseveralpartsoftheinterface.MostoftheappearancesettingsforacellareintheStyleInfoclass.
Settingsappliedtoaparticularcelloverridethesettingsthataresetatthecolumnorrowlevel.RefertoObjectParentage.
Othercell-levelappearancesettingsaresetbythecelltype.Formoreinformationonsettingsrelatedtocelltypes,refertoCustomizingInteractionwithCellTypes.YoucaneditpropertiesoftheCellsclassesinthePropertieswindow(inSpreadDesignerorinVisualStudio.NET).FormoreinformationontheCells,Columns,andRowsEditorthatisavailablefromthePropertieswindow,refertotheexplanationofthiseditorintheSpreadDesignerGuide(on-linedocumentation).
ForinformationoncustomizingtheappearanceofcellsusingtheSpreadDesigner,refertotheSpreadDesignerGuide(on-linedocumentation).
Working with the Active Cell
Theactivecellisthecellthatcurrentlyreceivesanyuserinteraction.Theactivecellisthesinglecellthathaskeyboardfocus.Thereisalwaysanactivecell.Usually,theactivecelldisplayssomeindicationthatitisinfocus.
YoucanspecifytheactivecellprogrammaticallyusingtheSetActiveCell('SetActiveCellMethod'intheon-linedocumentation)methodoftheSheetView('SheetViewClass'intheon-linedocumentation)class.YoucanalsousetheActiveCell('ActiveCellProperty'intheon-linedocumentation)propertytofindtheactivecellcoordinates.
TheactivecellisstoredintheActiveRowIndex('ActiveRowIndexProperty'intheon-linedocumentation)andActiveColumnIndex('ActiveColumnIndexProperty'intheon-linedocumentation)propertiesintheSheetViewclass.TheLeaveCell('LeaveCellEvent'intheon-linedocumentation)eventisraisedanytimetheactivecellchanges.
Youcanchangethefocusindicator;formoreinformation,refertoCustomizingtheFocusIndicatorforaCell.
Thecellselectionisoneormorecellsthathavebeenhighlightedbytheuserorapplication.Atanygiventime,theremayormaynotbeacellselectionpresent.Thecellselection(ifpresent)isstoredintheselectionmodelinsidetheSheetViewclass.TheChanged('ChangedEvent'intheon-linedocumentation)event(intheselectionmodel)israisedanytimethecellselectionchanges.
Spread Windows Forms Developer’s Guide 86
Copyright © GrapeCity, Inc. All rights reserved.
SpreadWindowsFormshastwoimplementationsofselectioncoloring.WhentheSelectionStyle('SelectionStyleProperty'intheon-linedocumentation)propertyissettoSelectionColors,thecellispaintedusingselectioncolors(thatis,bothSelectionBackColorandSelectionForeColor).WhentheSelectionStylepropertyissettoSelectionRenderer(whichisthedefault),thecellispaintedusingnormalcoloringandthenoverpaintedwiththeSelectionRenderer.ThedefaultSelectionRendererusesasemi-transparentversionofthesystem'sselectioncolor.
InRowMode,whichisanoperationmodewhereonlyrowscanbeselected,thereisanactivecell.Theactiverowispaintedsimilartoaselectedrow.
SpreadWindowsFormsusesapaintingschemesimilartoExcel.Ifthecellistheactivecellthenthecellispaintedusingnormalcoloringandafocusbox.Ifthecellisselectedthenthecellispaintedusingselectioncoloring,orelsethecellispaintedusingnormalcoloring.
ThereisadifferentpaintingschemeinOpenOffice.Ifthecellisboththeactivecellandaselectedcellthenthecellispaintedusingselectioncoloringandafocusbox.SpreadWindowsFormsdoesnotsupportOpenOffice'spaintingscheme.
Youcanchangewhatcanbeselectedbytheuser.Formoreinformation,refertoSpecifyingWhattheUserCanSelect.Youcanalsocustomizehowtheselectionappears.Formoreinformation,refertoCustomizingtheSelectionAppearance.
UsingaShortcut
YoucanuseActiveCell('ActiveCellProperty'intheon-linedocumentation)asashortcutobjectfortheactivecellwhenspecifyingpropertiesofthatcell.UsetheSetActiveCell('SetActiveCellMethod'intheon-linedocumentation)tosettheactivecell.
Example
Settheactivecellanddonotclearpreviouslyselectedcells.
C#fpSpread1.ActiveSheet.SetActiveCell(2, 2, false);
VBFpSpread1.ActiveSheet.SetActiveCell(2, 2, False)
Creating a Range of Cells
Youcancreatearangeofcellstoallowyoutodefinepropertiesandbehaviorsforthosecells.Arangemaybeanysetofcells.
Tofillrangesusingdrag-and-dropordrag-and-fillactions,refertoUsingDragOperationstoFillCells.
UsingCode
1. DefinearangeofcellsusingtheCell('CellClass'intheon-linedocumentation)object.2. SetpropertiesfortherangesuchastheNote('NoteProperty'intheon-linedocumentation)property.
Example
ThisexamplecodesetstheNote('NoteProperty'intheon-linedocumentation)propertyforarangeofCell('CellClass'intheon-linedocumentation)objects.
C#
Spread Windows Forms Developer’s Guide 87
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Spread.Cell range1;range1 = fpSpread1.ActiveSheet.Cells[1, 1, 3, 3];range1.Value = "Value Here";range1.Note = "This is the note that describes the value.";
VBDim range1 As FarPoint.Win.Spread.Cellrange1 = fpSpread1.ActiveSheet.Cells(1, 1, 3, 3)range1.Value = "Value Here"range1.Note = "This is the note that describes the value."
UsingtheSpreadDesigner
IntheCell,Column,orRoweditorandintheSpreadDesigner,selectthecellsthatyouwanttobeintherange.Propertiesyousetarethenappliedtothosecells.
Spread Windows Forms Developer’s Guide 88
Copyright © GrapeCity, Inc. All rights reserved.
Understanding the Underlying Models
TheSpreadcomponentisbasedonasetofunderlyingmodels:classesthatprovidemostofthefeaturesforthecomponent.Youcanworkdirectlywiththesemodels,oryoucanworkwiththeSpreadDesignerorshortcutobjects.WhenyouperformtasksusingtheSpreadDesignerorshortcutobjects,thetasksactuallyaffectthemodelsthemselves.
Ifyouwanttoprovideextensivecustomizationsforthecomponent,increaseefficiency,orcreateatemplatetousewithinyourworkgroup,youwillprobablywanttocustomizetheSpreadmodels.
ConsultthefollowingtopicsforlistsoftheSpreadmodelsandmoreinformationaboutthemodelclasses.
Thesetopicscanhelpyoucustomizethecomponentusingmodels:
UnderstandingtheTypesofSheetModelsUnderstandingtheSheetModelClassesandInterfacesFindingMoreDetailsontheSheetModelsCreatingaCustomSheetModelUnderstandingtheOptionalInterfaces
Understanding the Types of Sheet Models
TheSpreadcomponentmodelsareillustratedconceptuallyinthefollowingdiagram:
Asshowninthefigure,thedataareaofthespreadsheethasitsownsetofmodels,andtherowheadersandcolumnheadershavemodelsassignedtoeachofthem.Finally,thesheetcornerhasitsownsetofmodels.
Asthediagramillustrates,itcanbeusefultothinkofthesheet(SheetViewobject)asacompositeofthefiveunderlyingmodels.
Axis:TheAxismodelhandleseverythingtodowiththeColumnsandRows(forexample,thecolumnwidth,rowheight,andwhetheraroworcolumnisvisible).Data:TheDatamodelhandleseverythingtodowiththedata(forexample,thevalue,theformula,andanyoptionalnotesortagsinacell)andcontainsthedatainthesheet.Selection:TheSelectionmodelhandlesanycellrangeselectionsthataremade.Span:TheSpanmodelhandlesanyspannedcells.Style:TheStylemodelhandlestheappearancesettingsforthecells(forexample,thebackgroundcolor,thefont,andthecelltype).
YoucandomanytaskswithouteverusingthemodelsbyusingtheSpreadDesignerorpropertiesoftheshortcutobjects(suchasCells,Columns,andRows).Sincesheetmodelsarethebasisforalltheshortcutobjects,usingmodelsisgenerallyfasterthanusingshortcutobjects.Forexample,codeusingtheshortcutobjecttosetavalue:
FpSpread1.Sheets(0).Cells(0,0).Value = "Test"
wouldbeequivalenttousingtheunderlyingdatamodelmethod:
FpSpread1.Sheets(0).DataModel.SetValue(FpSpread1.Sheets(0). GetModelRowFromViewRow(0), FpSpread1.Sheets(0). GetModelColumnFromViewColumn(0), "Test")
Thesheetmodelscorrespondtothebasisofalltheobjectsandsettingsofaparticularsheet.Eachsheethasitsownsetofmodels.IfyouhavemultiplesheetsinyourSpreadcomponent,theneachsheethasitsownsetofmodels.
Therearemanyinterfacesinvolvedinthemodels.Eachmodelclassimplementsanumberofinterfaces,andeachmodelhasone"model"interfacewhichmustbeimplementedtomakeitavalidimplementationforthatparticularmodel.Allreferencestothemodelclassesarethroughtheinterfaces,andnoassumptionsaremadeastowhatinterfacesareimplementedoneachmodel(exceptforthe"model"interfacewhichmustbepresent).Ifthemodelclassdoesnotimplementaparticularinterface,thenthatfunctionalityissimplydisabledinthesheet(thatis,ifIDataSourceSupportisnotimplementbySheetView.Models.Data,thentheDataSourceandDataMemberpropertiesarenotfunctional).Forcompletelistsoftheseinterfaces,youcanlookuptheoverviewforthedefaultmodelclassesintheAssemblyReference(on-linedocumentation).
Understanding the Sheet Model Classes and Interfaces
Thefollowingtableliststhemodelsandtheirassociatedclassesandinterfaces.
Sheet ClassesandInterface Description
Spread Windows Forms Developer’s Guide 89
Copyright © GrapeCity, Inc. All rights reserved.
ModelAxismodel
BaseSheetAxisModel('BaseSheetAxisModelClass'intheon-linedocumentation)
DefaultSheetAxisModel('DefaultSheetAxisModelClass'intheon-linedocumentation)
ISheetAxisModel('ISheetAxisModelInterface'intheon-linedocumentation)
Basisforhowthesheetofcellsisstructuredintermsofrowsandcolumns.Formoreinformation,seeUnderstandingtheAxisModel.
Datamodel
BaseSheetDataModel('BaseSheetDataModelClass'intheon-linedocumentation)
DefaultSheetDataModel('DefaultSheetDataModelClass'intheon-linedocumentation)
ISheetDataModel('ISheetDataModelInterface'intheon-linedocumentation)
Basisforthemanipulationofdatainthecellsinthesheet.Formoreinformation,seeUnderstandingtheDataModel.
Selectionmodel
BaseSheetSelectionModel('BaseSheetSelectionModelClass'intheon-linedocumentation)
DefaultSheetSelectionModel('DefaultSheetSelectionModelClass'intheon-linedocumentation)
ISheetSelectionModel('ISheetSelectionModelInterface'intheon-linedocumentation)
Basisforthebehaviorofandinteractionofselectedcellsinthesheet.Formoreinformation,seeUnderstandingtheSelectionModel.
Spanmodel
BaseSheetSpanModel('BaseSheetSpanModelClass'intheon-linedocumentation)
DefaultSheetSpanModel('DefaultSheetSpanModelClass'intheon-linedocumentation)
ISheetSpanModel('ISheetSpanModelInterface'intheon-linedocumentation)
Basisforhowcellsinthesheetarespanned.Formoreinformation,seeUnderstandingtheSpanModel.
Stylemodel
BaseSheetStyleModel('BaseSheetStyleModelClass'intheon-linedocumentation)
DefaultSheetStyleModel('DefaultSheetStyleModelClass'intheon-linedocumentation)
ISheetStyleModel('ISheetStyleModelInterface'intheon-linedocumentation)
Basisfortheappearanceofthecellsinthesheet.Formoreinformation,seeUnderstandingtheStyleModel.
Spread Windows Forms Developer’s Guide 90
Copyright © GrapeCity, Inc. All rights reserved.
Thesheet(SheetViewobject)isacompositeofthefiveunderlyingmodels(Axis,Data,Selection,Span,andStyle).TheAxismodelhandleseverythingtodowiththeColumnsandRows(forexample,thecolumnwidth,rowheight,andwhetheraroworcolumnisvisible).TheDatamodelhandleseverythingtodowiththedata(forexample,thevalue,theformula,andanyoptionalnotesortagsinacell)andcontainsthedatainthesheet.TheSelectionmodelhandlesanycellrangeselectionsthataremade,andSpanmodelshandlesanyspannedcells.TheStylemodelhandlestheappearancesettingsforthecells(forexample,thebackgroundcolor,thefont,andthecelltype).
Everythingyoudotothemodelisautomaticallyupdatedinthesheetandmostoftheaspectsofthesheetthatyoucanmodifyareupdatedinthemodel.ThisisalsotrueforCell,Row,andColumnobjectsettings,too.Mostoftheaspectschangedwiththeseobjectsautomaticallychangesthesettinginthecorrespondingsheetmodelandviceversa.Ifyouaddcolumnstothedatamodel,thentheyareaddedtothesheet.Thisistrue,evendowntotheparameters;forexampletherowandcolumnargumentsintheGetValueandSetValuemethodsforthedatamodelarethesameindexesasthatoftherowsandcolumnsinthesheetaslongasthesheetisnotsorted.
NoteverythingintheSpreadnamespaceisinthemodels.Forexample,thereareaspectsoftheoverallcomponent,forexample,thesheettabs,thesheetbackgroundcolor,andthegridlines,thatarenotinthemodels.Buttherelevantpiecesofinformationaboutagivencell,bothaboutthedatainthecellsandabouttheappearanceofthecells,areinthemodels.
Thedataareaofthespreadsheethasitsownsetofmodels,andtherowheadersandcolumnheadersareconsideredtwomoresuchgroupshavingmodelsassignedtoeachofthem,andthesheetcornerisanotherwithitsownsetofmodels.
Eachmodelhasabasemodelclass,adefaultmodelclass,andaninterface.
Thebasemodelisthebaseonwhichthedefaultmodeliscreatedandisforcreatingcustommodelsfromscratch.Thedefaultmodelisthemodelwithwhichyoumostlikelywilldevelop;thisprovidesthedefaultfeaturesthatthecomponentoffersandisusedforsmallcustomizationstothemodels.
Thebasemodelhasthefewestbuilt-infeatures,andthedefaultmodelextendsthebasemodel.Ifyouwanttoprovidedifferentfeaturesorcustomizethebehaviororappearanceofyourapplication,youcanextendthebasemodelstocreatenewclasses.Forexampleyoumaydothistocreateatemplatecomponentforallthedevelopersinyourorganization.Bycreatingyourownclassbasedononeofthebasemodels,youcancreatethecustomizedclassandprovideittoallthedeveloperstouse.Typically,ifyouareeditingthemodels,usethedefaultmodelclasses.Butifyouwanttocreateacustommodel(fromscratch),usethebasemodelclasses.
Eachdefaultmodelclasscontainstheimplementationoftheinterfaceforthatmodeltypeaswellasadditionaloptionalinterfaces.Mostofthefunctionality(thatis,formulas,databinding,XMLserialization,etc.)isoptionalinthemodelclass,andisimplementedinseparateinterfacesfromthemainmodelinterfaces(suchasISheetDataModel).Therefore,ifyouwanttoimplementyourownmodelclass,youcanpickandchoosewhichpiecesoffunctionalityyouhaveinyourmodel.
Itisimportantforthemodelstostayinsyncwitheachother,sothattherowcountandcolumncountisconsistentamongthemodelsmakingupthesheet.TheSheetViewobjectlistensfortheISheetDataModel.ChangeeventfromtheSheetView.DocumentModels.Dataproperty,andupdatestheothermodelsaccordinglywhentherowcountorcolumncountchangesduetoanyofthese:
directpropertysettingsfortheRowCountorColumnCountproperties,insert/deleterow/columnoperationsthroughtheIRangeSupportinterfacetheentiredatamodelbeingreplacedwithanewone
Ifthemodelsgetoutofsync,thenindexout-of-rangeexceptionscanbecausedbycodetryingtogetinformationaboutnonexistentrowsorcolumns.
Formoreinformationoncreatingacustommodelforasheet,refertoCreatingaCustomSheetModel.
Finding More Details on the Sheet Models
Thefollowingtopicslistadditionalinformationaboutthemodelsofasheet.
Spread Windows Forms Developer’s Guide 91
Copyright © GrapeCity, Inc. All rights reserved.
UnderstandingtheDataModelUnderstandingtheAxisModelUnderstandingtheSelectionModelUnderstandingtheSpanModelUnderstandingtheStyleModel
Forgeneralinformationaboutthetypesofsheetmodels,refertoUnderstandingtheSheetModelClassesandInterfaces.
Understanding the Data Model
Thedatamodelincludesthecontentsofthecells,includingthevalueortheformulainacell,andthecellnotesorcelltags.ThisincludestheValuepropertiesforcellsinthedataareaofthespreadsheet,thedatabasepropertiesfordata-boundspreadsheets,andanythinghavingtodowiththecontentsinthecells.
YouarelikelytocustomizethedatamodelwhenworkingwithSpread.Thedatamodelimplementsmoreinterfaces,andmoreoptionalfunctionalitythroughit,thananyoftheothermodels.Also,ifyouwanttoimplementtheequivalenttotheunboundvirtualmodelfeatureoftheActiveXSpreadcontrol,forexample,youwillneedtocustomizethedatamodel.
Thefollowingtopicsprovidemoreinformationaboutthedatamodel:
DataModelObjectSettingandAddingtotheDataModelImplementedInterfacesBalanceofSpeedandPerformance
Formoredetails,refertotheBaseSheetDataModel('BaseSheetDataModelClass'intheon-linedocumentation)class,theDefaultSheetDataModel('DefaultSheetDataModelClass'intheon-linedocumentation)class,andtheISheetDataModel('ISheetDataModelInterface'intheon-linedocumentation)interface.
DataModelObject
Thedatamodelisanobjectthatsuppliesthecellvaluesbeingdisplayedinthesheet.Inmostcases,youcansimplyusethedefaultdatamodelthatiscreatedwhenthesheetiscreated.
Thedefaultdatamodel,DefaultSheetDataModel('DefaultSheetDataModelClass'intheon-linedocumentation),createsobjectstostorenotes,formulas,tags,andvalues,andthoseobjectsaredesignedtobalancememoryusageversusspeedbasedonhowbigthemodelisandhowsparsethedatainthemodelis.Ifyouarenotusingnotes,formulas,andtags,thenthecomponentdoesnotusemuchmemorybecausethedataisfairlysparse.Infact,thoseobjectsdonotallocateanymemoryfordatauntilitisactuallyneeded;therefore,aslongastherearenonotes,formulas,ortagssetinthemodel,memoryusageremainslow.
Thedefaultdatamodelcanbeusedinunboundmodeorboundmode.Inunboundmode,thedatamodelactssimilarlytoatwo-dimensionalarrayofcellvalues.Inboundmode,thedatamodelwrapsthesupplieddatasourceandifneededcansupplyadditionalsettingsnotavailablefromthedatasource,forexample,cellformulasandunboundrowsorcolumns.
SettingandAddingtotheDataModel
TheSetModelDataColumn('SetModelDataColumnMethod'intheon-linedocumentation)isdifferentfromAddColumn('AddColumnMethod'intheon-linedocumentation)inthatyoucanspecifywhichdatafieldyouwantboundtowhichcolumninthedatamodel.
Ifyouaddcolumnstothemodel,thentheyareaddedtothesheet.TherowandcolumnintheGetValue('GetValueMethod'intheon-linedocumentation)andSetValue('SetValueMethod'intheon-linedocumentation)methodsofthedatamodelhavethesameindexesasthatofthecolumnsinthesheetaslongasthesheetisnotsorted.Ifthesheet'srowsorcolumnsaresorted,thentheviewcoordinatesmustbemappedtothemodelcoordinateswiththeseSheetView.GetModelRowFromViewRow('GetModelRowFromViewRowMethod'intheon-linedocumentation)andSheetView.GetModelColumnFromViewColumn('GetModelColumnFromViewColumnMethod'intheon-linedocumentation)methods.
TheSheetView.GetValue('GetValueMethod'intheon-linedocumentation)andSheetView.SetValue('SetValueMethod'intheon-linedocumentation)methodsalwaysgetandsetthedatainthedatamodel.CallingthesemethodsisthesameascallingSheetView.Models.Data.GetValue('GetValueMethod'intheon-linedocumentation)andSheetView.Models.Data.SetValue('SetValueMethod'intheon-linedocumentation).TheCell.Value('ValueProperty'intheon-linedocumentation)propertyreturnsthevalueofthecellintheeditorcontrolifthecelliscurrentlyineditmodeinaSpreadViewcontainingtheSheetView.Thatvalueisnotupdatedtothedatamodeluntilthecellleaveseditmode;however,youcanmanuallyupdatethevalueinthedatamodelusingcode:
SheetView.SetValue(row, column, SheetView.Cells(row, column).Value)
ImplementedInterfaces
WhenthedatamodelimplementsIDataSourceSupport('IDataSourceSupportInterface'intheon-linedocumentation)anditisboundtoadatasource,theboundpartsofthedatamodelgetandsetdatadirectlyfromthedatasource.SomecolumnsinabounddatamodelcanbeunboundifcolumnsareaddedtothedatamodelwithAddColumns('AddColumnsMethod'intheon-linedocumentation)afteritisbound(IDataSourceSupport.IsColumnBound('IsColumnBoundMethod'intheon-linedocumentation)returnsFalseforthosemodelcolumnindexes),andthevaluesinthoseunboundcolumnsarestoredinthedatamodelratherthanthedatasource.
IfthedatamodelalsoimplementsIUnboundRowSupport('IUnboundRowSupportInterface'intheon-linedocumentation),thensomerowsinthedatamodelcanalsobeunbound,andthosevaluesarealsostoredinthedatamodelratherthanthedatasource.SuchrowscanbemadeintoboundrowsbycallingIUnboundRowSupport('IUnboundRowSupportInterface'intheon-linedocumentation).AddRowToDataSource('AddRowToDataSourceMethod'intheon-linedocumentation),andiftheautoFillparameterisspecifiedasTrue,thenthedataintheboundcolumnsinthatunboundrowwillbeaddedtothedatasourceinanewrecordorelement,assumingthatthedatasourcepermitsit(youwillgetanexceptionifitdoesnot),andtheunboundrowbecomesaboundrow.
Thedefaultdatamodelclass,DefaultSheetDataModel('DefaultSheetDataModelClass'intheon-linedocumentation),implementsalloftheseinterfaces,plusmanyothersrelatedtocalculation,hierarchy,andserialization.
Toseethedifferencebetweenthedefaultdatamodelandtheobjectsonthesheet,reviewthefollowingcodesnippets.ThesecodesnippetsbindthesheettoadatasourcecalledMyData.
FpSpread1.Sheets(0).DataSource = MyData.Tables(0)
Spread Windows Forms Developer’s Guide 92
Copyright © GrapeCity, Inc. All rights reserved.
and
Dim model As FarPoint.Win.Spread.Model.DefaultSheetDataModel = New FarPoint.Win.Spread.Model.DefaultSheetDataModel(MyData, strTable)
FpSpread1.Sheets(0).Models.Data = model
Inthefirstcodesnippet,theexistingdatamodelisusedandresizedtothedatasource;inthesecondsnippet,thedatamodelisreplacedwithanewoneandtheoldonediscarded.Theoutcomeisthesameinbothexamples,butthefirstexampleresultsintheolddatamodelgettinggarbagecollected.Generallyyoumightnotwanttoreplacethedatamodelunlessyouarecreatingyourowndatamodelclass.ThereisgenerallynoneedtoreplacethedatamodelwithanotherDefaultSheetDataModelsincethereisalreadyonetheretouse.
BalanceofSpeedandPerformance
IfyouderivefromDefaultSheetDataModel('DefaultSheetDataModelClass'intheon-linedocumentation)andusethatimplementationofGetValue('GetValueMethod'intheon-linedocumentation)andSetValue('SetValueMethod'intheon-linedocumentation)tostorethedata,thenitwillusetheSpreadimplementationofsparsearraysandmatricestobalancethememoryusagewiththeaccessspeed.Thisimplementationisdesignedtomakeitveryfasttocreateaverylargemodel(thatis,2billionrowsby2billioncolumns)andkeepitreasonablyfasttogetandsetvaluesintoit,untilthenumberofvaluesgetsverylarge(inwhichcaseyouwillstarttorunoutofmemoryanyway).
Incaseswherethemodelisverylargeand/orsparse(thatis,morethantwo-thirdsempty),accessspeedisslower(abinarysearchisrequired)andmemoryusageislower.Incaseswherethemodelisnotverylarge(lessthan32Krowsand/orcolumns)andnotsparse(morethanone-thirdfull),thentheaccessspeedisfaster(nobinarysearchrequired)andmemoryusageishigher.
YoucanrunsomesimpletestsbycreatingatestprojectwithSpreadonaform,andsettingtheColumnCount('ColumnCountProperty'intheon-linedocumentation)andRowCount('RowCountProperty'intheon-linedocumentation)forthesheettoverylargenumbers,andyoushouldnotseeanydelayatallbecausethememoryallocatedisbasedontheactualnumberofdataitems.Ifyoustarttofillthesheetwithlotsandlotsofdata,thenyouwillnoticedelaysafterawhile,especiallywhenmemorygetslowandthesystemstartsusingthepagefiletoswapvirtualmemory(itwilltakeaverylargequantityofdataforthattohappenthough).
Understanding the Axis Model
Theaxismodelincludesthemethodsthatmanagerow-andcolumn-relatedsettingsofthespreadsheet(howtherowsandcolumnsofcellsareorientedonthesheet).Theaxismodelincludesmanyoftheaxis-relatedsettingsinthefollowingshortcutobjects:
Column,ColumnsRow,RowsAlternatingRow,AlternatingRows
Thesesettingsinclude:
rowheightcolumnwidthrowvisiblecolumnvisible
Tousetheunderlyingaxismodel,usethemethodsoftheaxismodel.TheseincludetheSetSize('SetSizeMethod'intheon-linedocumentation)method,forsettingtherowheightorcolumnwidth,andtheSetVisible('SetVisibleMethod'intheon-linedocumentation)methodforsettingtheroworcolumnvisibleproperties.Thereareothermethods,too,suchasSetMergePolicy('SetMergePolicyMethod'intheon-linedocumentation),whichsetspecificpropertiesoftheroworcolumn,inthiscasewhethercellscanbeautomaticallymergedwhentheircontentisidentical.RefertotheDefaultSheetAxisModel('DefaultSheetAxisModelClass'intheon-linedocumentation)classformoreinformationontheaxismodelingeneralandthemethodsinparticular.
Asanexampleofhowyoucouldusetheaxismodeltoimproveperformanceofaspreadsheet,consideraspreadsheetwithaverylargenumberofrows.Ifyouareresizingtherowsbasedonthedata,thenyoumightwanttocreateacustomaxismodelforSheetView.Models.RowAxis('RowAxisProperty'intheon-linedocumentation)toreturnthisvalue.Todoso,createaclassderivedfromDefaultSheetAxisModel('DefaultSheetAxisModelClass'intheon-linedocumentation)thattakesareferencetotheSheetViewinitsconstructorandstoresitinafield.ThenoverridetheGetSize('GetSizeMethod'intheon-linedocumentation)methodtocallGetPreferredRowHeight('GetPreferredRowHeightMethod'intheon-linedocumentation)(intheSheetView)fortherowindex.YoucanalsooverridetheGetResizable('GetResizableMethod'intheon-linedocumentation)methodtopreventtheuserfromtryingtochangetherowheightsmanually,whichwillnotworksinceGetSize('GetSizeMethod'intheon-linedocumentation)isalwaysreturningthepreferredheight.
Thefollowingcodeprovidesanexamplethatmakeseachrowthreetimeswiderthanthedefaultwidth.
C#
Spread Windows Forms Developer’s Guide 93
Copyright © GrapeCity, Inc. All rights reserved.
public class MyRowAxisModel : FarPoint.Web.Spread.Model.DefaultSheetAxisModel{ public overrides int GetSize(int index) { if ( index % 2 == 1 ) return 60; else return 20; }}
VBPublic Class MyRowAxisModel Inherits FarPoint.Web.Spread.Model.DefaultSheetAxisModel Public Overrides Function GetSize(index As Integer) As Integer If index \ 2 = 1 Then Return 60 Else Return 20 End If End FunctionEnd Class
Formoredetails,refertotheBaseSheetAxisModel('BaseSheetAxisModelClass'intheon-linedocumentation)class,theDefaultSheetAxisModel('DefaultSheetAxisModelClass'intheon-linedocumentation)class,andtheISheetAxisModel('ISheetAxisModelInterface'intheon-linedocumentation)interface.
Understanding the Selection Model
Theselectionmodelincludesanyofthesettingsrelatedtorangesofselectedcells.Theselectionmodelincludesmethodssuchascountingthenumberofselectedranges,addingandremovingselections,clearingselections,andfindingwhetheracellisselected.
Tousetheunderlyingselectionmodel,usethemethodsoftheselectionmodel.TheseincludetheSetSelection('SetSelectionMethod'intheon-linedocumentation)method,forsettingcellsasselected,andtheAddSelection('AddSelectionMethod'intheon-linedocumentation),ClearSelection('ClearSelectionMethod'intheon-linedocumentation),andRemoveSelection('RemoveSelectionMethod'intheon-linedocumentation)methodsforadding,clearing,andremovingselectedrangesfromthesheet.RefertotheDefaultSheetSelectionModel('DefaultSheetSelectionModelClass'intheon-linedocumentation)classformoreinformationontheselectionmodelingeneralandthemethodsinparticular.
Thedefaultimplementationoftheselectionmodel(DefaultSheetSelectionModel('DefaultSheetSelectionModelClass'intheon-linedocumentation))handlestheselectionofcellsandrangesinthesheetandstorestheactualcellandrangecoordinatesforeachselection.TheSpreadViewobjecthandlestheuserinterfacefortheSheetViewobjectandupdatestheselectionmodelfromvariouseventhandlers.
Theselectionmodelhandlestheselectiondata,includingcomputingtherangebeingselectedbasedonthecellclicked(theanchorcell)andthecellunderthemousepointer.TheSheetView.GetSelection('GetSelectionMethod'intheon-linedocumentation)methodandSheetView.SelectionCount('SelectionCountProperty'intheon-linedocumentation)propertywraptheISheetSelectionModel('ISheetSelectionModelInterface'intheon-linedocumentation)indexerandCount('CountProperty'intheon-linedocumentation)property.Whenthereisnoselectioninthemodel,thecountis0andGetSelection('GetSelectionMethod'intheon-linedocumentation)returnsnull.
Someeventscausetheanchorcellintheselectionmodeltobeset(forexample,leftmousebuttondownonacell)sotheselectionmodelhastheactivecellasaselection.IfyouentereditmodethencancelitbypressingtheEscapekey(Esc),orifyouusethekeyboardtomovetheactivecellaroundinsteadofthemouse,thentheselectionmodelmightbe
Spread Windows Forms Developer’s Guide 94
Copyright © GrapeCity, Inc. All rights reserved.
cleared.YoushouldchecktheSelectionCount('SelectionCountProperty'intheon-linedocumentation)beforeusingGetSelection('GetSelectionMethod'intheon-linedocumentation),andinthecasewhereitreturns0,usetheActiveColumnIndex('ActiveColumnIndexProperty'intheon-linedocumentation)andActiveRowIndex('ActiveRowIndexProperty'intheon-linedocumentation)properties.
Theselectionmodelissavedtotheviewstateonlyifitcontainsatleastoneselection.
Formoredetails,refertotheBaseSheetSelectionModel('BaseSheetSelectionModelClass'intheon-linedocumentation)class,theDefaultSheetSelectionModel('DefaultSheetSelectionModelClass'intheon-linedocumentation)class,andtheISheetSelectionModel('ISheetSelectionModelInterface'intheon-linedocumentation)interface.
Formoreinformationonworkingwithselectionsprogrammatically,refertoWorkingwithSelections.
Understanding the Span Model
Thespanmodelincludestheobjectsneededtohandlecellspansandautomaticmergingofcells.RefertotheCell('CellClass'intheon-linedocumentation)class,ColumnSpan('ColumnSpanProperty'intheon-linedocumentation)andRowSpan('RowSpanProperty'intheon-linedocumentation)properties.
Tousetheunderlyingspanmodel,usetheAdd('AddMethod'intheon-linedocumentation),Clear('ClearMethod'intheon-linedocumentation),andRemove('RemoveMethod'intheon-linedocumentation)methodsofthespanmodel.RefertotheDefaultSheetSpanModel('DefaultSheetSpanModelClass'intheon-linedocumentation)classformoreinformationonthespanmodelingeneralandthemethodsinparticular.
Thedefaultimplementationofthespanmodel(DefaultSheetSpanModel('DefaultSheetSpanModelClass'intheon-linedocumentation))usesanarraytostoredthecellspans.Ifthereareamoderatenumberofspansinthesheet(forexample,athousandorless)thenthedefaultimplementationworksfine.Ifthereareaverylargenumberofspansinthesheet(forexample,ahundredthousandormore)thenthedefaultimplementationslowsdramatically.Inscenarioswhereyouhaveaverylargenumberofspansthatrepeatonaregularinterval,youshouldconsiderwritingacustomspanmodel.Bywritingacustomspanmodel,youcansignificantlyincreasethespeedanddecreasethememoryusage.
Formoredetails,refertotheBaseSheetSpanModel('BaseSheetSpanModelClass'intheon-linedocumentation)class,theDefaultSheetSpanModel('DefaultSheetSpanModelClass'intheon-linedocumentation)class,andtheISheetSpanModel('ISheetSpanModelInterface'intheon-linedocumentation)interface.
Understanding the Style Model
Thestylemodelincludesappearancesettingswhichmightbe:
SetintheSpreadDesignerSetaspropertiesinthePropertiesListInheritedfromacustomskinforawholesheetorfromacustomstyleforindividualcells
Formoreinformationonappearancesettingsforasheet,refertoCreatingaCustomSkinforaSheetandApplyingaSkintoaSheet.Formoreinformationonappearancesettingsforacell,refertoCreatingandApplyingaStyleforCells.
Moreinformationaboutthestylemodelisprovidedinthefollowingtopics:
SettingsandObjectsforStyleOrderofInheritanceofStylesCompositedorInheritedStylesStyleNameFormatObjects
Spread Windows Forms Developer’s Guide 95
Copyright © GrapeCity, Inc. All rights reserved.
Thestylemodelincludesthecelltypesaswell.Thevariouscelltypesdeterminetheappearanceofacellinseveralways.Formoreinformationaboutthevariouscelltypes,refertoCustomizingInteractionwithCellTypes.
RefertotheDefaultSheetStyleModel('DefaultSheetStyleModelClass'intheon-linedocumentation)classformoreinformationonthestylemodelingeneralandthemethodsinparticular.
Formoredetails,refertotheBaseSheetStyleModel('BaseSheetStyleModelClass'intheon-linedocumentation)class,theDefaultSheetStyleModel('DefaultSheetStyleModelClass'intheon-linedocumentation)class,andtheISheetStyleModel('ISheetStyleModelInterface'intheon-linedocumentation)interface.
SettingsandObjectsforStyle
TheappearancesettingsmaybesetfromanyofthefollowingclassesintheFarPointSpreadnamespacethatrepresentshortcutobjects:
Cell('CellClass'intheon-linedocumentation)Column('ColumnClass'intheon-linedocumentation)Row('RowClass'intheon-linedocumentation)AlternatingRow('AlternatingRowClass'intheon-linedocumentation)
TheycanalsobesetfromanyoftheseclassesintheFarPointSpreadnamespacethataffectstyle:
Appearance('AppearanceClass'intheon-linedocumentation)DefaultSkins('DefaultSkinsClass'intheon-linedocumentation)NamedStyle('NamedStyleClass'intheon-linedocumentation)SheetSkin('SheetSkinClass'intheon-linedocumentation)
PropertiesthatcorrespondtoStyleInfo('StyleInfoClass'intheon-linedocumentation)propertiesarestoredinthestylemodelthroughtheISheetStyleModel('ISheetStyleModelInterface'intheon-linedocumentation)interface.Stylepropertiescanbesetforacell,row(columnindex-1),column(rowindex-1),ortheentiremodel(columnandrowindex-1).Propertiesthatarenotsetinacellareinheritedfromtherowsetting,orthecolumnsettingiftherowhasnosetting,orthemodeldefaultifthecolumnalsohasnosetting.
ThedefaultisexposedthroughtheDefaultStyleproperty(SheetView('SheetViewClass'intheon-linedocumentation).DefaultStyle,ColumnHeader('ColumnHeaderClass'intheon-linedocumentation).DefaultStyle,andRowHeader('RowHeaderClass'intheon-linedocumentation).DefaultStyle).IfyousetorgetastylepropertyusingRows.DefaultorRows[-1]orColumns.DefaultorColumns[-1],thenyouwillactuallybesettingorgettingtheDefaultStyleproperty.ThisisbecauseColumnandRowalwaysuserowindex-1andcolumnindex-1whenaccessingthestylemodel,respectively,andsousingacolumnindexorarowindexof-1willbesettingorgettingthemodeldefault.
OrderofInheritanceofStyles
TheorderofinheritanceisdescribedinObjectParentage.Hereisalistofthestylepropertiesthatareincludedinthestylemodel,whicharebasicallythemembersoftheStyleInfo('StyleInfoClass'intheon-linedocumentation)classandaffecttheappearanceorstyleofacell:
BackColor('BackColorProperty'intheon-linedocumentation)Border('BorderProperty'intheon-linedocumentation)CellType('CellTypeProperty'intheon-linedocumentation)Editor('EditorProperty'intheon-linedocumentation)Font('FontProperty'intheon-linedocumentation)ForeColor('ForeColorProperty'intheon-linedocumentation)Formatter('FormatterProperty'intheon-linedocumentation)HorizontalAlignment('HorizontalAlignmentProperty'intheon-linedocumentation)Locked('LockedProperty'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 96
Copyright © GrapeCity, Inc. All rights reserved.
Renderer('RendererProperty'intheon-linedocumentation)VerticalAlignment('VerticalAlignmentProperty'intheon-linedocumentation)
CompositedorInheritedStyles
ThestylepropertiesforacellcanbecompositedormergedfromtheCell('CellClass'intheon-linedocumentation),Row('RowClass'intheon-linedocumentation),Column('ColumnClass'intheon-linedocumentation),SheetView('SheetViewClass'intheon-linedocumentation),andparentNamedStyle('NamedStyleClass'intheon-linedocumentation)objects.
Tousetheunderlyingstylemodel,usethemethodsofthestylemodelforthatsheet,specificallytheGetDirectInfo('GetDirectInfoMethod'intheon-linedocumentation)methodandSetDirectInfo('SetDirectInfoMethod'intheon-linedocumentation)method,andthesettingsintheStyleInfo('StyleInfoClass'intheon-linedocumentation)object."Direct"inthestylemodelmeans"notcomposite"or"notinherited."SetDirectInfo('SetDirectInfoMethod'intheon-linedocumentation)setsthestylepropertiesthathavebeensetforthespecifiedcell,column,orrowdirectlyanddoesnotreturnanysettingsthataresetforhigherlevels(suchastheentiremodel),whileGetCompositeInfo('GetCompositeInfoMethod'intheon-linedocumentation)givesthestyleproperties"composed"or"merged"intooneStyleInfo('StyleInfoClass'intheon-linedocumentation)objectthatcontainsallthesettingsthatareusedtopaintandeditthecell,column,orrow,includinganyinheritedsettings.
StyleName
SettingStyleNamereplacesthestyleinthestylemodelwiththeNamedStyle('NamedStyleClass'intheon-linedocumentation)havingthespecifiedname.ReplacingthestylewiththeNamedStylechangesthesettingsofallofthestyle-relatedproperties,includingParentStyleName(whichwrapsStyleInfo.Parent('ParentProperty'intheon-linedocumentation)).Anyprevioussettingforstyle-relatedpropertieslikeBackColor,Font,Border,orParentStyleNameareoverwrittenwhenyousetStyleName.AllofthesepropertiesarealreadysetintheNamedStyle('NamedStyleClass'intheon-linedocumentation)object;thecomponent’spropertiesarenotchangedjustbecauseyouassignedtheNamedStyletoacell,column,roworalternatingrow.Thenamedstyleisexpectedtoalreadybesetupthewayyouwantittobe.IfthisincludesthenamedstylehavingaparentNamedStyle,thenyoushouldhavethatparentsetalreadywhenyouassignitwithStyleName,oryoushouldassignitseparatelyusingareferencetotheNamedStyleobject(thishasthesameeffectassettingParentStyleNameaftersettingStyleName).
KeepinmindthatafteryouhavesetStyleName,allcellswhereyouhaveusedthatnamearesharingthesameNamedStyle('NamedStyleClass'intheon-linedocumentation)object,andanychangesthatyoumaketooneofthosecellswillalsochangealloftheothercellssharingthesamenamedstyle.
ThefollowingcodecreatestwoNamedStyle('NamedStyleClass'intheon-linedocumentation)objectswithaparent-childrelationship,thensetssomepropertiesonthestylesandaddsthemtotheNamedStyleCollectionintheSpreadcomponent.
C#NamedStyle test_parent = new NamedStyle("test_parent");test_parent.BackColor = Color.Red;test.ForeColor = Color.White;FpSpread1.NamedStyles.AddRange(new NamedStyle[] {test_parent, test});FpSpread1.Sheets(0).Columns(0).BackColor = Color.Blue;FpSpread1.Sheets(0).Rows(0).CellType = new NumberCellType();FpSpread1.Sheets(0).Cells(0,0).StyleName = "test";FpSpread1.Sheets(0).Cells(1,0).StyleName = "test";
VBtest_parent = new NamedStyle("test_parent")test_parent.BackColor = Color.Redtest.ForeColor = Color.WhiteFpSpread1.NamedStyles.AddRange(New NamedStyle() {test_parent, test})
Spread Windows Forms Developer’s Guide 97
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.Sheets[0].Columns[0].BackColor = Color.BlueFpSpread1.Sheets[0].Rows[0].CellType = New NumberCellType()FpSpread1.Sheets[0].Cells[0,0].StyleName = "test"FpSpread1.Sheets[0].Cells[1,0].StyleName = "test"
Intheexample,thebackgroundcolorforthefirstcolumnissettoblueandthecelltypeforthefirstrowissettoNumber,andthefirstcellsinthefirsttworowsarebothsettousetheNamedStylenamed"test."Theresultisthatthecellsinthefirstcolumnareblue,exceptforthecellsinthefirsttworows,whichareredbecausethe"test"styleinheritstheredbackgroundcolorfromitsparentNamedStyle.Theparentstyleoverridestheinheritedsettingforthecolumn.
ThecelltypeforthefirstcellisNumber,sincethereiscelltypesetineitherNamedStyleobject.Thereisacelltypesetinthefirstrowwhichisinheritedbyallcellsintherow.ThecelltypeforthesecondcellisGeneralsincethereisnocelltypesettingforthecell,row,orcolumn.ThedefaultcelltypeforthesheetisGeneral.Formoreinformationoninheritanceofstylesettings,refertoObjectParentage.
FormatObjects
TheFormatInfostringsinasavedXMLfileareDateTimeFormatInfoorNumberFormatInfoobjectsthatstoretheformatofthedata.ThesearecreatedinthestylemodelwhenaGeneralcellisedited,ifthestylemodelimplementsIParseFormatSupport('IParseFormatSupportInterface'intheon-linedocumentation).Theseformatobjectsallowthecellstodisplaythedatainthesameformatthatwasusedtoenterit.
TheGeneralcelltypeparsesthestringintoanumberorDateTime,andgeneratestheIFormatProviderandformatstringnecessarytorenderthedataasitwasentered.IfyouuseTextCellTypeinsteadofGeneralCellType,thenitworksthesameastheEditcellsdidintheActiveXFarPointSpread,andnoFormatInfoisstoredinthestylemodel,butthedataenteredintothecellsisalwaystreatedastext.
Creating a Custom Sheet Model
Youcanuseasheetmodelasatemplateforanewcustommodel.Forexample,considermakingacustomdatamodel.UsingacustomdatamodelrequirescreatingaclassthatimplementsISheetDataModel('ISheetDataModelInterface'intheon-linedocumentation),thensettinganinstanceoftheclassintotheSheetView.Models.Data('DataProperty'intheon-linedocumentation)property.
ISheetDataModel('ISheetDataModelInterface'intheon-linedocumentation)istheonlyinterfacerequired,assumingthatyoudonotneedanyoftheoptionalinterfaces.Formoreinformationontheotherinterfaces,refertoUnderstandingtheOptionalInterfaces.
AlloftheoptionalinterfacesareimplementedbyDefaultSheetDataModel('DefaultSheetDataModelClass'intheon-linedocumentation);therefore,ifyouwantanyoftheoptionalinterfacesimplementedinyourdatamodel,itmightbeeasiertosimplysubclassDefaultSheetDataModel('DefaultSheetDataModelClass'intheon-linedocumentation).
Note:InBaseSheetDataModel('BaseSheetDataModelClass'intheon-linedocumentation),theChangedeventisalsoimplemented.
Inafewcases,youmightneedtocreateyourowncustomdatamodelforperformancereasons.Forexample,supposeyouwanttodisplayalargetableofcomputedvalues(suchasanadditionormultiplicationtable)thatconsistsofamillionrowsbytencolumns.Ifyouusedthedefaultsheetdatamodel,youwouldneedtocomputeandstorealltenmillionvalues,whichwouldbeconsumealotoftimeandmemory.
Instead,youmightwanttocreateyourowncustomdatamodel,asshowninthefollowingexample.
Example
C#for (r = 0; r < 1000000; r++)
Spread Windows Forms Developer’s Guide 98
Copyright © GrapeCity, Inc. All rights reserved.
for ( c = 0; c < 10; c++)spread.Sheets[0].Cells[r,c].Value = r + c;
Example
C#class ComputedDataModel : BaseSheetDataModel{ public override int RowCount { get { return 1000000; } } public override int ColumnCount { get { return 10; } } public override object GetValue(int row, int column) { return row + column; }}
Understanding the Optional Interfaces
Besidestheinterfacesthatarededicatedtoeachofthespecificmodels,therearealsooptionalinterfacesthatprovideadditionalsupportandmaybeusedwhenmakingcustommodels.Theseoptionalinterfacesandthecustomizationstheyallowaresummarizedinthistable:
OptionalInterface CustomizationsAllowedIArraySupport('IArraySupportInterface'intheon-linedocumentation)
Allowscustomizationofsupportforgettingandsettingarraysofvaluesinarangeofcells
IDataSourceSupport('IDataSourceSupportInterface'intheon-linedocumentation)
Allowscustomizationofdatabindingonasheet
IChildModelSupport('IChildModelSupportInterface'intheon-linedocumentation)
Allowscustomizationofhierarchicaldatamodelsforhierarchiesonasheet;usedinconjunctionwithIDataSourceSupport('IDataSourceSupportInterface'intheon-linedocumentation)
ICalculationSupport('ICalculationSupportInterface'intheon-linedocumentation),ICustomFunctionSupport('ICustomFunctionSupportInterface'intheon-linedocumentation),ICustomNameSupport('ICustomNameSupportInterface'intheon-linedocumentation),IExpressionSupport('IExpressionSupportInterface'intheon-linedocumentation),IExpressionSupport2('IExpressionSupport2Interface'intheon-linedocumentation),IIterationSupport('IIterationSupportInterface'intheon-linedocumentation)
Allowscustomizationofformulasonasheet;ICustomFunctionSupport('ICustomFunctionSupportInterface'intheon-linedocumentation),ICustomNameSupport('ICustomNameSupportInterface'intheon-linedocumentation),andIIterationSupport('IIterationSupportInterface'intheon-linedocumentation)arenotusefulwithoutIExpressionSupport('IExpressionSupportInterface'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 99
Copyright © GrapeCity, Inc. All rights reserved.
IDisjointSelections('IDisjointSelectionsInterface'intheon-linedocumentation),IQuerySelection('IQuerySelectionInterface'intheon-linedocumentation)
Allowscustomizationofanorderedarrayofcellrangescontainingtheselectedcellswiththeminimaloverlapbetweentherangesonasheet
INamedStyle('INamedStyleSupportInterface'intheon-linedocumentation),IParseFormatSupport('IParseFormatSupportInterface'intheon-linedocumentation)
Allowscustomizationofcollectionsofcustomstylesinthestylemodel
INonEmptyCells('INonEmptyCellsInterface'intheon-linedocumentation)
Allowscustomizationofnon-emptycountstofindoutwhichrowsorcolumnshavedatainthecellsofthatroworcolumnonasheet
IOptimizedEnumerationSupport('IOptimizedEnumerationSupportInterface'intheon-linedocumentation),IOptimizedEnumerationSupport2('IOptimizedEnumerationSupport2Interface'intheon-linedocumentation)
Allowscustomizationofoptimizedenumerationforiteratingtothenextnon-emptyroworcolumnonasheet
IMovable('IMovableInterface'intheon-linedocumentation),IRangeSupport('IRangeSupportInterface'intheon-linedocumentation)
Allowscustomizationofmoving,inserting,anddeletingrowsandcolumnssupportforarangeofcellsonasheet;alsocoversclear,copy,move,andswapsupport
IUnboundRowSupport('IUnboundRowSupportInterface'intheon-linedocumentation)
Allowscustomizationofunboundrowswithdatabindingonasheet;usedinconjunctionwithIDataSourceSupport('IDataSourceSupportInterface'intheon-linedocumentation)
NoneoftheseoptionalinterfacesarerequiredforsavingExcelortextfiles,orforprinting.Formoredetailedinformationontheseinterfaces,refertotheFarPoint.Win.Spread.Model('FarPoint.Win.Spread.ModelNamespace'intheon-linedocumentation)namespaceintheAssemblyReference.
Formoreinformationonformulasincells,referManagingFormulasinCells.
Spread Windows Forms Developer’s Guide 100
Copyright © GrapeCity, Inc. All rights reserved.
Customizing the Sheet Appearance
YoucancustomizetheappearanceofvariouspartsoftheSpreadcomponent.
ThetasksthatrelatetosettingtheappearanceofobjectsintheSpreadcomponentinclude:
CustomizingtheOverallComponentAppearanceCustomizingtheIndividualSheetAppearanceCustomizingtheSheetCornerAppearance
ForinformationoncustomizingtheinteractionwithpartsoftheSpreadcomponent,refertoCustomizingSheetInteraction.
ForinformationoncustomizingtheappearanceusingtheSpreadDesigner,refertotheSpreadDesignerGuide(on-linedocumentation).
Customizing the Overall Component Appearance
YoucansetseveralaspectsthatdeterminetheappearanceoftheoverallSpreadcomponent.Thesetasksrelatetosettingtheappearanceoftheoverallcomponent:
SettingtheComponenttotheOriginalAppearanceApplyingaSkintotheComponentCreatingaCustomSkinforaComponentCustomizingtheRenderersCustomizingtheDimensionsoftheComponentCustomizingtheOutlineoftheComponentCustomizingtheDisplayofthePointerCustomizingPaintingofPartsoftheComponentUsingXPThemeswiththeComponentHandlingRight-to-LeftLayouts
Othertopicsrelatedtooverallappearanceinclude:
SettingtheBackgroundColorsforaSheetDisplayingGridLinesonaSheet
Forinformationonotheraspectsoftheoverallcomponent,refertoCustomizingInteractionintheOverallComponent.
Setting the Component to the Original Appearance
Youcansettheappearanceofthespreadsheetcomponenttotheoriginaldefaultlookofversion3.Thisinvolvessettingtherenderersfortheoverallcomponent,columnheader,rowheader,scrollbars,sheetcorner,andfocusindicator.Youcansetaskinalongwiththerenderersforthescrollbarstogetthelookfromversion2.5(FarPoint.Win.Spread.DefaultSkins.Default.Apply(FpSpread1)).
Spread Windows Forms Developer’s Guide 101
Copyright © GrapeCity, Inc. All rights reserved.
TheinterfacerendererforthecomponenteffectsthefollowingareasaswellastheGrayAreaBackColor('GrayAreaBackColorProperty'intheon-linedocumentation)propertyofthesheet(areabetweenthelastcolumnorrowandthescrollbars).
Tosettheappearancetothedefault,usethefollowingproperties.
UsingCode
Tosettheappearancetothelookofversion3,settherenderersincludingtheColumnHeaderRenderer,theRowHeaderRenderer,andtheCornerRenderer,asshowninthefollowingexample.
Example
Thisexampleshowshowtosettheappearanceofthecomponenttotheoriginalversion3look.
C#fpSpread1.InterfaceRenderer = null;// set the column header renderer to the defaultfpSpread1.ActiveSheet.ColumnHeader.DefaultStyle.Renderer = new FarPoint.Win.Spread.CellType.ColumnHeaderRenderer();// set the row header renderer to the defaultfpSpread1.ActiveSheet.RowHeader.DefaultStyle.Renderer = new FarPoint.Win.Spread.CellType.RowHeaderRenderer();// set the sheet corner renderer to the defaultfpSpread1.ActiveSheet.SheetCorner.DefaultStyle.Renderer = new FarPoint.Win.Spread.CellType.CornerRenderer();// set the scroll bar renderers to the defaultfpSpread1.HorizontalScrollBar.Renderer = null;fpSpread1.VerticalScrollBar.Renderer = null;
Spread Windows Forms Developer’s Guide 102
Copyright © GrapeCity, Inc. All rights reserved.
// The focus indicator can be set to the version 3 look as well//fpSpread1.FocusRenderer = new FarPoint.Win.Spread.DefaultFocusIndicatorRenderer;
VBFpSpread1.InterfaceRenderer = Nothing' set the column header renderer to the defaultFpSpread1.ActiveSheet.ColumnHeader.DefaultStyle.Renderer = New FarPoint.Win.Spread.CellType.ColumnHeaderRenderer' set the row header renderer to the defaultFpSpread1.ActiveSheet.RowHeader.DefaultStyle.Renderer = New FarPoint.Win.Spread.CellType.RowHeaderRenderer' set the sheet corner renderer to the defaultFpSpread1.ActiveSheet.SheetCorner.DefaultStyle.Renderer = New FarPoint.Win.Spread.CellType.CornerRendererFpSpread1.HorizontalScrollBar.Renderer = Nothing' set the scroll bar renderers to the defaultFpSpread1.VerticalScrollBar.Renderer = Nothing' The focus indicator can be set to the version 3 look as well'FpSpread1.FocusRenderer = New FarPoint.Win.Spread.DefaultFocusIndicatorRenderer
Applying a Skin to the Component
Youcanquicklycustomizetheappearanceofthespreadsheetcomponentbyapplyinga"skin"toit.Askinissimplyacollectionofappearancepropertiesthatapplytoanentirecomponentortoanindividualsheetsuchascolors,gridlines,andwhethertoshowheaders.Thissavesyouthetimeandeffortofsettingthepropertiesindividually.Spreadincludesseveralbuilt-inskinsthatarereadyforyoutouse.YoucanalsocreateyourowncustomskinandsaveitsothatyoucanuseitinotherSpreadcomponentsforacommonformat.
Formoreinformationandinstructionsabout
See
Creatingandapplyingyourownskins CreatingaCustomSkinforaComponent
Creatingandapplyingyourowncell-levelstyles CreatingandApplyingaStyleforCells
Savingtheskintoafileorstream SavingandLoadingaSkin
CustomizingaskinintheSpreadDesigner SpreadSkinEditor(on-linedocumentation)
Spreadskins SpreadSkin('SpreadSkinClass'intheon-linedocumentation)class
UsingtheSpreadSkinEditor
1. Ifyouwanttocreateyourownskin,followtheinstructionsprovidedinCreatingaCustomSkinforaComponenttocreateaskinandapplyit.Toapplyadefaultskintotheentirespreadsheetcomponent,followthesedirections.
2. IntheFormwindow,clicktheSpreadcomponentforwhichyouwanttosettheskin(orrightclickonthecomponentandchoosetheEditSkinsmenu).
3. AtthebottomofthePropertieswindow,clicktheEditSkinsverb.4. IntheSpreadSkinEditor,selectoneofthePre-Definedskinsinthelistofpredefinedskins,thenclickOKto
closetheeditor.
UsingaShortcut
Spread Windows Forms Developer’s Guide 103
Copyright © GrapeCity, Inc. All rights reserved.
1. Ifyouwanttocreateyourownskin,followtheinstructionsprovidedinCreatingaCustomSkinforaComponenttocreateasheetskinandapplyit.Toapplyadefaultsheetskin,followthesedirections.
2. UsetheApply('ApplyMethod'intheon-linedocumentation)methodontheselecteddefaultskin(setbythepropertyintheDefaultSkins('DefaultSkinsClass'intheon-linedocumentation)object)toapplyaspecifieddefaultskintoaspecificSpreadcomponent,collectionofsheets,orsheet.
Example
ThisexamplecodesetsthecomponenttousetheClassicpredefinedskin.
C#FarPoint.Win.Spread.DefaultSpreadSkins.Classic.Apply(fpSpread1);
VBFarPoint.Win.Spread.DefaultSpreadSkins.Classic.Apply(FpSpread1)
UsingCode
1. Ifyouwanttocreateyourownskin,followtheinstructionsprovidedinCreatingaCustomSkinforaComponenttocreateaskinandapplyit.Toapplyadefaultskin,followthesedirections.
2. UsetheApply('ApplyMethod'intheon-linedocumentation)methodontheselecteddefaultskin(setbythepropertyintheDefaultSpreadSkinsobject)toapplyaspecifieddefaultskintoaspecificSpreadcomponent.
Example
ThisexamplecodesetsthefirstsheettousetheClassicpredefinedskin.
C#// Create new SheetView object.FarPoint.Win.Spread.SheetView newsheet = new FarPoint.Win.Spread.SheetView();// Apply a skin to the SheetView object.FarPoint.Win.Spread.DefaultSpreadSkins.Classic.Apply(newsheet);// Assign the SheetView object to the first sheet in the component.fpSpread1.Sheets[0] = newsheet;
VB' Create new SheetView object.Dim newsheet As New FarPoint.Win.Spread.SheetView()' Apply a skin to the SheetView object.FarPoint.Win.Spread.DefaultSpreadSkins.Classic.Apply(newsheet)' Assign the SheetView object to the first sheet in the component.FpSpread1.Sheets(0) = newsheet
UsingtheSpreadDesigner
1. FromtheSettingsmenu,choosetheSpreadSkinicon.2. IntheSpreadSkinEditor,selectoneofthepredefinedskinsfromthePre-Definedtab,orasavedcustom
skinfromtheSavedtab.3. ClickOKtoclosetheeditor.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Spread Windows Forms Developer’s Guide 104
Copyright © GrapeCity, Inc. All rights reserved.
Creating a Custom Skin for a Component
Youcanquicklycustomizetheappearanceofthespreadsheetcomponentbyapplyinga"skin"toit.Somebuilt-inskinsareprovidedwithSpreadtocreatecommonformats.Youcancreateyourowncustomskinandsaveittouseagain,similartoatemplate.
Formoreinformationandinstructionsabout
See
Applyingthebuilt-inskins ApplyingaSkintotheComponent
Creatingandapplyingyourowncell-levelstyles CreatingandApplyingaStyleforCells
Savingtheskintoafileorstream SavingandLoadingaSkin
Underlyingmodelforskins UnderstandingtheStyleModel
CustomizingaskinintheSpreadDesigner SpreadSkinEditor(on-linedocumentation)
Spreadskins SpreadSkin('SpreadSkinClass'intheon-linedocumentation)class
UsingtheSpreadSkinEditor
1. IntheFormwindow,clicktheSpreadcomponentforwhichyouwanttocreatetheskin.2. AtthebottomofthePropertieswindow,clicktheEditSkinsverb.3. IntheSpreadSkinEditor,selecttheCustomtab.4. SetthepropertiesintheCustomtabtocreatetheskinyouwant.5. SettheNamepropertytospecifythenameforyourcustomskin.6. ClicktheSaveSkinbuttontosavetheskin.
Adialogappearssayingtheskinhasbeensaved.
7. ClickOKtoclosetheeditorandapplytheskinyoucreatedtothesheet,orclickCanceltoclosetheeditorandnotapplytheskinyoucreated.
UsingaShortcut
1. UsetheSpreadSkinobjectconstructor,andsetitsparameterstospecifythesettingsfortheskin.2. UsetheApply('ApplyMethod'intheon-linedocumentation)methodoftheSpreadSkinobjecttoapplyit
tothecomponent.
Example
Thisexamplecodecreatesandusesacustomskin.
C#fpSpread1.Sheets.Count = 3;FarPoint.Win.Spread.StyleInfo chd = new FarPoint.Win.Spread.StyleInfo();chd.BackColor = Color.LightGreen;FarPoint.Win.Spread.StyleInfo cds = new FarPoint.Win.Spread.StyleInfo();cds.BackColor = Color.LightGreen;FarPoint.Win.Spread.StyleInfo rhd = new FarPoint.Win.Spread.StyleInfo();rhd.BackColor = Color.LightGreen;FarPoint.Win.Spread.StyleInfo def = new FarPoint.Win.Spread.StyleInfo();FarPoint.Win.Spread.GradientSelectionRenderer gsr = new FarPoint.Win.Spread.GradientSelectionRenderer();
Spread Windows Forms Developer’s Guide 105
Copyright © GrapeCity, Inc. All rights reserved.
gsr.Color1 = Color.Green;gsr.Color2 = Color.LightGreen;gsr.Opacity = 50;def.BackColor = Color.Honeydew;FarPoint.Win.Spread.EnhancedInterfaceRenderer int1 = new FarPoint.Win.Spread.EnhancedInterfaceRenderer();int1.ArrowColorDisabled = Color.Green;int1.ArrowColorEnabled = Color.LightSeaGreen;int1.ScrollBoxBackgroundColor = Color.Aqua;int1.TabShape = FarPoint.Win.Spread.EnhancedInterfaceRenderer.SheetTabShape.RoundedRectangle;int1.TabStripButtonStyle = FarPoint.Win.Spread.EnhancedInterfaceRenderer.ButtonStyles.Enhanced;int1.TabStripButtonFlatStyle = FlatStyle.Popup;int1.SheetTabBorderColor = Color.Aquamarine;int1.SheetTabLowerActiveColor = Color.DarkSeaGreen;int1.SheetTabLowerNormalColor = Color.DarkOliveGreen;int1.SheetTabUpperActiveColor = Color.ForestGreen;int1.SheetTabUpperNormalColor = Color.LightSeaGreen;int1.SplitBarBackgroundColor = Color.Aquamarine;int1.SplitBarDarkColor = Color.DarkGreen;int1.SplitBarLightColor = Color.LightGreen;int1.SplitBoxBackgroundColor = Color.Green;int1.SplitBoxBorderColor = Color.LimeGreen;int1.TabStripBackgroundColor = Color.Aquamarine;FarPoint.Win.Spread.NamedStyle chstyle = new FarPoint.Win.Spread.NamedStyle("ColumnHeaders", "HeaderDefault", chd);FarPoint.Win.Spread.NamedStyle corner = new FarPoint.Win.Spread.NamedStyle("CornerHeaders", "HeaderDefault", cds);FarPoint.Win.Spread.NamedStyle rowhstyle = new FarPoint.Win.Spread.NamedStyle("RowHeaders", "HeaderDefault", rhd);FarPoint.Win.Spread.NamedStyle ds = new FarPoint.Win.Spread.NamedStyle("Default", "DataAreaDefault", def);
FarPoint.Win.Spread.MarqueeFocusIndicatorRenderer focusrend = new FarPoint.Win.Spread.MarqueeFocusIndicatorRenderer(Color.LightSeaGreen, 2);FarPoint.Win.Spread.EnhancedScrollBarRenderer ScrollBarR = new FarPoint.Win.Spread.EnhancedScrollBarRenderer(Color.Green, Color.LightGreen,Color.Green, Color.Aqua,Color.DarkGreen, Color.DarkSeaGreen, Color.Turquoise, Color.SpringGreen, Color.Teal, Color.PaleGreen, Color.ForestGreen);
FarPoint.Win.Spread.SpreadSkin skin = new FarPoint.Win.Spread.SpreadSkin("MySkin", int1, ScrollBarR, focusrend, gsr, ds, chstyle, rowhstyle, corner);skin.Apply(fpSpread1);
VB' Create a custom skin.FpSpread1.Sheets.Count = 3Dim chd As New FarPoint.Win.Spread.StyleInfochd.BackColor = Color.LightGreenDim cds As New FarPoint.Win.Spread.StyleInfocds.BackColor = Color.LightGreenDim rhd As New FarPoint.Win.Spread.StyleInforhd.BackColor = Color.LightGreenDim def As New FarPoint.Win.Spread.StyleInfoDim gsr As New FarPoint.Win.Spread.GradientSelectionRenderer
Spread Windows Forms Developer’s Guide 106
Copyright © GrapeCity, Inc. All rights reserved.
gsr.Color1 = Color.Greengsr.Color2 = Color.LightGreengsr.LinearGradientMode = Drawing2D.LinearGradientMode.BackwardDiagonalgsr.Opacity = 50def.BackColor = Color.HoneydewDim int As New FarPoint.Win.Spread.EnhancedInterfaceRendererint.ArrowColorDisabled = Color.Greenint.ArrowColorEnabled = Color.LightSeaGreenint.ScrollBoxBackgroundColor = Color.Aquaint.TabShape = FarPoint.Win.Spread.EnhancedInterfaceRenderer.SheetTabShape.RoundedRectangleint.TabStripButtonStyle = FarPoint.Win.Spread.EnhancedInterfaceRenderer.ButtonStyles.Enhancedint.TabStripButtonFlatStyle = FlatStyle.Popupint.SheetTabBorderColor = Color.Aquamarineint.SheetTabLowerActiveColor = Color.DarkSeaGreenint.SheetTabLowerNormalColor = Color.DarkOliveGreenint.SheetTabUpperActiveColor = Color.ForestGreenint.SheetTabUpperNormalColor = Color.LightSeaGreenint.SplitBarBackgroundColor = Color.Aquamarineint.SplitBarDarkColor = Color.DarkGreenint.SplitBarLightColor = Color.LightGreenint.SplitBoxBackgroundColor = Color.Greenint.SplitBoxBorderColor = Color.LimeGreenint.TabStripBackgroundColor = Color.AquamarineDim chstyle As New FarPoint.Win.Spread.NamedStyle("ColumnHeaders", "HeaderDefault", chd)Dim corner As New FarPoint.Win.Spread.NamedStyle("CornerHeaders", "HeaderDefault", cds)Dim rowhstyle As New FarPoint.Win.Spread.NamedStyle("RowHeaders", "HeaderDefault", rhd)Dim ds As New FarPoint.Win.Spread.NamedStyle("Default", "DataAreaDefault", def)Dim focusrend As New FarPoint.Win.Spread.MarqueeFocusIndicatorRenderer(Color.LightSeaGreen, 2)
Dim ScrollBarR As New FarPoint.Win.Spread.EnhancedScrollBarRenderer(Color.Green, Color.LightGreen, Color.Green, Color.Aqua, Color.DarkGreen,Color.DarkSeaGreen, Color.Turquoise, Color.SpringGreen, Color.Teal, Color.PaleGreen, Color.ForestGreen)
Dim skin As New FarPoint.Win.Spread.SpreadSkin("MySkin", int, ScrollBarR, focusrend, gsr, ds, chstyle, rowhstyle, corner)skin.Apply(FpSpread1)
UsingtheSpreadDesigner
1. FromtheSettingsmenu,choosetheSpreadSkinicon.2. IntheSpreadSkinEditor,selecttheCustomtab.3. Setthepropertiesforthenewcustomskin,includingtheNamepropertytonameyourskin.4. SelecttheSaveSkinbutton.
Amessageboxappearstellingyouyourcustomskinhasbeensaved.
5. ClickOKtoclosetheSpreadSkinEditor.6. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing the Renderers
Spread Windows Forms Developer’s Guide 107
Copyright © GrapeCity, Inc. All rights reserved.
Youcancustomizetherenderersusedtocreatethedefaultstyles.
TheOffice2013orOffice2016styleusestheFlatCornerHeaderRenderer('FlatCornerHeaderRendererClass'intheon-linedocumentation),FlatColumnHeaderRenderer('FlatColumnHeaderRendererClass'intheon-linedocumentation),FlatRowHeaderRenderer('FlatRowHeaderRendererClass'intheon-linedocumentation),FlatScrollBarRenderer('FlatScrollBarRendererClass'intheon-linedocumentation),andFlatFocusIndicatorRenderer('FlatFocusIndicatorRendererClass'intheon-linedocumentation)classes.
ThedefaultstyleusestheColumnHeaderDefaultEnhanced('ColumnHeaderDefaultEnhancedField'intheon-linedocumentation),CornerDefaultEnhanced('CornerDefaultEnhancedField'intheon-linedocumentation),CornerFooterDefaultEnhanced('CornerFooterDefaultEnhancedField'intheon-linedocumentation),FilterBarDefaultEnhanced('FilterBarDefaultEnhancedField'intheon-linedocumentation),andRowHeaderDefaultEnhanced('RowHeaderDefaultEnhancedField'intheon-linedocumentation)fields.
TheOffice2007styleusestheEnhancedCornerRenderer('EnhancedCornerRendererClass'intheon-linedocumentation),EnhancedFocusIndicatorRenderer('EnhancedFocusIndicatorRendererClass'intheon-linedocumentation),EnhancedColumnHeaderRenderer('EnhancedColumnHeaderRendererClass'intheon-linedocumentation),EnhancedScrollBarRenderer('EnhancedScrollBarRendererClass'intheon-linedocumentation),andEnhancedRowHeaderRenderer('EnhancedRowHeaderRendererClass'intheon-linedocumentation)classes.
Spread Windows Forms Developer’s Guide 108
Copyright © GrapeCity, Inc. All rights reserved.
TheclassicstyleusestheColumnHeaderRenderer('ColumnHeaderRendererClass'intheon-linedocumentation),RowHeaderRenderer('RowHeaderRendererClass'intheon-linedocumentation),andCornerRenderer('CornerRendererClass'intheon-linedocumentation)classes.
UsingCode
1. Createanewrendererandsettherendererproperties.2. Settherendererforthedefaultstyleareasuchascolumnfooter.3. Applythenewcornerstylestothecontrol.
Example
Thisexamplecodecustomizestherenderersforthecolumnheaderandfooter,rowheader,cornerheader,andcornerfooter.
C#//header/footer columnfpSpread1.ActiveSheet.ColumnFooter.Visible = true;fpSpread1.ActiveSheet.ColumnFooter.RowCount = 3;fpSpread1.ActiveSheet.ColumnHeader.RowCount = 3;FarPoint.Win.Spread.CellType.FlatColumnHeaderRenderer flatcolumnheader = new FarPoint.Win.Spread.CellType.FlatColumnHeaderRenderer();fpSpread1.ActiveSheet.ColumnHeader.DefaultStyle.Renderer = flatcolumnheader;FarPoint.Win.Spread.CellType.FlatColumnFooterRenderer flatcolumnfooter = new FarPoint.Win.Spread.CellType.FlatColumnFooterRenderer();fpSpread1.ActiveSheet.ColumnFooter.DefaultStyle.Renderer = flatcolumnfooter;
//header row
Spread Windows Forms Developer’s Guide 109
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.ActiveSheet.RowHeader.ColumnCount = 3;FarPoint.Win.Spread.CellType.FlatRowHeaderRenderer flatrowheader = new FarPoint.Win.Spread.CellType.FlatRowHeaderRenderer();fpSpread1.ActiveSheet.RowHeader.DefaultStyle.Renderer = flatrowheader;
//sheet corner header renderFarPoint.Win.Spread.CellType.FlatCornerHeaderRenderer flatconrnerheader = new FarPoint.Win.Spread.CellType.FlatCornerHeaderRenderer();fpSpread1.ActiveSheet.SheetCorner.DefaultStyle.Renderer = flatconrnerheader;
//sheet corner footer renderFarPoint.Win.Spread.SpreadSkin a1 = new FarPoint.Win.Spread.SpreadSkin(FarPoint.Win.Spread.DefaultSpreadSkins.Default);a1.Apply(fpSpread1);fpSpread1.ActiveSheet.ColumnFooter.Visible = true;FarPoint.Win.Spread.CellType.FlatCornerFooterRenderer flatconrnerfooter = new FarPoint.Win.Spread.CellType.FlatCornerFooterRenderer();flatconrnerfooter.NormalTriangleColor = Color.Aquamarine;FarPoint.Win.Spread.NamedStyle conner = new FarPoint.Win.Spread.NamedStyle("conner", "HeaderDefault");conner.BackColor = Color.Olive;conner.Renderer = flatconrnerfooter;fpSpread1.NamedStyles.Add(conner);a1.CornerFooterDefaultStyle = conner;
VB'header/footer columnFpSpread1.ActiveSheet.ColumnFooter.Visible = TrueFpSpread1.ActiveSheet.ColumnFooter.RowCount = 3FpSpread1.ActiveSheet.ColumnHeader.RowCount = 3Dim flatcolumnheader As New FarPoint.Win.Spread.CellType.FlatColumnHeaderRenderer()FpSpread1.ActiveSheet.ColumnHeader.DefaultStyle.Renderer = flatcolumnheaderDim flatcolumnfooter As New FarPoint.Win.Spread.CellType.FlatColumnFooterRenderer()FpSpread1.ActiveSheet.ColumnFooter.DefaultStyle.Renderer = flatcolumnfooter
'header rowFpSpread1.ActiveSheet.RowHeader.ColumnCount = 3Dim flatrowheader As New FarPoint.Win.Spread.CellType.FlatRowHeaderRenderer()FpSpread1.ActiveSheet.RowHeader.DefaultStyle.Renderer = flatrowheader
'sheet corner header renderDim flatconrnerheader As New FarPoint.Win.Spread.CellType.FlatCornerHeaderRenderer()FpSpread1.ActiveSheet.SheetCorner.DefaultStyle.Renderer = flatconrnerheader
'sheet corner footer renderDim a1 As New FarPoint.Win.Spread.SpreadSkin(FarPoint.Win.Spread.DefaultSpreadSkins.Default)a1.Apply(FpSpread1)FpSpread1.ActiveSheet.ColumnFooter.Visible = TrueDim flatconrnerfooter As New FarPoint.Win.Spread.CellType.FlatCornerFooterRenderer()flatconrnerfooter.NormalTriangleColor = Color.AquamarineDim conner = New FarPoint.Win.Spread.NamedStyle("conner", "HeaderDefault")conner.BackColor = Color.Oliveconner.Renderer = flatconrnerfooterFpSpread1.NamedStyles.Add(conner)a1.CornerFooterDefaultStyle = conner
Spread Windows Forms Developer’s Guide 110
Copyright © GrapeCity, Inc. All rights reserved.
Customizing the Dimensions of the Component
YoucansettheoveralldimensionsoftheSpreadcomponentandthisdeterminesthesizeofthevisibleareaofthespreadsheet.Thefollowingfigureshowsthedimensionsthatyoucansetbysettingthenumberofpixelsforeach.
RefertotheMicrosoft.NETFrameworkdocumentationformoredetailsontheControl.HeightpropertyorControl.Widthproperty.
TocalculatetheheightoftheSpread,assumingscrollbarsturnedoffandnoheaders,calculatetheheightofalltherowsandthenaddonepixelforeveryborder,soif10rowsof20pixelheight,(10x20)+(10x1)+1,or211inthisexample.FortheSpreadwidth,theprocessisthesame.Formoreinformationonsettingtherowheightandcolumnwidth,refertoSettingtheRowHeightorColumnWidth.
UsingthePropertiesWindow
1. SelecttheSpreadcomponent.2. Withthepropertieswindowopen,intheLayoutcategory,selecttheHeightpropertyortheWidthproperty
andtypeinanewvalue.Theunitispixels.PressEnter.Thenewdimensionisnowset.RefertotheMicrosoft.NETFrameworkdocumentationforsettingtheunitsofmeasurementforheighttosomethingotherthanthedefault,whichispixels.
UsingCode
Addalineofcodethatsetsthespecificdimension.Unlessyouhavesetitotherwise,thedefaultfortheunitofmeasurementispixels.UsetheHeightandWidthpropertiesoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class.
Example
ThisexampleshowshowtosettheheightoftheSpreadcomponentto250pixelsandthewidthto300.
C#fpSpread1.Height = 250;fpSpread1.Width = 300;
VB
Spread Windows Forms Developer’s Guide 111
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.Height = 250FpSpread1.Width = 300
Customizing the Outline of the Component
Youcansettheappearanceoftheoutlineoftheoverallcomponent.Thefollowingfiguresshowthetypesofoutlines(orborder)styles.
Outline(Border)Style ExampleFixed,three-dimensional(default)
Fixed,single-line
None
Formoredetails,refertotheFpSpread.BorderStyle('BorderStyleProperty'intheon-linedocumentation)propertyandtheBorderStyleenumerationintheMicrosoft.NETFramework.
UsingthePropertiesWindow
Spread Windows Forms Developer’s Guide 112
Copyright © GrapeCity, Inc. All rights reserved.
1. SelecttheSpreadcomponent.2. InthePropertieswindow,intheAppearancecategory,selecttheBorderStyleproperty.3. Selectavaluefromthedrop-downlist.PressEnter.Thenewpropertyisnowset.
UsingCode
Addalineofcodethatsetsthespecificproperty,theBorderStyle('BorderStyleProperty'intheon-linedocumentation)propertyoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class.
Example
Thisexampleshowshowtosetthebordertobeasingle-lineborder.
C#fpSpread1.BorderStyle = BorderStyle.FixedSingle;
VBFpSpread1.BorderStyle = BorderStyle.FixedSingle
UsingtheSpreadDesigner
1. Inthepropertylist,intheAppearancecategory,selecttheBorderStyleproperty.2. Fromthedrop-downlist,selecttheborderstyle.3. FromtheFilemenu,selectApplyandExittoapplyyourchangestotheSpreadcomponentandexitSpread
Designer.
Customizing the Display of the Pointer
Youcansetthecursororpointertoappeardifferentlyfordifferentpartsofthedisplay.Todeterminethepointertodisplay,usetheGetCursor('GetCursorMethod'intheon-linedocumentation)methodandSetCursor('SetCursorMethod'intheon-linedocumentation)methodandtheCursorType('CursorTypeEnumeration'intheon-linedocumentation)enumeration.Thecodeforsettingthepointertochangewhenitisoveraheadercell,asshowninthisfigure,isgivenintheexamplebelow.
TheSpreadcomponentusesonepointerforlockedcells(CursorType('CursorTypeEnumeration'intheon-linedocumentation)enumerationequaltoLocked)andonepointerforunlockedcells(CursorType('CursorTypeEnumeration'intheon-linedocumentation)enumerationequaltoNormal).Thecomponentdoesnotsupportdifferentpointersforeachcelltype.
Spread Windows Forms Developer’s Guide 113
Copyright © GrapeCity, Inc. All rights reserved.
CellTypesandReservedLocations
Thebuilt-inhyperlinkcelltypebydefaultusesthehandpointeroverthelinkarea.Formoreinformation,refertoSettingaHyperlinkCell.
Somecelltypes(forexample,button,checkbox,combobox,andhyperlink)reserveareaswithinthecellthatrequirespecialmouseprocessing.Forexample,clickingamousebuttonwhileoverthedrop-downbuttoninacomboboxcellimmediatelyenterseditmode.ThelocationofthespecialareaandthepointerusedoverthespecialareaisdeterminedbytheIsReservedLocation('IsReservedLocationMethod'intheon-linedocumentation)andGetReservedCursor('GetReservedCursorMethod'intheon-linedocumentation)methodsinthecelltypeclasses.Ifyoudonotlikethepointersuppliedbyabuilt-incelltypeclassthenyoucouldderiveaclassfromthebuilt-incelltypeclassandoverridetheGetReservedCursor('GetReservedCursorMethod'intheon-linedocumentation)method.
TheGetReservedCursor('GetReservedCursorMethod'intheon-linedocumentation)methodisonlycalledforlocationswhereIsReservedLocation('IsReservedLocationMethod'intheon-linedocumentation)returnsnon-null.Byreturningnull(NothinginVB)ornon-null,theIsReservedLocationmethodessentiallydividesthecellrectangleintotwosubregions(normalregionandreservedregion).Inthenormalsubregion,amousedownisprocessedbytheSpreadcomponentandstartsacellselection.SincethemousedownisprocessedbytheSpreadcomponent,themousepointerisdeterminedbytheSpreadcomponent(thatis,GetReservedCursorisnotcalled).Inthereservedsubregion,amousedownimmediatelystartsacelleditandthemousedowngetspassedtothecelleditorforprocessing.Sincethemousedownisprocessedbythecelleditor,themousepointerisdeterminedbythecelltypeviatheGetReservedCursormethod.Whileyoucansupplycelltypespecificpointersforthereservedsubregion,youcannotsupplycelltypespecificpointersforthenormalsubregions.
Example
Thisexamplesetsthepointertodisplayasahandasshowninthefigureabove.
C#private void Form1_Load(object sender, System.EventArgs e){ // Change the pointer shape on column headers. fpSpread1.SetCursor(FarPoint.Win.Spread.CursorType.ColumnHeader, System.Windows.Forms.Cursors.Hand);}
VBPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Change the pointer shape on column headers. FpSpread1.SetCursor(FarPoint.Win.Spread.CursorType.ColumnHeader, System.Windows.Forms.Cursors.Hand)End Sub
Customizing Painting of Parts of the Component
Youcancustomizethepaintingofvariouspartsofthecomponent'sdisplaybylookingforeventsandpainting(rendering)thosepartsthewayyouwant.
Themembersthatareusedwithcustompaintinginclude:
Member DescriptionOnPaintTabStrip('OnPaintTabStripMethod'intheon-linedocumentation)
RaisesthePaintTabStripevent
Spread Windows Forms Developer’s Guide 114
Copyright © GrapeCity, Inc. All rights reserved.
OnPaintTabStripButton('OnPaintTabStripButtonMethod'intheon-linedocumentation)
RaisesthePaintTabStripButtonevent
OnPaintTabStripTab('OnPaintTabStripTabMethod'intheon-linedocumentation)
RaisesthePaintTabStripTabevent
PaintTabStrip('PaintTabStripEvent'intheon-linedocumentation)event
OccurswhentheTabStripneedspainting
PaintTabStripButton('PaintTabStripButtonEvent'intheon-linedocumentation)event
OccurswhenaTabStripbuttonneedspainting
PaintTabStripTab('PaintTabStripTabEvent'intheon-linedocumentation)event
OccurswhenaTabStriptabneedspainting
PaintTabStripEventArgs('PaintTabStripEventArgsClass'intheon-linedocumentation)
Containsdatarelatedtothisevent
PaintTabStripButtonEventArgs('PaintTabStripButtonEventArgsClass'intheon-linedocumentation)
Containsdatarelatedtothisevent
PaintTabStripTabEventArgs('PaintTabStripTabEventArgsClass'intheon-linedocumentation)
Containsdatarelatedtothisevent
Using XP Themes with the Component
YoucansetsupportforXPthemesforthecellsandgraphicalelementsintheSpreadcomponent.TheVisualStyles('VisualStylesProperty'intheon-linedocumentation)propertyfortheSpreadcomponentcausesthecellstohavetheappearanceoftheXPtheme.Youcancreateamanifestfilesothatthescrollbarshaveathemeappearance.
BydefaulttheVisualStyles('VisualStylesProperty'intheon-linedocumentation)propertyissettoAuto,sothegraphicalcelltypespaintthewaythethemeissettopaint(forexamplethebuttonisthemedsoyoucannotsetabackgroundcolorwiththeBackColorproperty).YoueitherneedtoturnoffVisualStylesfortheSpreadcomponentorcreateacustomcelltypewhereyouoverridethePaintCellandGetEditorControlmethodsandthensettheVisualStylespropertyoftheAppearanceobjecttooff.Athirdalternativeistoleaveit"on"fortheSpreadcomponentbutturnit"off"fortheindividualcontrol(suchastheFpProgresscontrolfortheprogressindicatorcell).
ApplyingasheetskincausestheVisualStylespropertytobesettofalse.
IfyouareonWindowsXP,thenyouneedtoaddthefollowinglineofcodetoturnofftheXPthemesintheSpread.
FpSpread1.VisualStyles = FarPoint.Win.VisualStyles.Off
SettingtheVisualStylespropertyoftheSpreadtoOffshouldreturnthelookoftheSpreadtotheclassiclook.
ButtonsarenotdisplayedasexpectedifyouhavechangedtheSelectionStyleandhaveVisualStyleson.TheproblemisthatwhenVisualStylesareoncertaincelltypesignorecertainsettings,suchasthebuttonignoringthesettingoftheButtonColorproperty.YouwouldneedtotakethatintoaccountandpossiblysettheSelectionForeColor,forexample,tosomethingdifferent.TheSelectionColorssettingforSelectionStyleisanolderstyleandmixingitwithXPthemesisnotrecommended.
TheVisualStylespropertyisusedoncontrolsthatSpreadrenderssuchasthebuttonintheButtonCellType.ThescrollbarsarechildcontrolsrenderedbyVisualStudio.TohavethemrenderwithXPthemes,youwouldneedtosetupamanifestforyourapplication.
UsingthePropertiesWindow
1. SelecttheSpreadcomponent.2. InthePropertieswindow,selecttheVisualStylesproperty,andchooseanoptionfromthedrop-downlist.
UsingCode
Spread Windows Forms Developer’s Guide 115
Copyright © GrapeCity, Inc. All rights reserved.
AddalineofcodethatallowsthethemesupportbysettingtheVisualStyles('VisualStylesProperty'intheon-linedocumentation)propertyfortheSpreadcomponent.
Example
ThisexamplesetstheVisualStyles('VisualStylesProperty'intheon-linedocumentation)propertytoontoallowXPthemes.
C#fpSpread1.VisualStyles = FarPoint.Win.VisualStyles.On;
VBFpSpread1.VisualStyles = FarPoint.Win.VisualStyles.On
UsingtheSpreadDesigner
1. SelectSheetfromthedrop-downlistlocatedonthetoprightsideoftheDesigner.2. FromtheAppearancesection,selectanoptionfortheVisualStylesproperty.3. FromtheFilemenu,selectSaveandExittosavethechanges.
Handling Right-to-Left Layouts
TheSpreadcomponentcansupportright-to-leftlayouts.Right-to-leftfeaturessupportapplicationswherethelanguageiswrittenfromrighttoleft,suchasHebrew,Arabic,orFarsi,sotheuserinterfacewouldbedisplayednaturallywithright-to-leftorientation.
Mostoftheright-to-leftfunctionalityfortheSpreadcomponentisinheritedfromtheunderlying.NETframework,butthereareafewpropertiesthatcanbesettoinstructSpreadtodisplaythelayoutright-to-left.Currentlytheseaspectsofthelayoutarechangedwiththerighttoleftsupport:
celleditingcolumnresizingonrightinsteadofleftdirectionattributeinHTMLexportfilterandsortindicatorsorderofcolumnspopupandstickynotesandcellnoteindicatorsscrollbarsshapessheetcornerssheetnametabsviewportcolumns
Themembersthatareusedwithright-to-leftsupportinclude:
Member DescriptionRightToLeft('RightToLeftProperty'intheon-linedocumentation)
Getsorsetswhethertheobjectshouldpaintrighttoleft
OnRightToLeftChanged('OnRightToLeftChangedMethod'intheon-linedocumentation)
RaisestheRightToLefteventintheMicrosoft.NETFramework
Spread Windows Forms Developer’s Guide 116
Copyright © GrapeCity, Inc. All rights reserved.
Theseactionsareadded:ExtendToNextColumnVisual('ExtendToNextColumnVisualField'intheon-linedocumentation)ExtendToPreviousColumnVisual('ExtendToPreviousColumnVisualField'intheon-linedocumentation)MoveToNextColumnVisual('MoveToNextColumnVisualField'intheon-linedocumentation)MoveToPreviousColumnVisual('MoveToPreviousColumnVisualField'intheon-linedocumentation)ScrollToNextColumnVisual('ScrollToNextColumnVisualField'intheon-linedocumentation)ScrollToPreviousColumnVisual('ScrollToPreviousColumnVisualField'intheon-linedocumentation)
Customizing the Individual Sheet Appearance
Youcanhavemultiplesheetswithinaworkbook.Eachsheetisaseparatespreadsheetandcanhaveitsownappearanceandsettingsforuserinteraction.Eachsheethasauniquenameandsheetnametabforeasynavigationbetweensheets.
ThesetasksrelatetosettingtheappearanceoftheindividualsheetsinsidetheSpreadcomponent:
SettingtheBackgroundColorsforaSheetSettingaBackgroundImageforaSheetDisplayingGridLinesonaSheetAddingaTitleandSubtitletoaSheetDisplayingaFooterforColumnsorGroupsApplyingaSkintoaSheetCreatingaCustomSkinforaSheet
Othertasksthatrelatetothesheetappearance,butarepartoftheappearanceoftheSpreadcomponentinclude:
CustomizingtheOutlineoftheComponentCustomizingtheSheetNameTabsoftheComponentWorkingwithHierarchicalDataDisplayCreatingandApplyingaStyleforCells
Whenyouworkwithsheets,youcanmanipulatetheobjectsusingtheshortcutsincode,(SheetView('SheetViewClass'intheon-linedocumentation)andSheetViewCollection('SheetViewCollectionClass'intheon-linedocumentation)classes)oryoucandirectlyworkwiththemodel.Mostdeveloperswhoarenotchanginganythingdrasticallyfinditeasytoworkwiththeshortcutobjects.Formoreinformationonmodels,refertoUnderstandingtheUnderlyingModels.
Settingsappliedtoaparticularroworcolumnorcellcanoverridethesettingsthataresetatthesheetlevel.RefertoObjectParentage.
Fortasksthatrelatetosettingtheuserinteractionatthesheetlevel,refertoCustomizingInteractionwithaSheet.
Formoredetailsontheobjectsinvolved,refertotheSheetView('SheetViewClass'intheon-linedocumentation)classandSheetViewCollection('SheetViewCollectionClass'intheon-linedocumentation)class.
Spread Windows Forms Developer’s Guide 117
Copyright © GrapeCity, Inc. All rights reserved.
Setting the Background Colors for a Sheet
Therearetwodifferentbackgroundcolorsforasheet.Thefirstisthebackgroundofallthecellsinthedataarea,whichcanbesetatthesheetlevel.Thesecondistheareabeyondthecellsbutalsosetatthesheetlevel,whichiscalledthegrayareabackgroundcolor.
Thebackgroundcolorforallthecellsinthesheet,aswellasotherproperties,canbesetusingthedefaultstyleofthesheet.Inthisexample,thebackgroundcolorofthedefaultstyleforallofthecellsisgreen.Youcanalsosetthebackgroundcolorforindividualcells.
Thegrayareabackgroundcolorforthesheetisdisplayedintheareawherecellsarenotdisplayed,asshowninthefollowingfigure.Bydefault,theareaisthesystem'sControlcolor.Thisexamplesetsthebackgroundcolorbeyondthecellstobepink.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetforwhichtosetthegrayareabackgroundcolor.5. SelecttheGrayAreaBackColorpropertyinthepropertylist,andthenclickthedrop-downbuttontodisplaythecolorpicker.
6. Selectacolorinthecolorpicker.7. ClickOKtoclosetheeditor.
UsingaShortcut
SettheSheetsshortcutobjectGrayAreaBackColor('GrayAreaBackColorProperty'intheon-linedocumentation)propertyforthesheet.
Example
Thisexamplecodesetsthefirstsheet’sgrayareabackgroundcolortolightyellow.
C#// Set the first sheet's background color to light yellow.fpSpread1.InterfaceRenderer = null;fpSpread1.Sheets[0].GrayAreaBackColor = Color.LightYellow;
VB' Set the first sheet's background color to light yellow.
Spread Windows Forms Developer’s Guide 118
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.InterfaceRenderer = NothingFpSpread1.Sheets(0).GrayAreaBackColor = Color.LightYellow
UsingCode
1. CreateanewSheetViewobject.2. SettheGrayAreaBackColor('GrayAreaBackColorProperty'intheon-linedocumentation)property
fortheSheetViewobject.3. AssigntheSheetViewobjecttoasheetintheSpreadcomponent.
Example
Thisexamplecodesetsthefirstsheet’sbackgroundcolortolightyellow.
C#// Create a new SheetView object.FarPoint.Win.Spread.SheetView newsheet = new FarPoint.Win.Spread.SheetView();fpSpread1.InterfaceRenderer = null// Set the SheetView object's background color to light yellow.newsheet.GrayAreaBackColor = Color.LightYellow;// Assign the SheetView object to the first sheet in the component.fpSpread1.Sheets[0] = newsheet;
VB' Create a new SheetView object.Dim newsheet As New FarPoint.Win.Spread.SheetView()FpSpread1.InterfaceRenderer = Nothing' Set the SheetView object's background color to light yellow.newsheet.GrayAreaBackColor = Color.LightYellow' Assign the SheetView object to the first sheet in the component.FpSpread1.Sheets(0) = newsheet
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosetthegrayareabackgroundcolor.2. Inthepropertylist,selecttheGrayAreaBackColorproperty.3. Clickthedrop-downarrowtodisplaythecolorpicker.4. Selectacolorfromthecolorpicker.5. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Background Image for a Sheet
Youcansetanimageinthebackgroundofthecellsinthedataareaofthesheet.Dependingonthesizeofthegraphicandthesizeofthespreadsheet,theimagemayberepeated(tiled)overtheentiresheetofcells,asshowninthefollowingfigure.
Spread Windows Forms Developer’s Guide 119
Copyright © GrapeCity, Inc. All rights reserved.
Formoreinformationonsettinganimageinanindividualcell,refertoSettingaBackgroundImagetoaCell.
Formoreinformationontheimagecelltype,refertoSettinganImageCell.
UsingCode
1. SettheBackgroundImage('BackgroundImageProperty'intheon-linedocumentation)property.2. Setthebackcolorofthedefaultstyle.
Example
Thisexamplecodesetsthebackgroundimageofthesheet.
C#private void Form1_Load(object sender, System.EventArgs e){ //Specify background images. fpSpread1.BackgroundImage = Image.FromFile("D:\\images\\butterfly.gif"); //Set "Transparent" to the default background color of the sheet. fpSpread1.ActiveSheet.DefaultStyle.BackColor = Color.Transparent;}
VBPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Specify background images. FpSpread1.BackgroundImage = Image.FromFile("D:\images\butterfly.gif") 'Set "Transparent" to the default background color of the sheet. FpSpread1.ActiveSheet.DefaultStyle.BackColor = Color.TransparentEnd Sub
Displaying Grid Lines on a Sheet
Bydefaultsheetsdisplaygridlines.Youcansetthecolor,thewidth,andthestyleofgridlines.Inthefollowingfigure,thehorizontalgridlinesareflatand
Spread Windows Forms Developer’s Guide 120
Copyright © GrapeCity, Inc. All rights reserved.
red,andtheverticalgridlinesareflatandgreen.
Youcanchoosetodisplaythegridlinesasthree-dimensionallines,withahighlightandshadowcolor.Ifyoudoso,setthehighlightandshadowcolortocreatetheeffectyouwant.Youcancustomizethefollowinggridlinecharacteristics:
color-thecolorofthegridlinehighlightcolor-thehighlightcolorforthree-dimensionalgridlinesshadowcolor-theshadowcolorforthree-dimensionalgridlinestype-thetypeofgridlinewidth-thewidthinpixelsofthegridline
Thecolorisforflatlines;thehighlightandshadowcolorarefortheothertypesoflines.
YoucanhidethegridlineinaparticulardirectionbysettingthetypeofgridlinetoNone.Forexample,thefollowingcodehidesthehorizontalgridlines.
FpSpread1.ActiveSheet.HorizontalGridLine = New FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.None)
Tocustomizeotherproperties,createanewGridLine('GridLineClass'intheon-linedocumentation)object(ratherthanchangingapropertyontheexistingobject).
Formoredetailsonhowtoworkwiththegridlinesincode,refertotheexamplesbelow,theGridLine('GridLineClass'intheon-linedocumentation)class,andHorizontalGridLine('HorizontalGridLineProperty'intheon-linedocumentation)propertyorVerticalGridLine('VerticalGridLineProperty'intheon-linedocumentation)propertyoftheSheetView('SheetViewClass'intheon-linedocumentation)class.
Note:Youcandisplaylinesaroundindividualcellsbysettingcellborders.Formoreinformation,refertoCustomizingCellBorders.
Forinformationonsettingthegridlinesinaheader,refertoCustomizingtheHeaderGridLines.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetforwhichyouwanttosetthegridlinecolor.5. Tosetthehorizontalgridlinecolor,
a. SelecttheHorizontalGridLineobjectinthepropertylist.b. Ifyouwanttodisplaythree-dimensionalgridlines,settheTypepropertytoLoweredorRaised.c. Ifthegridlinesarenotthree-dimensional,selecttheColorproperty,andthenclickthedrop-downbuttontodisplaythecolorpicker.Selectacolorinthecolorpicker.
d. Ifthegridlinesarethree-dimensional,selecttheHighlightColorproperty,andthenclickthedrop-downbuttontodisplaythecolorpicker.Selectacolorinthecolorpicker.DothesamefortheShadowColorproperty.
6. Tosettheverticalgridlinecolor,a. SelecttheVerticalGridLineobjectinthepropertylistb. Ifyouwanttodisplaythree-dimensionalgridlines,settheTypepropertytoLoweredorRaised.c. Ifthegridlinesarenotthree-dimensional,selecttheColorproperty,andthenclickthedrop-downbuttontodisplaythecolorpicker.Selectacolorinthecolorpicker.
d. Ifthegridlinesarethree-dimensional,selecttheHighlightColorproperty,andthenclickthedrop-downbuttontodisplaythecolorpicker.Selectacolorinthecolorpicker.DothesamefortheShadowColorproperty.
7. ClickOKtoclosetheeditor.
UsingCode
1. CreateaGridLine('GridLineClass'intheon-linedocumentation)object,settingthecolororcolorsandthestyleforthegridlineintheconstructor.
2. AssigntheGridLine('GridLineClass'intheon-linedocumentation)objecttothespecifiedsheetbysettingtheSheetView('SheetViewClass'intheon-linedocumentation)objectHorizontalGridLine('HorizontalGridLineProperty'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 121
Copyright © GrapeCity, Inc. All rights reserved.
orVerticalGridLine('VerticalGridLineProperty'intheon-linedocumentation)propertytotheGridLine('GridLineClass'intheon-linedocumentation)objectyoucreatedinstep1.
Example
Thisexamplecodesetsthehorizontalgridlinecolortoredandtheverticalgridlinecolortochartreuse.Bothgridlinesareflat.
C#FarPoint.Win.Spread.GridLine HGridLine = new FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.Flat, Color.Red);FarPoint.Win.Spread.GridLine VGridLine = new FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.Flat, Color.Chartreuse);fpSpread1.Sheets[0].HorizontalGridLine = HGridLine;fpSpread1.Sheets[0].VerticalGridLine = VGridLine;
VBDim HGridLine As New FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.Flat, Color.Red)Dim VGridLine As New FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.Flat, Color.Chartreuse)FpSpread1.Sheets(0).HorizontalGridLine = HGridLineFpSpread1.Sheets(0).VerticalGridLine = VGridLine
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosetthegridlinecolors.2. Tosetthehorizontalgridlinecolor,
a. IntheAppearancecategory,selecttheHorizontalGridLineobjectinthepropertylist.b. Ifyouwanttodisplaythree-dimensionalgridlines,settheTypepropertytoLoweredorRaised.c. Ifthegridlinesarenotthree-dimensional,selecttheColorproperty,andthenclickthedrop-downbuttontodisplaythecolorpicker.Selectacolorinthecolorpicker.
d. Ifthegridlinesarethree-dimensional,selecttheHighlightColorproperty,andthenclickthedrop-downbuttontodisplaythecolorpicker.Selectacolorinthecolorpicker.DothesamefortheShadowColorproperty.
3. Tosettheverticalgridlinecolor,a. IntheAppearancecategory,selecttheVerticalGridLineobjectinthepropertylistb. Ifyouwanttodisplaythree-dimensionalgridlines,settheTypepropertytoLoweredorRaised.c. Ifthegridlinesarenotthree-dimensional,selecttheColorproperty,andthenclickthedrop-downbuttontodisplaythecolorpicker.Selectacolorinthecolorpicker.
d. Ifthegridlinesarethree-dimensional,selecttheHighlightColorproperty,andthenclickthedrop-downbuttontodisplaythecolorpicker.Selectacolorinthecolorpicker.DothesamefortheShadowColorproperty.
4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Adding a Title and Subtitle to a Sheet
Youcanaddaspeciallyformattedareaatthetopofthecomponentthatincludesatitle,asubtitleorboth.Atitleissetforthecomponent,andaseparatesubtitlecanbesetforeachsheet.ThefollowingfigureillustratesaSpreadcomponentwithatitleandasubtitlesetforthesheet.
ThetitleissetusingtheTitleInfo('TitleInfoProperty'intheon-linedocumentation)propertyattheFpSpread
Spread Windows Forms Developer’s Guide 122
Copyright © GrapeCity, Inc. All rights reserved.
level.ThesubtitleissetusingtheTitleInfo('TitleInfoProperty'intheon-linedocumentation)propertyatthesheetlevel.
UsetheTitleInfo('TitleInfoClass'intheon-linedocumentation)classanditsmemberstodisplayandcustomizethetitleandsubtitles.
UsingaShortcut
SetthepropertiesoftheTitleInfo('TitleInfoClass'intheon-linedocumentation)class.
Example
Thisexamplecodesetsanddisplaysatitleforthecomponentandasubtitleforthesheet.
C#// Show the title for the entire spreadsheet component.FpSpread1.TitleInfo.Visible = true;FpSpread1.TitleInfo.Text = "FarPoint Spread Title";FpSpread1.TitleInfo.HorizontalAlign = FarPoint.Win.Spread.CellHorizontalAlignment.Center;// Show the subtitle for the individual sheet.FpSpread1.Sheets[0].TitleInfo.Visible = true;FpSpread1.Sheets[0].TitleInfo.Text = "Sheet Only Subtitle";FpSpread1.Sheets[0].TitleInfo.HorizontalAlign = FarPoint.Win.Spread.CellHorizontalAlignment.Center;FpSpread1.Sheets[0].TitleInfo.BackColor = System.Drawing.Color.Aqua;
VB' Show the title for the entire spreadsheet component.FpSpread1.TitleInfo.Visible = TrueFpSpread1.TitleInfo.Text = "FarPoint Spread Title"FpSpread1.TitleInfo.HorizontalAlign = FarPoint.Win.Spread.CellHorizontalAlignment.Center' Show the subtitle for the individual sheet.FpSpread1.Sheets(0).TitleInfo.Visible = TrueFpSpread1.Sheets(0).TitleInfo.Text = "Sheet Only Subtitle"FpSpread1.Sheets(0).TitleInfo.HorizontalAlign = FarPoint.Win.Spread.CellHorizontalAlignment.CenterFpSpread1.Sheets(0).TitleInfo.BackColor = System.Drawing.Color.Aqua
UsingtheSpreadDesigner
1. FromtheSettingsmenu,selecttheTitlesiconintheSpreadSettingssection.
2. Specifythetextandwhethertodisplaythetitleandsubtitle.
3. SelectOKtoclosethedialog.
4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Displaying a Footer for Columns or Groups
Youcanshowacolumnfooter,agroupfooter,orbothforthesheetandputinformationinthefootersuchasformulasortext.Thecolumnfooterisanareaatthebottomofthesheet.Thegroupfooterisanextrarowoffootercellsatthebottomofasheetwithgrouping,ifyouareusingthegroupingfeature.
Spread Windows Forms Developer’s Guide 123
Copyright © GrapeCity, Inc. All rights reserved.
FordetailsontheAPI,refertotheColumnFooter('ColumnFooterProperty'intheon-linedocumentation)propertyoftheSheetView('SheetViewClass'intheon-linedocumentation)classandthevariousmembersoftheColumnFooter('ColumnFooterClass'intheon-linedocumentation)class.
Tocalculatethecolumnfooterorgroupfooterresultwithaformula,settheSetAggregationType('SetAggregationTypeMethod'intheon-linedocumentation)methodoftheColumnFooterobjecttothecorrectformulatypeforthatcolumn.Thefollowingfiguredisplaysagroupbarandacolumnfooterwithaformulainthecolumn:
Thegroupfooterisanextrarowthatisdisplayedbelowthegroupaftergroupingbyacolumnheader.TheGroupFooterVisible('GroupFooterVisibleProperty'intheon-linedocumentation)propertymustbesettotrueafterthegrouphasbeencreated.TheGrouped('GroupedEvent'intheon-linedocumentation)eventcanbeusedtoputinformationinthegroupfooterafterauserhascreatedthegroup.
Formoreinformationongrouping,refertoManagingGroupingofRowsofUserData.
Formoreinformationaboutsettingthegroupappearance,refertoSettingtheAppearanceofGroupedRows.
Formoreinformationoncolumnappearance,refertoCustomizingtheRoworColumnAppearance.
PropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSheetspropertyfortheFpSpreadcomponent.2. ClickthebuttontodisplaytheSheetViewCollectionEditor.3. SelecttheColumnFooterpropertyortheGroupFooterpropertyorbothinthePropertylistandsetVisibletotrue.4. ClickOKtoclosetheeditor.
UsingaShortcut
SettheVisible('VisibleProperty'intheon-linedocumentation)propertyoftheColumnFooterforthesheet.
Example
Thisexamplecodedisplaysacolumnfooterandsetsaspanandatextcolor.
C#fpSpread1.Sheets[0].RowCount = 10;fpSpread1.Sheets[0].ColumnCount = 15;// Show the column footer.fpSpread1.Sheets[0].ColumnFooter.Visible = true;fpSpread1.Sheets[0].ColumnFooter.RowCount = 2;fpSpread1.Sheets[0].ColumnFooter.DefaultStyle.ForeColor = Color.Purple;fpSpread1.Sheets[0].ColumnFooter.Columns[12].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Left;fpSpread1.Sheets[0].ColumnFooter.Cells[0, 12].RowSpan = 2;fpSpread1.Sheets[0].ColumnFooter.Cells[0, 0].Value = "test";
VBFpSpread1.Sheets(0).RowCount = 10
Spread Windows Forms Developer’s Guide 124
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.Sheets(0).ColumnCount = 15' Show the footer.FpSpread1.Sheets(0).ColumnFooter.Visible = trueFpSpread1.Sheets(0).ColumnFooter.RowCount = 2FpSpread1.Sheets(0).ColumnFooter.DefaultStyle.ForeColor = Color.PurpleFpSpread1.Sheets(0).ColumnFooter.Columns(12).HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.LeftFpSpread1.Sheets(0).ColumnFooter.Cells(0, 12).RowSpan = 2FpSpread1.Sheets(0).ColumnFooter.Cells(0, 0).Value = "test
UsingaShortcut
1. SettheVisible('VisibleProperty'intheon-linedocumentation)propertyoftheColumnFooterforthesheet.2. SettheSetAggregationTypemethodforthecolumn.
Example
Thisexamplesumsthevaluesinthefirstcolumnanddisplaystheminthecolumnfooter.Theexamplealsosumsthevaluesinthesecondgroupandputstheminthegroupfooter.
C#private void Form1_Load(object sender, System.EventArgs e){fpSpread1.Sheets[0].RowCount=8;fpSpread1.Sheets[0].ColumnCount = 15;fpSpread1.Sheets[0].GroupBarInfo.Visible = true;fpSpread1.Sheets[0].AllowGroup = true;fpSpread1.Sheets[0].GroupFooterVisible = true;fpSpread1.Sheets[0].ColumnFooter.Visible = true;fpSpread1.Sheets[0].ColumnFooter.RowCount = 2;fpSpread1.Sheets[0].ColumnFooter.Columns[12].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Left;fpSpread1.Sheets[0].ColumnFooter.Cells[0, 12].RowSpan = 2;//Valuefor (int r = 0; r < fpSpread1.Sheets[0].RowCount; r++){for (int j = 0; j < fpSpread1.Sheets[0].ColumnCount; j++){fpSpread1.Sheets[0].Models.Data.SetValue(r, j, j + r * fpSpread1.Sheets[0].ColumnCount);}}int i = 0;fpSpread1.Sheets[0].ColumnFooter.SetAggregationType(0,1, FarPoint.Win.Spread.Model.AggregationType.Sum);fpSpread1.Sheets[0].ColumnFooter.Cells[0, i].Value = "Sum";}
private void fpSpread1_Grouped(object sender, EventArgs e)FarPoint.Win.Spread.Model.GroupDataModel gdm;gdm = (FarPoint.Win.Spread.Model.GroupDataModel)fpSpread1.ActiveSheet.Models.Data;gdm.GroupFooterVisible = true;FarPoint.Win.Spread.Model.Group g1 = (FarPoint.Win.Spread.Model.Group)gdm.Groups[1];((FarPoint.Win.Spread.Model.IAggregationSupport)g1.GroupFooter.DataModel).SetCellAggregationType(0, 0,FarPoint.Win.Spread.Model.AggregationType.Sum);fpSpread1.ActiveSheet.Models.Data = gdm;}
VBPrivate Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.LoadFpSpread1.Sheets(0).RowCount = 8
Spread Windows Forms Developer’s Guide 125
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.Sheets(0).ColumnCount = 15FpSpread1.Sheets(0).GroupBarInfo.Visible = TrueFpSpread1.Sheets(0).AllowGroup = TrueFpSpread1.Sheets(0).GroupFooterVisible = TrueFpSpread1.Sheets(0).ColumnFooter.Visible = TrueFpSpread1.Sheets(0).ColumnFooter.RowCount = 2fpSpread1.Sheets(0).ColumnFooter.Columns(12).HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Left'ValueDim r As IntegerDim j As IntegerFor r = 0 To FpSpread1.Sheets(0).RowCountFor j = 0 To FpSpread1.Sheets(0).ColumnCountFpSpread1.Sheets(0).Models.Data.SetValue(r, j, j + r * FpSpread1.Sheets(0).ColumnCount)Next jNext rDim i As Integeri = 0FpSpread1.Sheets(0).ColumnFooter.SetAggregationType(0, 1, FarPoint.Win.Spread.Model.AggregationType.Sum)FpSpread1.Sheets(0).ColumnFooter.Cells(0, i).Value = "Sum"End Sub
Private Sub FpSpread1_Grouped(ByVal sender As Object, ByVal e As System.EventArgs) Handles FpSpread1.GroupedDim gdm As FarPoint.Win.Spread.Model.GroupDataModelDim g1 As FarPoint.Win.Spread.Model.Groupgdm = FpSpread1.Sheets(0).Models.Datagdm.GroupFooterVisible = Trueg1 = gdm.Groups(1)CType(g1.GroupFooter.DataModel, FarPoint.Win.Spread.Model.IAggregationSupport).SetCellAggregationType(0, 0, FarPoint.Win.Spread.Model.AggregationType.Sum)FpSpread1.ActiveSheet.Models.Data = gdmEnd Sub
Example
Thisexamplecodedisplaysacolumnfooterandaddsaformulafromadifferentsheet.
C#fpSpread1.Sheets.Count = 3;fpSpread1.Sheets[0].RowCount = 8;fpSpread1.Sheets[0].ColumnCount = 15;fpSpread1.Sheets[0].GroupBarInfo.Visible = true;fpSpread1.Sheets[0].AllowGroup = true;fpSpread1.Sheets[0].GroupFooterVisible = true;fpSpread1.Sheets[0].ColumnFooter.Visible = true;fpSpread1.Sheets[0].ColumnFooter.RowCount = 2;fpSpread1.Sheets[0].ColumnFooter.Columns[12].HorizontalAlignment =FarPoint.Win.Spread.CellHorizontalAlignment.Left;fpSpread1.Sheets[0].ColumnFooter.Cells[0, 12].RowSpan = 2;//Valuefor (int r = 0; r < fpSpread1.Sheets[0].RowCount; r++){ for (int j = 0; j < fpSpread1.Sheets[0].ColumnCount; j++) { fpSpread1.Sheets[0].Models.Data.SetValue(r, j, j + r * fpSpread1.Sheets[0].ColumnCount); }}
int i = 0; fpSpread1.Sheets[1].RowCount = 10;
Spread Windows Forms Developer’s Guide 126
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.Sheets[1].ColumnCount = 15;fpSpread1.Sheets[1].GroupBarInfo.Visible = true;fpSpread1.Sheets[1].AllowGroup = true;fpSpread1.Sheets[1].GroupFooterVisible = true;fpSpread1.Sheets[1].ColumnFooter.Visible = true;fpSpread1.Sheets[1].ColumnFooter.RowCount = 2;fpSpread1.Sheets[1].ColumnFooter.Columns[12].HorizontalAlignment =FarPoint.Win.Spread.CellHorizontalAlignment.Left;fpSpread1.Sheets[1].ColumnFooter.Cells[0, 12].RowSpan = 2;//Valuefor (int r = 0; r < fpSpread1.Sheets[1].RowCount; r++){ for (int j = 0; j < fpSpread1.Sheets[1].ColumnCount; j++) { fpSpread1.Sheets[1].Models.Data.SetValue(r, j, j + r * fpSpread1.Sheets[1].ColumnCount); }} fpSpread1.Sheets[0].ColumnFooter.Cells[0, i].Value = "2ndSum";fpSpread1.Sheets[0].ColumnFooter.Cells[0, 1].Formula = "SUM(Sheet2!A:A)";
VBFpSpread1.Sheets.Count = 3FpSpread1.Sheets(0).RowCount = 8FpSpread1.Sheets(0).ColumnCount = 15FpSpread1.Sheets(0).GroupBarInfo.Visible = TrueFpSpread1.Sheets(0).AllowGroup = TrueFpSpread1.Sheets(0).GroupFooterVisible = TrueFpSpread1.Sheets(0).ColumnFooter.Visible = TrueFpSpread1.Sheets(0).ColumnFooter.RowCount = 2FpSpread1.Sheets(0).ColumnFooter.Columns(12).HorizontalAlignment =FarPoint.Win.Spread.CellHorizontalAlignment.Left'ValueDim r As IntegerDim j As IntegerFor r = 0 To FpSpread1.Sheets(0).RowCount For j = 0 To FpSpread1.Sheets(0).ColumnCount FpSpread1.Sheets(0).Models.Data.SetValue(r, j, j + r * FpSpread1.Sheets(0).ColumnCount) Next jNext r
FpSpread1.Sheets(1).RowCount = 10FpSpread1.Sheets(1).ColumnCount = 15FpSpread1.Sheets(1).GroupBarInfo.Visible = TrueFpSpread1.Sheets(1).AllowGroup = TrueFpSpread1.Sheets(1).GroupFooterVisible = TrueFpSpread1.Sheets(1).ColumnFooter.Visible = TrueFpSpread1.Sheets(1).ColumnFooter.RowCount = 2FpSpread1.Sheets(1).ColumnFooter.Columns(12).HorizontalAlignment =FarPoint.Win.Spread.CellHorizontalAlignment.LeftFpSpread1.Sheets(1).ColumnFooter.Cells(0, 12).RowSpan = 2'ValueFor r = 0 To FpSpread1.Sheets(1).RowCount For j = 0 To FpSpread1.Sheets(1).ColumnCount FpSpread1.Sheets(1).Models.Data.SetValue(r, j, j + r * FpSpread1.Sheets(1).ColumnCount) Next jNext r
Dim i As Integeri = 0FpSpread1.Sheets(0).ColumnFooter.Cells(0, i).Value = "2ndSum"FpSpread1.Sheets(0).ColumnFooter.Cells(0, 1).Formula = "SUM(Sheet2!A:A)"
Spread Windows Forms Developer’s Guide 127
Copyright © GrapeCity, Inc. All rights reserved.
Applying a Skin to a Sheet
Youcanquicklycustomizetheappearanceofasheetbyapplyinga"skin"toit.Askinissimplyacollectionofappearancepropertiesthatapplytoanentiresheetsuchascolors,gridlines,andwhethertoshowheaders.Thissavesyouthetimeandeffortofsettingthepropertiesindividually.
Spreadincludesseveralbuilt-inskinsthatarealreadymadeandreadyforyoutouse.YoucanalsocreateyourowncustomskinandsaveitsothatyoucanuseitinotherSpreadcomponentsforacommonformat.
Ifyouapplyaskintoasheetwithahierarchyofchildsheets,besuretoapplytheskintotheparentsheetaswellastoeachofthechildsheets.Formoreinformationonhierarchicaldisplays,refertoWorkingwithHierarchicalDataDisplay.
Formoreinformationandinstructionsabout
See
Creatingandapplyingyourownsheetskins CreatingaCustomSkinforaSheet
Creatingandapplyingyourowncell-levelstyles CreatingandApplyingaStyleforCells
Savingthesheetskintoafileorstream SavingandLoadingaSkin
CustomizingaskinintheSpreadDesigner SheetSkinEditor(on-linedocumentation)intheSpreadDesignerGuide
Sheetskins SheetSkin('SheetSkinClass'intheon-linedocumentation)class
UsingtheSheetSkinEditor
1. Ifyouwanttocreateyourownsheetskin,followtheinstructionsprovidedinCreatingaCustomSkinforaSheettocreateasheetskinandapplyit.Toapplyadefaultsheetskintoasheet,followthesedirections.
2. IntheFormwindow,clicktheSheetViewobjectforwhichyouwanttosettheskin.3. AtthebottomofthePropertieswindow,clicktheEditSkinsverb.4. IntheSheetSkinEditor,selectoneofthepredefinedskinsinthePre-Definedlist,thenclickOKtoclosethe
editor.
UsingaShortcut
1. Ifyouwanttocreateyourownsheetskin,followtheinstructionsprovidedinCreatingaCustomSkinforaSheettocreateasheetskinandapplyit.Toapplyadefaultsheetskin,followthesedirections.
2. UsetheApply('ApplyMethod'intheon-linedocumentation)methodontheselecteddefaultskin(setbythepropertyintheDefaultSkins('DefaultSkinsClass'intheon-linedocumentation)object)toapplyaspecifieddefaultskintoaspecificSpreadcomponent,collectionofsheets,orsheet.
Example
ThisexamplecodesetsthefirstsheettousetheColorful2predefinedskin.
C#FarPoint.Win.Spread.DefaultSkins.Colorful2.Apply(fpSpread1.Sheets[0]);
VBFarPoint.Win.Spread.DefaultSkins.Colorful2.Apply(FpSpread1.Sheets(0))
Spread Windows Forms Developer’s Guide 128
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
1. Ifyouwanttocreateyourownsheetskin,followtheinstructionsprovidedinCreatingaCustomSkinforaSheettocreateasheetskinandapplyit.Toapplyadefaultsheetskin,followthesedirections.
2. UsetheApply('ApplyMethod'intheon-linedocumentation)methodontheselecteddefaultskin(setbythepropertyintheDefaultSkins('DefaultSkinsClass'intheon-linedocumentation)object)toapplyaspecifieddefaultskintoaspecificSpreadcomponent,collectionofsheets,orsheet.
Example
ThisexamplecodesetsthefirstsheettousetheColorful2predefinedskin.
C#// Create new SheetView object.FarPoint.Win.Spread.SheetView newsheet = new FarPoint.Win.Spread.SheetView();// Apply a skin to the SheetView object.FarPoint.Win.Spread.DefaultSkins.Colorful2.Apply(newsheet);// Assign the SheetView object to the first sheet in the component.fpSpread1.Sheets[0] = newsheet;
VB' Create new SheetView object.Dim newsheet As New FarPoint.Win.Spread.SheetView()' Apply a skin to the SheetView object.FarPoint.Win.Spread.DefaultSkins.Colorful2.Apply(newsheet)' Assign the SheetView object to the first sheet in the component.FpSpread1.Sheets(0) = newsheet
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosettheskin.2. FromtheSettingsmenu,chooseSheetSkinDesigner.3. IntheSheetSkinEditor,selectoneofthepredefinedskinsfromthePre-Definedtab,orasavedcustomskin
fromtheSavedtab.4. ClickOKtoclosetheeditor.5. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Creating a Custom Skin for a Sheet
Youcanquicklycustomizetheappearanceofasheetbyapplyinga"skin"toit.Somebuilt-inskinsareprovidedwithSpreadtocreatecommonformats.Youcancreateyourowncustomskinandsaveittouseagain,similartoatemplate.Askin,whetherbuilt-inorcustom,canbeappliedtoanynumberofsheets.Justasastylecanbeappliedtocells,soaskincanbeappliedtoanentiresheet.
Formoreinformationandinstructionsabout
See
Applyingthebuilt-insheetskins ApplyingaSkintoaSheet
Creatingandapplyingyourowncell-levelstyles CreatingandApplyingaStyleforCells
Savingthesheetskintoafileorstream SavingandLoadingaSkin
Underlyingmodelforskins UnderstandingtheStyleModel
Spread Windows Forms Developer’s Guide 129
Copyright © GrapeCity, Inc. All rights reserved.
CustomizingaskinintheSpreadDesigner SheetSkinEditor(on-linedocumentation)intheSpreadDesignerGuide
Sheetskins SheetSkin('SheetSkinClass'intheon-linedocumentation)class
UsingtheSheetSkinEditor
1. IntheFormwindow,clicktheSheetViewobjectforwhichyouwanttocreatetheskin.2. InthePropertieswindow,intheAppearancecategory,selecttheActiveSkinpropertyandclickonthe
buttontolaunchtheSheetSkinEditor.3. IntheSheetSkinEditor,selecttheCustomtab.4. SetthepropertiesintheCustomtabtocreatetheskinyouwant.5. SettheNamepropertytospecifythenameforyourcustomskin.6. ClicktheSaveSkinbuttontosavetheskin.
Adialogappearssayingtheskinhasbeensaved.
7. ClickOKtoclosetheeditorandapplytheskinyoucreatedtothesheet,orclickCanceltoclosetheeditorandnotapplytheskinyoucreated.
UsingaShortcut
1. UsetheSheetSkin('SheetSkinClass'intheon-linedocumentation)objectconstructor,andsetitsparameterstospecifythesettingsfortheskin.
2. UsetheApply('ApplyMethod'intheon-linedocumentation)methodoftheSheetSkin('SheetSkinClass'intheon-linedocumentation)objecttoapplyittothecomponent,asheet,orasetofsheets.
Example
Thisexamplecodesetsthefirstsheettouseacustomskin.
C#// Create a custom skin.FarPoint.Win.Spread.SheetSkin myskin = new FarPoint.Win.Spread.SheetSkin("MySkin", Color.AliceBlue, Color.BlanchedAlmond, Color.Navy, Color.CornflowerBlue, FarPoint.Win.Spread.GridLines.Both, Color.Coral, Color.Navy, Color.Bisque, Color.Crimson, Color.AntiqueWhite, Color.BlanchedAlmond, true, true, true, true, true);// Apply the custom skin to the first sheet in the component.myskin.Apply(fpSpread1.Sheets[0]);
VB' Create a custom skin.Dim myskin As New FarPoint.Win.Spread.SheetSkin("MySkin", Color.AliceBlue, Color.BlanchedAlmond, Color.Navy, Color.CornflowerBlue, FarPoint.Win.Spread.GridLines.Both, Color.Coral, Color.Navy, Color.Bisque, Color.Crimson, Color.AntiqueWhite, Color.BlanchedAlmond, True, True, True, True, True)' Apply the custom skin to the first sheet in the component.myskin.Apply(FpSpread1.Sheets(0))
UsingCode
1. CalltheSheetSkinobjectconstructor,andsetitsparameterstospecifythesettingsfortheskin.2. CalltheSheetSkinobjectApplymethodtoapplyittothecomponent,asheet,orasetofsheets.
Spread Windows Forms Developer’s Guide 130
Copyright © GrapeCity, Inc. All rights reserved.
Example
Thisexamplecodesetsthefirstsheettouseacustomskin.
C#// Create a custom skin.FarPoint.Win.Spread.SheetSkin myskin = new FarPoint.Win.Spread.SheetSkin("MySkin", Color.AliceBlue, Color.BlanchedAlmond, Color.Navy, Color.CornflowerBlue, FarPoint.Win.Spread.GridLines.Both, Color.Coral, Color.Navy, Color.Bisque, Color.Crimson, Color.AntiqueWhite, Color.BlanchedAlmond, true, true, true, true, true);// Create a new SheetView object.FarPoint.Win.Spread.SheetView newsheet = new FarPoint.Win.Spread.SheetView();// Apply the custom skin to the SheetView object.myskin.Apply(newsheet);// Assign the SheetView object to the first sheet in the component.fpSpread1.Sheets[0] = newsheet;
VB' Create a custom skin.Dim myskin As New FarPoint.Win.Spread.SheetSkin("MySkin", Color.AliceBlue, Color.BlanchedAlmond, Color.Navy, Color.CornflowerBlue, FarPoint.Win.Spread.GridLines.Both, Color.Coral, Color.Navy, Color.Bisque, Color.Crimson, Color.AntiqueWhite, Color.BlanchedAlmond, True, True, True, True, True)' Create a new SheetView object.Dim newsheet As New FarPoint.Win.Spread.SheetView()' Apply the custom skin to the SheetView object.myskin.Apply(newsheet)' Assign the SheetView object to the first sheet in the component.FpSpread1.Sheets(0) = newsheet
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosettheskin.2. FromtheSettingsmenu,chooseSheetSkinEditor.3. IntheSheetSkinEditor,selecttheCustomtab.4. Setthepropertiesforthenewcustomsheetskin,includingtheNamepropertytonameyourskin.5. SelecttheSaveSkinbutton.Amessageboxappearstellingyouyourcustomskinhasbeensaved.
6. ClickOKtoclosetheSheetSkinEditor.7. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing the Sheet Corner Appearance
Youcancustomizetheappearanceofthesheetcorner,theheadercellintheupperleftcornerofthesheet,foreachsheet.Inmanyways,customizingthesheetcornerissimilartocustomizingcellsorsheets.
Thesetopicsdiscussthesheetcornerfeatures:
GeneralStyleoftheSheetCornerTextDisplayintheSheetCornerTableDisplayintheSheetCorner
Spread Windows Forms Developer’s Guide 131
Copyright © GrapeCity, Inc. All rights reserved.
CustomizableCellintheSheetCornerCellSpansintheSheetCornerHeaderCountSynchronizationintheSheetCornerDrawing(Rendering)Style
OperationalSupport
ThesheetcornersupportsXMLserializationanddeserializationalongwithsheet.AnythingchangedinthesheetcornerissavedwiththeSpreadwhenyousaveSpread.
Thesheetcornersupportscopyandpastingcellsbetweensheets.Youcanselectasheetbyclickinginsheetcorner,thenpressCtrl+CtocopyitandthengotoanothersheetandpressCtrl+Vtopastethesheetandthesheetcorner.
ThesheetcornersupportsPDFprintingandnormalprintingsoyoucanprintthesheetcorneralongwiththesheet.
Theunderlyingmodelsofthesheetcornerareexposedthroughthesheetmodelpropertyandyoucanchangethismodel.Thefollowingclassesareinvolvedinthesheetcorner.
FarPoint.Win.SpreadNamespace:SheetCorner('SheetCornerClass'intheon-linedocumentation)ClassFarPoint.Win.Spread.CellTypeNamespace:IRenderer('IRendererInterface'intheon-linedocumentation)InterfaceFarPoint.Win.Spread.CellTypeNamespace:CornerRenderer('CornerRendererClass'intheon-linedocumentation)ClassFarPoint.Win.Spread.CellTypeNamespace:EnhancedCornerRenderer('EnhancedCornerRendererClass'intheon-linedocumentation)Class
General Style of the Sheet Corner
Sheetcornerscandisplaygridlines,haveadifferentbackgroundcolorfromtherestoftheheaders,andmore.Thereareseveraldifferentwaystosetpropertiesinthesheetcorner.OnewayiswiththeSheetCorner('SheetCornerClass'intheon-linedocumentation)class.AnotheroptionistosetthesheetcornerpropertiesfortheSheetView('SheetViewClass'intheon-linedocumentation)class.Inthefollowingfigure,thesheetcornerisdisplayedwithatwo-pixelwide,greenborderandalightbluebackground.
Thesheetcornersupportsright-to-leftorientation.WhenyousetRight-to-LeftmodeinSpreadfortheentirespreadsheet,thesheetcorneralsodisplayswithright-to-leftorientationaswell.
GeneralCustomization
SeveralofthepropertiesofaStyleInfoobjectcanbesetforthesheetcornercell.Thesepropertiesinclude:
backgroundcolor-thebackgroundcolorofthecellborder-theborderaroundthecellcelltype-thetypeofcellfont-thefontsettingsofthecelltextcolor-thecoloroftextcolorinthecell
Spread Windows Forms Developer’s Guide 132
Copyright © GrapeCity, Inc. All rights reserved.
alignment-thealignmentoftextinthecell(horizontalandvertical)
ThefollowingfiguredisplaysasheetcornerthathasbeencustomizedwiththeSheetCorner('SheetCornerClass'intheon-linedocumentation)class.
Thefollowingsectionsprovideinstructionsandexamplecodeforcustomizingmanyaspectsofthesheetcorner.
UsingCode
YoucansetthesheetcornerstyleusingthepropertiesoftheSheetCorner('SheetCornerClass'intheon-linedocumentation)class.
Example
Thisexamplecodesetsthebackgroundcolor,setsborders,putstextinacell,andsetstherowandcolumncount.
C#fpSpread1.ActiveSheet.SheetCorner.DefaultStyle.Renderer = new FarPoint.Win.Spread.CellType.CornerRenderer();fpSpread1.ActiveSheet.AllowTableCorner = true;fpSpread1.ActiveSheet.SheetCorner.RowCount = 6;fpSpread1.ActiveSheet.SheetCorner.ColumnCount = 6;fpSpread1.ActiveSheet.SheetCorner.AlternatingRows[0].BackColor = Color.Violet;fpSpread1.ActiveSheet.SheetCorner.Cells[0, 0].Text = "Test";fpSpread1.ActiveSheet.SheetCorner.Columns[0].Border = new FarPoint.Win.LineBorder(Color.Green);fpSpread1.ActiveSheet.SheetCorner.Rows[0].Border = new FarPoint.Win.LineBorder(Color.Green);fpSpread1.ActiveSheet.SheetCorner.HorizontalGridLine = new FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.None);fpSpread1.ActiveSheet.SheetCorner.VerticalGridLine = new FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.None);fpSpread1.ActiveSheet.SheetCorner.DefaultStyle.VisualStyles = FarPoint.Win.VisualStyles.Off;
VBFpSpread1.ActiveSheet.SheetCorner.DefaultStyle.Renderer = New FarPoint.Win.Spread.CellType.CornerRendererFpSpread1.ActiveSheet.AllowTableCorner = TrueFpSpread1.ActiveSheet.SheetCorner.RowCount = 6FpSpread1.ActiveSheet.SheetCorner.ColumnCount = 6FpSpread1.ActiveSheet.SheetCorner.AlternatingRows(0).BackColor = Color.Violet
Spread Windows Forms Developer’s Guide 133
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.ActiveSheet.SheetCorner.Cells(0, 0).Text = "Test"FpSpread1.ActiveSheet.SheetCorner.Columns(0).Border = New FarPoint.Win.LineBorder(Color.Green)FpSpread1.ActiveSheet.SheetCorner.Rows(0).Border = New FarPoint.Win.LineBorder(Color.Green)FpSpread1.ActiveSheet.SheetCorner.HorizontalGridLine = New FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.None)FpSpread1.ActiveSheet.SheetCorner.VerticalGridLine = New FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.None)FpSpread1.ActiveSheet.SheetCorner.DefaultStyle.VisualStyles = FarPoint.Win.VisualStyles.Off
CustomizingtheCornerColor
YoucansetthesheetcornerstylebyusingtheSheetCornerStyle('SheetCornerStyleProperty'intheon-linedocumentation)propertyoftheSheetView('SheetViewClass'intheon-linedocumentation)objecttospecifyindividualpropertiesofthesheetcorner(asinthefollowingexample).YoucanalsospecifythegridlinesaroundthesheetcornerusingtheSheetCornerHorizontalGridLine('SheetCornerHorizontalGridLineProperty'intheon-linedocumentation)andSheetCornerVerticalGridLine('SheetCornerVerticalGridLineProperty'intheon-linedocumentation)properties.
Example
Thisexamplecodesetsthebackgroundcolortolightblueandsetstheborderasshowninthefigure.
C#fpSpread1.ActiveSheet.ColumnHeader.RowCount = 3;fpSpread1.ActiveSheet.RowHeader.ColumnCount = 3;fpSpread1.ActiveSheet.SheetCorner.DefaultStyle.Renderer = new FarPoint.Win.Spread.CellType.CornerRenderer();fpSpread1.ActiveSheet.SheetCornerStyle.BackColor = Color.LightBlue;fpSpread1.ActiveSheet.SheetCornerStyle.Border = new FarPoint.Win.LineBorder(Color.Green, 2);
VBFpSpread1.ActiveSheet.ColumnHeader.RowCount = 3FpSpread1.ActiveSheet.RowHeader.ColumnCount = 3FpSpread1.ActiveSheet.SheetCorner.DefaultStyle.Renderer = New FarPoint.Win.Spread.CellType.CornerRendererFpSpread1.ActiveSheet.SheetCornerStyle.BackColor = Color.LightBlueFpSpread1.ActiveSheet.SheetCornerStyle.Border = New FarPoint.Win.LineBorder(Color.Green, 2)
CustomizingtheCornerImage
Youcanplaceagraphicinthesheetcornerbysettingabackgroundimagetoacelltypeandassigningthatcelltypetothesheetcorner,whichisjustacell.Then,specifyaparticulargraphicfilefortheimage(Pictureobject).
Example
Thisexamplecodesetsthebackgroundimageofacelltypeandassignsthatcelltypetothesheetcorner.
C#
Spread Windows Forms Developer’s Guide 134
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Spread.CellType.GeneralCellType gencell = new FarPoint.Win.Spread.CellType.GeneralCellType();FarPoint.Win.Picture cornerimage = new FarPoint.Win.Picture(Image.FromFile("D:\\images\\logocorner.jpg"));gencell.BackgroundImage = cornerimage;fpSpread1.ActiveSheet.SheetCornerStyle.CellType = gencell;
VBDim gencell As New FarPoint.Win.Spread.CellType.GeneralCellTypeDim cornerimage As New FarPoint.Win.Picture(Image.FromFile("D:\images\logocorner.jpg"))gencell.BackgroundImage = cornerimageFpSpread1.ActiveSheet.SheetCornerStyle.CellType = gencell
Text Display in the Sheet Corner
YoucanaddtexttothesheetcornercellofthespreadsheetbysettingtheSheetCornerpropertiesoroverridingthePaintCellmethod.Thefigureshowstheresultsoftheexamplecodeinthistopic.
ForinformationaboutsettingtextusingtheSheetCornerproperties,seeGeneralStyleoftheSheetCorner.
UsingCode
Youcanassigntexttothesheetcornercellbyoverridingthepaintingofthecellandpaintingitwiththespecifiedtext.
Example
C#class CornerCell : FarPoint.Win.Spread.CellType.GeneralCellType{ public override void PaintCell(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearance appearance, object value, bool isSelected, bool isLocked, float zoomFactor) { base.PaintCell(g, r, appearance, "Text", isSelected, isLocked, zoomFactor); }}
CornerCell sctextcell = new CornerCell();fpSpread1.Sheets[0].SheetCornerStyle.CellType = sctextcell;
VBPublic Class SheetCornerInherits FarPoint.Win.Spread.CellType.GeneralCellType Public Overrides Sub PaintCell(ByVal g As System.Drawing.Graphics, ByVal r As System.Drawing.Rectangle, ByVal appearance As FarPoint.Win.Spread.Appearance, ByVal value As Object, ByVal isSelected As Boolean, ByVal isLocked As Boolean, ByVal zoomFactor As Single)
Spread Windows Forms Developer’s Guide 135
Copyright © GrapeCity, Inc. All rights reserved.
MyBase.PaintCell(g, r, appearance, "Text", isSelected, isLocked, zoomFactor) End SubEnd Class
Dim sctextcell As New SheetCorner()FpSpread1.Sheets(0).SheetCornerStyle.CellType = sctextcell
Table Display in the Sheet Corner
Thesheetcornercanhaveatableorgriddisplaywithcolumnsandrowsofcells,thoughcellsarenoteditable.Youcansetthesheetcornertoatable(range)displayorasinglecelldisplaywiththeAllowTableCorner('AllowTableCornerProperty'intheon-linedocumentation)propertyofthesheet(SheetView('SheetViewClass'intheon-linedocumentation)class).
Thesheetcorneralsosupportscellspansinthetabledisplay.
WhenyousettheAllowTableCorner('AllowTableCornerProperty'intheon-linedocumentation)propertyofthesheettotrue,thesheetcornerdisplaysasatablewiththenumberofcolumnsequaltothenumberofrowheadersofthesheetandthenumberofrowsequaltothenumberofcolumnheadersofthesheet.Thefollowingfigureillustratesatablesheetcornerdisplay:
WhenyousettheAllowTableCorner('AllowTableCornerProperty'intheon-linedocumentation)propertyofthesheettofalse,thefirstcellofthesheetcornerspanstheentireareaofthesheetcorner,basedonthenumberofcolumnsandrowssetforthecorner.Thefollowingfigureillustratesasingle-cellsheetcornerdisplay:
Example
Thefollowingcodesetsthesheetcornertoappearasatable.
C#
Spread Windows Forms Developer’s Guide 136
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.ActiveSheet.AllowTableCorner = true;fpSpread1.ActiveSheet.SheetCorner.ColumnCount = 4;fpSpread1.ActiveSheet.SheetCorner.RowCount = 5;
VBFpSpread1.ActiveSheet.AllowTableCorner = TrueFpSpread1.ActiveSheet.SheetCorner.ColumnCount = 4FpSpread1.ActiveSheet.SheetCorner.RowCount = 5
Example
Thefollowingcodesetsthesheetcornertoappearasasinglecell.
C#fpSpread1.ActiveSheet.AllowTableCorner = false;fpSpread1.ActiveSheet.SheetCorner.ColumnCount = 4;fpSpread1.ActiveSheet.SheetCorner.RowCount = 5;
VBFpSpread1.ActiveSheet.AllowTableCorner = FalseFpSpread1.ActiveSheet.SheetCorner.ColumnCount = 4FpSpread1.ActiveSheet.SheetCorner.RowCount = 5
Customizable Cell in the Sheet Corner
Thesinglecellortableofcellsinthesheetcornercanbecustomized.YoucansetthecellstoanyofthecelltypesthataresupportedbySpread.YoucanalsocustomizepropertiesoftheCell('CellClass'intheon-linedocumentation)class.
YoucanchangethecelltypeofthecellsinthesheetcornerbysettinganewcelltypefortheSheetCornerStyle('SheetCornerStyleProperty'intheon-linedocumentation)propertyofthesheet(SheetView('SheetViewClass'intheon-linedocumentation)class).WhenyousettheSheetCornerStyle.CellType,allthecellsinthesheetcornerarechangedtothattype.
Thefollowingexamplessetthesheetcornertobeacheckboxorabutton.
Example
Thefollowingcodesetsthesheetcornertobecheckboxcellsbysettingthesheetcornerstyle(asshownintheprecedingillustration).
Spread Windows Forms Developer’s Guide 137
Copyright © GrapeCity, Inc. All rights reserved.
C#fpSpread1.ActiveSheet.AllowTableCorner = true;fpSpread1.ActiveSheet.SheetCorner.ColumnCount = 4;fpSpread1.ActiveSheet.SheetCorner.RowCount = 5;fpSpread1.ActiveSheet.SheetCornerStyle.CellType = new FarPoint.Win.Spread.CellType.CheckBoxCellType();
VBFpSpread1.ActiveSheet.AllowTableCorner = TrueFpSpread1.ActiveSheet.SheetCorner.ColumnCount = 4FpSpread1.ActiveSheet.SheetCorner.RowCount = 5FpSpread1.ActiveSheet.SheetCornerStyle.CellType = New FarPoint.Win.Spread.CellType.CheckBoxCellType()
Example
Thefollowingcodesetsthesheetcornertobebuttoncellsbyassigningthebuttoncelltypetothecellsinthesheetcorner(asshownintheprecedingillustration).
C#fpSpread1.ActiveSheet.AllowTableCorner = true;fpSpread1.ActiveSheet.SheetCorner.ColumnCount = 4;fpSpread1.ActiveSheet.SheetCorner.RowCount = 5;fpSpread1.ActiveSheet.SheetCorner.Cells[2,3].CellType = new FarPoint.Win.Spread.CellType.ButtonCellType();
VBFpSpread1.ActiveSheet.AllowTableCorner = TrueFpSpread1.ActiveSheet.SheetCorner.ColumnCount = 4FpSpread1.ActiveSheet.SheetCorner.RowCount = 5FpSpread1.ActiveSheet.SheetCorner.Cells(2,3).CellType = New FarPoint.Win.Spread.CellType.ButtonCellType()
Cell Spans in the Sheet Corner
Cellspansaresupportedinthesheetcorner.Anynumberofrowsandcolumnsofcellscanbeselectedandmergedtocreatecellspans.Youcansetspansofcellsinrowsorcolumnsorboth.
Spread Windows Forms Developer’s Guide 138
Copyright © GrapeCity, Inc. All rights reserved.
Formoreinformationoncreatingcellspans,refertoCreatingaSpanofCells.
Example
Thefollowingcodecreatesaspanofrowcellsandaspanofcolumncellsinthesheetcorner.
C#fpSpread1.ActiveSheet.AllowTableCorner = true;fpSpread1.ActiveSheet.SheetCorner.ColumnCount = 6;fpSpread1.ActiveSheet.SheetCorner.RowCount = 7;fpSpread1.ActiveSheet.SheetCorner.Cells[1, 2].ColumnSpan = 3;fpSpread1.ActiveSheet.SheetCorner.Cells[1, 2].RowSpan = 4;
VBFpSpread1.ActiveSheet.AllowTableCorner = TrueFpSpread1.ActiveSheet.SheetCorner.ColumnCount = 6FpSpread1.ActiveSheet.SheetCorner.RowCount = 7FpSpread1.ActiveSheet.SheetCorner.Cells(1, 2).ColumnSpan = 3FpSpread1.ActiveSheet.SheetCorner.Cells(1, 2).RowSpan = 4
Header Count Synchronization in the Sheet Corner
Thenumberofrowsandcolumnsinthesheetcornerdependonnumberofthecolumnheaderrowsandrowheadercolumnsofthesheet.Infact,thesetwoaresynchronizedbySpread,soifyouchangesheetcornersize,thesheetheaderrowsandcolumnsareadjustedaccordinglyandifyouchangethenumberofsheetheaderrowsorcolumnsofthesheet,thesheetcorneradjustsaccordingly.
YoucanusetheRowsandColumnspropertiesofthesheetcornertomodifythesheet’srowheadercolumncountandcolumnheaderrowcount.Therowcountofcolumnheadersofthesheetalwaysequalstherowcountofthesheetcorner;thecolumncountofrowheadersofthesheetalwaysequalsthecolumncountofthesheetcorner.
Example
Thefollowingexampleillustrateshowthenumberofrowsinthesheetcornerchangewhenyouchangethenumberofcolumnheaderrows.
C#fpSpread1.ActiveSheet.AllowTableCorner = true;fpSpread1.ActiveSheet.SheetCorner.ColumnCount = 6;
Spread Windows Forms Developer’s Guide 139
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.ActiveSheet.SheetCorner.RowCount = 7;//Change rows in sheet corner by change Row count of columns headerfpSpread1.ActiveSheet.ColumnHeader.RowCount = 5;
VBFpSpread1.ActiveSheet.AllowTableCorner = TrueFpSpread1.ActiveSheet.SheetCorner.ColumnCount = 6FpSpread1.ActiveSheet.SheetCorner.RowCount = 7'Change rows in sheet corner by change Row count of columns headerFpSpread1.ActiveSheet.ColumnHeader.RowCount = 5
Example
Thefollowingexampleillustrateshowthenumberofcolumnheaderrowschangewhenyouchangethenumberofsheetcornercolumns.
C#fpSpread1.ActiveSheet.ColumnHeader.RowCount = 5;fpSpread1.ActiveSheet.SheetCorner.ColumnCount = 3;
VBFpSpread1.ActiveSheet.ColumnHeader.RowCount = 5FpSpread1.ActiveSheet.SheetCorner.ColumnCount = 3
Drawing (Rendering) Style
Youcancustomizethecornerrenderer,whichdrawsthesheetcorner.
Therearetwopre-definedcornerrenderersinSpread.
ThedefaultrendererdrawsthesheetcornerwithorwithoutWindowsXPstyledependingonthesettingofthesystem.
TheenhancedcornerrendereralwaysdrawsthesheetcornerwithanappearancesimilartoMicrosoftExcel2007.
Example
Thisexampleliststhemethodsthatareusedtocreateacustomcornerrenderer.
C#public class MyCornerRenderer : IRenderer {/// <summary>/// Gets the preferred (maximum needed) size of the cell for the renderer control./// </summary>/// <param name="g">Graphics device interface for painting the cell</param>/// <param name="size">Preferred or maximum needed size</param>/// <param name="appearance">Appearance settings of the renderer control</param>/// <param name="value">Object containing the name of the renderer control</param>/// <param name="zoomFactor">Numeric value for zoom factor for scaling the display of the renderer control</param>/// <returns></returns>public Size GetPreferredSize(Graphics g, Size size, Appearance appearance, object value, float zoomFactor){
Spread Windows Forms Developer’s Guide 140
Copyright © GrapeCity, Inc. All rights reserved.
///Your Code add here}/// <summary>/// Paints the corner cell when not in edit mode to the specified graphics interface/// with the specified appearance settings./// </summary>/// <param name="g">Graphics device interface for painting the corner cell</param>/// <param name="r">Location and size of a rectangular region for painting the corner cell</param>/// <param name="appearance">Appearance settings of the corner cell</param>/// <param name="value">Object containing the name of the renderer control of the corner cell</param>/// <param name="isSelected">Whether the corner cell is selected</param>/// <param name="isLocked">Whether the corner cell is locked</param>/// <param name="zoomFactor">Numeric value for scaling the display of the corner cell</param>public virtual void PaintCell(Graphics g, Rectangle r, Appearance appearance, object value, bool isSelected, bool isLocked, float zoomFactor){///Your Code add here}/// <summary>/// Paints the corner cell./// </summary>/// <param name="g">Graphics device interface for painting the corner cell</param>/// <param name="r">Location and size of a rectangular region for painting the corner cell</param>/// <param name="backColor">Background color of the corner cell</param>/// <param name="foreColor">Foreground color of the corner cell</param>/// <param name="f">Font</param>/// <param name="horizontalAlignment">Horizontal alignment of corner cell content</param>/// <param name="verticalAlignment">Vertical alignment of the corner cell content</param>/// <param name="s">String to paint</param>/// <param name="textOrientation">Orientation of the text</param>/// <param name="wordWrap">Whether wrap words to multiple lines</param>/// <param name="hotkeyPrefix">Whether to show hotkey effect</param>/// <param name="stringTrim">String trimming mode</param>/// <param name="visualStyles">Visual styles</param>/// <param name="mouseOver">Whether the mouse is over the corner cell</param>/// <param name="rightToLeft">Whether to display right to left</param>/// <param name="zoomFactor">Numeric value for scaling the display of the corner cell</param>public virtual void PaintCorner(Graphics g, Rectangle r, Color backColor, Color foreColor, Font f, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, string s, TextOrientation textOrientation, bool wordWrap, HotkeyPrefix hotkeyPrefix, StringTrimming stringTrim, VisualStyles visualStyles, bool mouseOver, bool rightToLeft, float zoomFactor){///Your Code add here}/// <summary>/// Determines whether this cell can overflow into an adjacent cell./// </summary>/// <returns></returns>public bool CanOverflow()
Spread Windows Forms Developer’s Guide 141
Copyright © GrapeCity, Inc. All rights reserved.
{///Your Code add here}/// <summary>/// Determines whether adjacent cells can overflow into this cell./// </summary>/// <returns></returns>public bool CanBeOverflown(){///Your Code add here}}// Assign new corner render to drawing sheet corner:fpSpread1.ActiveSheet.SheetCornerStyle.Renderer = new MyCornerRenderer();
Spread Windows Forms Developer’s Guide 142
Copyright © GrapeCity, Inc. All rights reserved.
Customizing Row, Column, and Cell Appearance
YoucancustomizetheappearanceofvariouspartsoftheSpreadcomponentattherow,column,andcelllevel.
ThetasksthatrelatetosettingtheappearanceofobjectsintheSpreadcomponentinclude:
CustomizingtheRoworColumnAppearanceCustomizingtheAppearanceofHeadersCustomizingtheAppearanceofaCell
ForinformationoncustomizingtheinteractionwithpartsoftheSpreadcomponent,refertoCustomizingSheetInteraction.
ForinformationoncustomizingtheappearanceusingtheSpreadDesigner,refertotheSpreadDesignerGuide(on-linedocumentation).
Customizing the Row or Column Appearance
Thesetasksrelatetosettingtheappearanceofcolumnsorrowsinthesheet:
SettingtheRowHeightorColumnWidthResizingtheRoworColumntoFittheDataFindingRowsorColumnsThatHaveDataCreatingAlternatingRows
Whenyouworkwithrowsandcolumns,youcanworkwiththeobjectsusingtheshortcutsincode(Row('RowClass'intheon-linedocumentation),Rows('RowsClass'intheon-linedocumentation),Column('ColumnClass'intheon-linedocumentation),Columns('ColumnsClass'intheon-linedocumentation),AlternatingRow('AlternatingRowClass'intheon-linedocumentation),AlternatingRows('AlternatingRowsClass'intheon-linedocumentation))oryoucanworkdirectlywiththemodel.Mostdeveloperswhoarenotcreatingextensivecustomizationsfinditeasiertoworkwiththeshortcutobjects.YoucaneditpropertiesoftheRowsandColumnsclassesinthePropertieswindow(inSpreadDesignerorinVisualStudio.NET).FormoreinformationontheCells,Columns,andRowsEditorthatisavailablefromthePropertieswindow,refertotheexplanationofthiseditorintheSpreadDesignerGuide(on-linedocumentation).
Aswithmostspreadsheetandgridproducts,Spreaddoesnotallowin-celleditingofthecellsintherowandcolumnheaders.
Settingsappliedtoaparticularroworcolumnoverridethesettingsthataresetatthesheetlevelandsettingsappliedatacellleveloverridetheroworcolumnsettings.Formoreinformation,refertoObjectParentage.
Formoreinformationabouttheappearanceofrowsasaresultoffiltering,refertoSettingtheAppearanceofFilteredRows.Formoreinformationabouttheappearanceofcells,refertoCreatingandApplyingaStyleforCells.Forinformationontheunderlyingmodelresponsibleforrowsandcolumns,refertotheUnderstandingtheAxisModel.Formoreinformation,refertotheRow('RowClass'intheon-linedocumentation),Rows('RowsClass'intheon-linedocumentation),AlternatingRow('AlternatingRowClass'intheon-linedocumentation),AlternatingRows('AlternatingRowsClass'intheon-linedocumentation),Column('ColumnClass'intheon-linedocumentation),andColumns('ColumnsClass'intheon-linedocumentation)objectsintheAssemblyReference.
Setting the Row Height or Column Width
Youcansettherowheightorcolumnwidthasaspecifiednumberofpixels.Eachsheetusesandletsyousetadefaultsize,makingallrowsorcolumnsinthesheetthesamesize.Youcanoverridethatsettingbysettingthevaluefor
Spread Windows Forms Developer’s Guide 143
Copyright © GrapeCity, Inc. All rights reserved.
individualrowsorcolumns.
Userscanchangetherowheightorcolumnwidthbydraggingtheheaderlinesbetweenrowsorcolumns.
FormoredetailsrefertotheColumn.Width('WidthProperty'intheon-linedocumentation)methodorRow.Height('HeightProperty'intheon-linedocumentation)method.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetforwhichtosetthecolumnwidthforacolumn.5. Inthepropertieslist,settheColumnsproperty(orRowproperty)andthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Clickthecolumnheadingofthecolumnforwhichyouwanttosetthewidth(orrowfortheheight).7. Inthepropertieslist,settheWidthproperty(Heightpropertyfortherow).8. ClickOKtoclosetheCell,Column,andRowEditor.9. ClickOKtoclosetheSheetViewCollectionEditor.
UsingaShortcut
SettheColumnsshortcutobjectWidth('WidthProperty'intheon-linedocumentation)property.Youcanuse-1forallcolumns(Columns[-1]).
Example
Thisexamplecodesetsthesecondcolumn’swidthto100pixels.
C#// Set second column width to 100.fpSpread1.Sheets[0].Columns[1].Width = 100;
VB' Set second column width to 100.FpSpread1.Sheets(0).Columns(1).Width = 100
UsingCode
Spread Windows Forms Developer’s Guide 144
Copyright © GrapeCity, Inc. All rights reserved.
SettheWidth('WidthProperty'intheon-linedocumentation)propertyforaColumn('ColumnClass'intheon-linedocumentation)object.
Example
Thisexamplecodesetsthesecondcolumn’swidthto100pixels.
C#FarPoint.Win.Spread.Column Col1;Col1 = fpSpread1.Sheets[0].Columns[1];Col1.Width = 100;
VBDim Col1 As FarPoint.Win.Spread.ColumnCol1 = FpSpread1.Sheets(0).Columns(1)Col1.Width = 100
UsingtheSpreadDesigner
1. Tosetthedefaultcolumnwidth,a. Selectthesheettabforthesheetforwhichyouwanttosetthedefaultcolumnwidth.b. Inthepropertylist,intheAppearancecategory,selectColumnstoexpandthelistofpropertiesforthe
columns.c. Inthelistofpropertiesforcolumns,selectDefaulttoexpandthelistofdefaultcolumnsettings.d. Inthelistofdefaultsettings,changetheWidthsetting.e. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
2. Tosetaspecificcolumnwidth,a. Selectthecolumnforwhichyouwanttochangethewidth.b. Inthepropertieslistforthatcolumn,changetheWidthproperty.c. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Resizing the Row or Column to Fit the Data
Youcanresizethecolumnwidthorrowheightbasedonthelengthorbreadthofdatainthecellsinthatcolumnorrow.Thesizeoftheroworcolumnwiththelargestdataisreferredtoasthepreferredsize.
Themethodsthatmakeuseofthepreferredsizeare:
Row('RowClass'intheon-linedocumentation)class,GetPreferredHeight('GetPreferredHeightMethod'intheon-linedocumentation)methodColumn('ColumnClass'intheon-linedocumentation)class,GetPreferredWidth('GetPreferredWidthMethod'intheon-linedocumentation)methodSheetView('SheetViewClass'intheon-linedocumentation)class,GetPreferredRowHeight('GetPreferredRowHeightMethod'intheon-linedocumentation)methodSheetView('SheetViewClass'intheon-linedocumentation)class,GetPreferredColumnWidth('GetPreferredColumnWidthMethod'intheon-linedocumentation)methodSheetView('SheetViewClass'intheon-linedocumentation)class,GetPreferredCellSize('GetPreferredCellSizeMethod'intheon-linedocumentation)method
TheRowclassGetPreferredHeight('GetPreferredHeightMethod'intheon-linedocumentation)method
Spread Windows Forms Developer’s Guide 145
Copyright © GrapeCity, Inc. All rights reserved.
andColumnclassGetPreferredWidth('GetPreferredWidthMethod'intheon-linedocumentation)methodalwaysincludetheheadercells.TheSheetView('SheetViewClass'intheon-linedocumentation)classoverloadedGetPreferredColumnWidth('GetPreferredColumnWidthMethod'intheon-linedocumentation)methodhasoneoverloadthatalwaysincludestheheadercellswhileanotheroverloadallowsyoutochoosewhethertoincludeorexcludeheadercells.Inthefollowingcode,width1andwidth2includetheheadercellsbutwidth3excludestheheadercells.
float width1 = fpspread.Sheets[0].Columns[0].GetPreferredWidth();
float width2 = fpspread.Sheets[0].GetPreferredColumnWidth(0);
float width3 = fpspread.Sheets[0].GetPreferredColumnWidth(0, true);
Forinformationonsettingthecellsizebasedonthesizeofthedata,refertoResizingaCelltoFittheData.
Forinformationonallowingtheusertoresizethedata,refertoAllowingtheUsertoResizeRowsorColumns.
UsingCode
Usethelistedmethodstosetthewidthandheightofcolumnsorrows.
Example
Thisexamplesetstherowheightandcolumnwidth.
C#FarPoint.Win.Spread.Row row;FarPoint.Win.Spread.Column col;float sizerow;float sizercol;row = fpSpread1.ActiveSheet.Rows[0];col = fpSpread1.ActiveSheet.Columns[0];fpSpread1.ActiveSheet.Cells[0, 0].Text = "This text is used to determine the height and width.";sizerow = row.GetPreferredHeight();sizecol = col.GetPreferredWidth();row.Height = sizerow;col.Width = sizecol;
VBDim row As FarPoint.Win.Spread.RowDim col As FarPoint.Win.Spread.ColumnDim sizerow As SingleDim sizecol As Singlerow = FpSpread1.ActiveSheet.Rows(0)col = FpSpread1.ActiveSheet.Columns(0)FpSpread1.ActiveSheet.Cells(0, 0).Text = "This text is used to determine the height and width."sizerow = row.GetPreferredHeight()sizecol = col.GetPreferredWidth()row.Height = sizerowcol.Width = sizecol
Finding Rows or Columns That Have Data
Youcanworkwiththerowsandcolumnsofthesheetanddistinguishwhichoneshavedatabyusingvariousmembersof
Spread Windows Forms Developer’s Guide 146
Copyright © GrapeCity, Inc. All rights reserved.
theSheetView('SheetViewClass'intheon-linedocumentation)class.Youcanusethefollowingmethodsavailableonthesheet:
GetLastNonEmptyColumn('GetLastNonEmptyColumnMethod'intheon-linedocumentation)methodGetLastNonEmptyRow('GetLastNonEmptyRowMethod'intheon-linedocumentation)method
Youcanreturnthenumberofrowsandcolumnsthathavedatausingtheseproperties:
NonEmptyColumnCount('NonEmptyColumnCountProperty'intheon-linedocumentation)propertyNonEmptyColumnCount('NonEmptyColumnCountProperty'intheon-linedocumentation)property
Creating Alternating Rows
Youmightwanttosetupyoursheetsothatalternatingrowshaveadifferentappearance.Forexample,inaledger,alternatingrowsoftenhaveagreenbackground.InSpread,youcansetupmultiplealternatingrowappearances,whichareappliedinsequence,startingwiththefirstrow.
Setupthealternatingrowsusinganindexintothealternatingrowappearances.Itmighthelptothinkofthedefaultrowappearanceasthefirstalternatingrowstyle(orstylezero,becausetheindexiszero-based).Settheotheralternatingrowappearancestosubsequentindexes.
Thefigurehereshowstheresultsforthefollowingexamplecodeforsettingupalternatingrowsforeverythreerows.
Formoredetails,refertotheAlternatingRow('AlternatingRowClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. Selectthesheetforwhichyouwanttocreatealternatingrowsfromthecollectionlist.5. SelecttheAlternatingRowspropertyfromthepropertylistforthatsheet.6. Ifyouwanttoaddadditionalalternatingrowspatterns,settheCountpropertytothenumberofpatternsyou
want.7. ClicktheAlternatingRowspropertybuttontodisplaytheAlternatingRowCollectionEditor.8. Selectalternatingrowpatternforwhichtosetproperties.9. Setpropertiesfortheselectedpatternusingthepropertylist.10. ClickOKtoclosetheAlternatingRowCollectionEditor.11. ClickOKtoclosetheSheetViewCollectionEditor.
Spread Windows Forms Developer’s Guide 147
Copyright © GrapeCity, Inc. All rights reserved.
UsingaShortcut
1. SettheCountpropertyfortheAlternatingRowsshortcutobject.2. SetthevariousappearanceandotherpropertiesoftheAlternatingRowsshortcutobject,suchastheBackColorandForeColorproperties.
3. CreateadditionalalternatingrowappearancesbysettingpropertiesforadditionalAlternatingRowsshortcutobjects,increasingtheindexforeachappearanceyoucreate.
Example
Thisexamplecodecreatesasheetthathasthreedifferentappearancesettingsforrows.Thefirstrowusesthedefaultappearance.Thesecondrowhasalightbluebackgroundwithnavytext,andthethirdrowhasalightyellowbackgroundwithnavytext.Thispatternrepeatsforallsubsequentrows.
C#fpSpread1.Sheets[0].AlternatingRows.Count = 3;fpSpread1.Sheets[0].AlternatingRows[0].BackColor = Color.RoyalBlue;fpSpread1.Sheets[0].AlternatingRows[0].ForeColor = Color.Navy;fpSpread1.Sheets[0].AlternatingRows[1].BackColor = Color.LightYellow;fpSpread1.Sheets[0].AlternatingRows[1].ForeColor = Color.Navy;fpSpread1.Sheets[0].AlternatingRows[2].BackColor = Color.Salmon;fpSpread1.Sheets[0].AlternatingRows[2].ForeColor = Color.Navy;
VBFpSpread1.Sheets(0).AlternatingRows.Count = 3FpSpread1.Sheets(0).AlternatingRows(0).BackColor = Color.RoyalBlueFpSpread1.Sheets(0).AlternatingRows(0).ForeColor = Color.NavyFpSpread1.Sheets(0).AlternatingRows(1).BackColor = Color.LightYellowFpSpread1.Sheets(0).AlternatingRows(1).ForeColor = Color.NavyFpSpread1.Sheets(0).AlternatingRows(2).BackColor = Color.SalmonFpSpread1.Sheets(0).AlternatingRows(2).ForeColor = Color.Navy
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosetthealternatingrows.2. Fromthepropertylistforthatsheet,intheAppearancecategory,selecttheAlternatingRowsproperty.3. Ifyouwanttoaddadditionalalternatingrowspatterns,settheCountpropertytothenumberofpatternsyou
want.4. ClicktheAlternatingRowsbuttontodisplaytheAlternatingRowCollectionEditorasshowninthe
followingfigure.
Spread Windows Forms Developer’s Guide 148
Copyright © GrapeCity, Inc. All rights reserved.
5. Selectalternatingrowpatternforwhichtosetproperties.6. Setpropertiesfortheselectedpatternusingthepropertylist.7. ClickOKtoclosetheAlternatingRowCollectionEditor.8. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing the Appearance of Headers
Youcancustomizetheappearanceofheadercells.Thesetasksrelatetosettingtheappearanceofheadersforrowsorcolumnsinthesheet:
CustomizingtheDefaultHeaderLabelsCustomizingHeaderLabelTextCustomizingtheStyleofHeaderCellsAddingaGradienttoHeaderCellsCustomizingtheHeaderGridLinesSettingtheHeightorWidthofHeaderCellsCreatingaSpaninaHeader
Youcanalsocustomizeheaderappearanceinotherways.
Youcansetthestartingnumberforthedefaultheaderlabels.Ifyouhavemultiplerowsinthecolumnheaders,youcanselectwhichrowdisplaysthesortindicatorandwhichrowdisplaystheautomatictext.Youcanshowarowselectoriconfortheselectedrow(ShowRowSelector('ShowRowSelectorProperty'intheon-linedocumentation)).
Theappearanceoftheheadercellisdeterminedalsobythestate,whetheritisselected(active)ornot(normal),asshowninthefigurebelow.
Spread Windows Forms Developer’s Guide 149
Copyright © GrapeCity, Inc. All rights reserved.
Forinformationontheappearanceofthesheetcorner,refertoCustomizingtheSheetCornerAppearanceFormoreinformationoncell-levelpropertiesofheadercells,refertotheCell('CellClass'intheon-linedocumentation)andCells('CellsClass'intheon-linedocumentation)objects.Formoreinformationonthepaintingoftheheadercells,refertotheColumnHeaderRenderer('ColumnHeaderRendererClass'intheon-linedocumentation)classandRowHeaderRenderer('RowHeaderRendererClass'intheon-linedocumentation)class.
Customizing the Default Header Labels
BydefaulttheSpreadcomponentdisplayssequentiallettersinthebottomrowofthecolumnheaderandsequentiallyincreasingnumbersintheright-mostcolumnoftherowheader.Ifyoursheetdisplaysmultiplecolumnheaderrowsorrowheadercolumns,youcanspecifywhichcolumnorrowdisplaysthesedefaultlabels.
Inthefollowingfigure,thecolumnheadersshownumbersinsteadoflettersandthelabelsareshowninthesecondrowinsteadofthebottomrow.Youcanalsochoosenottodisplaythedefaultlabels.
Youcanalsosetthenumber(orletter)atwhichtostartthesequentialnumbering(orlettering)ofthelabelsusingapropertyofthesheet.UsetheStartingColumnNumber('StartingColumnNumberProperty'intheon-linedocumentation)propertyorStartingRowNumber('StartingRowNumberProperty'intheon-linedocumentation)propertyoftheSheetView('SheetViewClass'intheon-linedocumentation)objecttosetthenumberorletterdisplayedinthefirstcolumnheaderorfirstrowheaderrespectivelyonthesheet.Thestarting
Spread Windows Forms Developer’s Guide 150
Copyright © GrapeCity, Inc. All rights reserved.
numberorletterisusedonlyfordisplaypurposesandhasnoeffectontheactualrowandcolumncoordinates.
Note:Thevalueofastartingnumberorletterisaninteger,soiftheheaderdisplayslettersandsetthestartingletterto10,thefirstheadercellcontainstheletterJ.
Formoreinformation,refertotheseAPImembers:
RowHeader('RowHeaderClass'intheon-linedocumentation)classAutoText('AutoTextProperty'intheon-linedocumentation)andAutoTextIndex('AutoTextIndexProperty'intheon-linedocumentation)propertiesColumnHeader('ColumnHeaderClass'intheon-linedocumentation)classAutoText('AutoTextProperty'intheon-linedocumentation)andAutoTextIndex('AutoTextIndexProperty'intheon-linedocumentation)propertiesSheetView('SheetViewClass'intheon-linedocumentation)classRowHeaderAutoText('RowHeaderAutoTextProperty'intheon-linedocumentation)andRowHeaderAutoTextIndex('RowHeaderAutoTextIndexProperty'intheon-linedocumentation)propertiesSheetView('SheetViewClass'intheon-linedocumentation)classColumnHeaderAutoText('ColumnHeaderAutoTextProperty'intheon-linedocumentation)andColumnHeaderAutoTextIndex('ColumnHeaderAutoTextIndexProperty'intheon-linedocumentation)propertiesHeaderAutoText('HeaderAutoTextEnumeration'intheon-linedocumentation)enumeration
Youcanalsochoosetodisplaycustomtextintheheadersinsteadoforinadditiontotheautomaticlabeltext.Forinstructions,seeCustomizingHeaderLabelText.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. Clickthesheetforwhichyouwanttochangetheheaderlabels.5. Tochangetheheaderlabelsdisplayed,changethesettingoftheColumnHeaderAutoTextorRowHeaderAutoTextproperty.
6. Tochangetheroworcolumnintheheaderinwhichthelabelisdisplayed,changethesettingoftheColumnHeaderAutoTextIndexorRowHeaderAutoTextIndexproperty.
7. ClickOKtoclosetheeditor.
UsingaShortcut
1. Tochangethesettingsforthecolumnheader,settheSheetobject'sColumnHeaderAutoText('ColumnHeaderAutoTextProperty'intheon-linedocumentation)andColumnHeaderAutoTextIndex('ColumnHeaderAutoTextIndexProperty'intheon-linedocumentation)properties.
2. Tochangethesettingsfortherowheader,settheSheetobject'sRowHeaderAutoText('RowHeaderAutoTextProperty'intheon-linedocumentation)andRowHeaderAutoTextIndex('RowHeaderAutoTextIndexProperty'intheon-linedocumentation)properties.
Example
Thisexamplecodesetsthecolumnheadertodisplaynumbersinsteadofletters.
C#// Set the column header to display numbers instead of letters.fpSpread1.Sheets[0].ColumnHeader.RowCount = 3;
Spread Windows Forms Developer’s Guide 151
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.Sheets[0].ColumnHeaderAutoTextIndex = 1;fpSpread1.Sheets[0].ColumnHeaderAutoText = FarPoint.Win.Spread.HeaderAutoText.Numbers;fpSpread1.Sheets[0].RowHeaderAutoText = FarPoint.Win.Spread.HeaderAutoText.Letters;
VB' Set the column header to display numbers instead of letters.FpSpread1.Sheets(0).ColumnHeader.RowCount = 3FpSpread1.Sheets(0).ColumnHeaderAutoTextIndex = 1FpSpread1.Sheets(0).ColumnHeaderAutoText = FarPoint.Win.Spread.HeaderAutoText.NumbersFpSpread1.Sheets(0).RowHeaderAutoText = FarPoint.Win.Spread.HeaderAutoText.Letters
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttomodifytheheaderlabel(automatictext)settings.2. Inthepropertieslist,intheAppearancecategory,double-clicktheColumnHeaderorRowHeaderproperty
todisplaythepropertiesforthecolumnorrowheader.3. ChangethesettingsoftheAutoTextandAutoTextIndexpropertiestospecifytheheaderlabeltodisplayand
whichcolumnorrowintheheadershoulddisplaytheautomatictext.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing Header Label Text
BydefaulttheSpreadcomponentdisplayslettersinthecolumnheadersandnumbersintherowheaders.Besidesthisautomatictext,youcanaddlabelstoanyoralloftheheadercells.Youcanaddcustomizetheheaderlabeltext,asshowninthefollowingfigurewherethefirstfourcolumnshavecustomlabels.
Tospecifythecustomtextforaheaderlabel,youcanusetheLabelpropertyoftheColumnHeader.ColumnorRowHeader.RowshortcutobjectsoryoucanusetheText('TextProperty'intheon-linedocumentation)propertyoftheCellsshortcutobjects.Forheaderswithmultiplecolumnsandmultiplerows,youusetheTextpropertyoftheCellsshortcutobjects.RefertotheexampleinCreatingaHeaderwithMultipleRowsorColumns.Formoreinformationontheindividualproperties,refertotheLabel('LabelProperty'intheon-linedocumentation)propertyintheColumn('ColumnClass'intheon-linedocumentation)classortheLabel('LabelProperty'intheon-linedocumentation)propertyintheRow('RowClass'intheon-linedocumentation)class.
Cellsintheheadersareseparatefromthecellsinthedataarea,sothecoordinatesforcellsintheheadersstartat0,0andcountupfromupperlefttolowerrightwithintheheader.Thesheetcornercellisseparateandisnotcountedwhen
Spread Windows Forms Developer’s Guide 152
Copyright © GrapeCity, Inc. All rights reserved.
specifyingheadercellcoordinates.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. Clickthesheetforwhichyouwanttochangetheheaderlabels.
YoucannotaddorchangecustomtextincellsotherthanchangingthelabelsdisplayedwhenusingthePropertieswindow.
5. Inthepropertylist,selecttheCellspropertyandclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecolumnforwhichyouwanttochangethelabelsdisplayedtocustomtext.7. SettheLabelpropertytosetthecustomtext.8. ClickOKtoclosetheCell,Column,andRowEditor.9. ClickOKtoclosetheSheetViewCollectionEditor.
UsingaShortcut
Ifyouwanttochangethetextinaheadercellordisplaytextinacell,settheTextpropertyfortheColumnHeader’sCellobjecttothecustomtextyouwanttodisplay.Ifyouwanttosetthetextformultipleheadercells,calltheColumnHeader’sSetClip('SetClipMethod'intheon-linedocumentation)orSetClipValue('SetClipValueMethod'intheon-linedocumentation)methods.Ifyouwanttochangethelabelsdisplayed,settheLabelpropertyfortheColumnHeader’sColumnobjecttothecustomtextyouwanttodisplay.
Example
Thisexamplecodesetscustomtextforthelabelsinthefirstfourcolumnheaders.
C#// Set custom text for columns A through D.fpSpread1.Sheets[0].ColumnHeader.Columns[0].Label = "North";fpSpread1.Sheets[0].ColumnHeader.Columns[1].Label = "South";fpSpread1.Sheets[0].ColumnHeader.Columns[2].Label = "East";fpSpread1.Sheets[0].ColumnHeader.Columns[3].Label = "West";
VB' Set custom text for columns A through D.FpSpread1.Sheets(0).ColumnHeader.Columns(0).Label = "North"FpSpread1.Sheets(0).ColumnHeader.Columns(1).Label = "South"FpSpread1.Sheets(0).ColumnHeader.Columns(2).Label = "East"FpSpread1.Sheets(0).ColumnHeader.Columns(3).Label = "West"
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosetcustomheadertext.2. Selecttheroworcolumnforwhichyouwanttosetcustomheadertext,thenright-clickandchooseHeaders.3. IntheHeaderEditor,double-clicktheheaderforwhichyouwanttodisplaycustomtext.
Ifthereisonlyoneheaderroworcolumn,clicktheonedisplayedcellwiththetext"<Default>".
4. Editthetexttobethecustomtextyouwant,andthenpressEntertostopediting.
Spread Windows Forms Developer’s Guide 153
Copyright © GrapeCity, Inc. All rights reserved.
5. Whenyouhaveeditedalltheheadertextyouwanttoedit,clickOKtoclosetheHeaderEditor,thenclickYestoapplyyourchangestotheselection.
6. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing the Style of Header Cells
Youcancustomizethestyleofheadercellsifyouwanttochangethedefaultappearance.Youcansetorcustomizemanyfeatures,including:
stylepropertiesoftheheaderclassesmembersoftherendererspropertiesofthedefaultheaderclasses
Tocustomizestylepropertiesfortheheaderclasses,setthedefaultstyleoftheheadercellsbysettingtheRowHeader('RowHeaderClass'intheon-linedocumentation)DefaultStyle('DefaultStyleProperty'intheon-linedocumentation)propertyortheColumnHeader('ColumnHeaderClass'intheon-linedocumentation)DefaultStyle('DefaultStyleProperty'intheon-linedocumentation)property.Formoreinformationonwhatcanbeset,refertotheStyleInfo('StyleInfoClass'intheon-linedocumentation)objectandtheRowHeader('RowHeaderClass'intheon-linedocumentation)andColumnHeader('ColumnHeaderClass'intheon-linedocumentation)objects.
Before
After
Tocustomizeusingtherenderers,settheirmemberstocustomizetheappearanceofheaders.TherenderersusedintheOffice2013orOffice2016styleareshownandlistedinthefollowingfigure.
Spread Windows Forms Developer’s Guide 154
Copyright © GrapeCity, Inc. All rights reserved.
YoucanalsousedefaultclassestocustomizemanyoftheheaderappearancepropertiesbysettingthepropertiesoftheColumns.DefaultColumn('Columns.DefaultColumnClass'intheon-linedocumentation)classandtheRows.DefaultRow('Rows.DefaultRowClass'intheon-linedocumentation)class.
Youcanalsosetthegridlinesaroundtheheadercellstochangethethree-dimensionalappearance.RefertoCustomizingtheHeaderGridLines.
Youcanalsoaddgradientstotheheadercells.RefertoAddingaGradienttoHeaderCells.
UsingaShortcut
1. Tochangethestyleforthecolumnheader,defineastyleandthensettheColumnHeaderobjectDefaultStyle('DefaultStyleProperty'intheon-linedocumentation)property.
2. Tochangethesettingsfortherowheader,defineastyleandthensettheRowHeaderobjectDefaultStyle('DefaultStyleProperty'intheon-linedocumentation)property.
Example
Thisexamplecodedefinesastylewithnewcolorsandappliesittothecolumnheaderasshowninthefigureinthistopic.
C#fpSpread1.VisualStyles = FarPoint.Win.VisualStyles.Off;// Define a new style.FarPoint.Win.Spread.StyleInfo darkstyle = new FarPoint.Win.Spread.StyleInfo();darkstyle.BackColor = Color.Teal;
Spread Windows Forms Developer’s Guide 155
Copyright © GrapeCity, Inc. All rights reserved.
darkstyle.ForeColor = Color.Yellow;// Apply the new style to the column header of a sheet.fpSpread1.ActiveSheet.ColumnHeader.DefaultStyle = darkstyle;
VBFpSpread1.VisualStyles = FarPoint.Win.VisualStyles.Off' Define a new style.Dim darkstyle As New FarPoint.Win.Spread.StyleInfo()darkstyle.BackColor = Color.Tealdarkstyle.ForeColor = Color.Yellow' Apply the new style to the column header of a sheet.FpSpread1.ActiveSheet.ColumnHeader.DefaultStyle = darkstyle
Adding a Gradient to Header Cells
Youcanchangetheappearanceofheadercellsbyaddingacolorgradient.Youcanhaveagradientfromonecolortoanothercolor.
Youcanimplementagradientappearancebycreatingacustomclassthatinheritsexistingcellclasses(ageneralcell,inthiscase)andchangethedisplaytoagradient.YoucanalsousetheGradientHeaderRenderer('GradientHeaderRendererClass'intheon-linedocumentation)class.
UsingaShortcut
UsetheGradientHeaderRenderer('GradientHeaderRendererClass'intheon-linedocumentation)classandtheRenderer('RendererProperty'intheon-linedocumentation)propertyforthecolumnheaderrowandrowheadercolumn.
Example
Thisexamplesetsagradientfortheheadersandthesheetcorner.
C#
Spread Windows Forms Developer’s Guide 156
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Spread.CellType.GradientHeaderRenderer gr = new FarPoint.Win.Spread.CellType.GradientHeaderRenderer(Color.Yellow,Color.Orange, Color.YellowGreen, Color.Bisque,Drawing2D.LinearGradientMode.ForwardDiagonal);FpSpread1.ActiveSheet.ColumnHeader.Rows[0].Renderer = gr;FpSpread1.ActiveSheet.RowHeader.Columns[0].Renderer = gr;FpSpread1.ActiveSheet.SheetCorner.DefaultStyle.Renderer = gr;
VBDim gr As New FarPoint.Win.Spread.CellType.GradientHeaderRenderer(Color.Yellow, Color.Orange, Color.YellowGreen, Color.Bisque, Drawing2D.LinearGradientMode.ForwardDiagonal)FpSpread1.ActiveSheet.ColumnHeader.Rows(0).Renderer = grFpSpread1.ActiveSheet.RowHeader.Columns(0).Renderer = grFpSpread1.ActiveSheet.SheetCorner.DefaultStyle.Renderer = gr
Customizing the Header Grid Lines
Youcanspecifythegridlinesforaheaderinwayssimilartosettingthegridlinesforasheet.Formoreinformationongridlines,refertoDisplayingGridLinesonaSheet.Inthefollowingfigure,therowheadergridlinesarethree-dimensionalwithredhuesandthecolumnheadergridlinesarethree-dimensionalwithbluehues.
Youcanspecifythehorizontalgridlinesseparatelyfromtheverticalgridlines.Youcanspecifythecolumnheadergridlinesseparatelyfromtherowheadergridlines.
Incode,youcancustomizethegridlinesinaheadereitherintheroworcolumnheaderclassesorintheSheetView('SheetViewClass'intheon-linedocumentation)class.Youcanuseanyofthefollowing:
RowHeader('RowHeaderClass'intheon-linedocumentation)class,HorizontalGridLine('HorizontalGridLineProperty'intheon-linedocumentation)propertyRowHeader('RowHeaderClass'intheon-linedocumentation)class,VerticalGridLine('VerticalGridLineProperty'intheon-linedocumentation)propertyColumnHeader('ColumnHeaderClass'intheon-linedocumentation)classHorizontalGridLine('HorizontalGridLineProperty'intheon-linedocumentation)propertyColumnHeader('ColumnHeaderClass'intheon-linedocumentation)class,VerticalGridLine('VerticalGridLineProperty'intheon-linedocumentation)propertySheetView('SheetViewClass'intheon-linedocumentation)class
Spread Windows Forms Developer’s Guide 157
Copyright © GrapeCity, Inc. All rights reserved.
RowHeaderHorizontalGridLine('RowHeaderHorizontalGridLineProperty'intheon-linedocumentation)propertySheetView('SheetViewClass'intheon-linedocumentation)classRowHeaderVerticalGridLine('RowHeaderVerticalGridLineProperty'intheon-linedocumentation)propertySheetView('SheetViewClass'intheon-linedocumentation)classColumnHeaderHorizontalGridLine('ColumnHeaderHorizontalGridLineProperty'intheon-linedocumentation)propertySheetView('SheetViewClass'intheon-linedocumentation)classColumnHeaderVerticalGridLine('ColumnHeaderVerticalGridLineProperty'intheon-linedocumentation)propertyGridLine('GridLineClass'intheon-linedocumentation)class
Youcanalsosettheheaderstonotshowanygridlines,asshowninthefollowingfigure,bysettingthegridlinetypetoNone.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheparticularsheetfromtheselectiondrop-downlist.2. AnotherwaytoselectthesheetistoselecttheSpreadcomponent,selecttheSheetsproperty,andclickthe
buttontodisplaytheSheetViewCollectionEditor,andintheMemberslist,selectthesheet.3. Tosettherowheader(orcolumnheader)horizontalgridlinecolororverticalgridlinecolor,
a. SelecttheRowHeaderobject(orColumnHeaderobject)inthepropertylist,andexpandthelistofpropertiesunderthatobject.
b. SelecttheHorizontalGridLinepropertyortheVerticalGridLineproperty,andexpandthelistofpropertiesunderthatobject.
c. Ifyouwanttodisplaythree-dimensionalgridlines,settheTypepropertytoLoweredorRaised.d. Ifthegridlinesarenotthree-dimensional,selecttheColorproperty,andthenclickthedrop-downbutton
todisplaythecolorpicker.Selectacolorinthecolorpicker.Ifthegridlinesarethree-dimensional,selecttheHighlightColorproperty,andthenclickthedrop-downbuttontodisplaythecolorpicker.Selectacolorinthecolorpicker.DothesamefortheShadowColorproperty.
4. IfyouselectedthesheetusingtheSheetsEditor,clickOKtoclosetheeditor.
UsingCode
1. CreateaGridLine('GridLineClass'intheon-linedocumentation)object,settingthecolororcolorsand
Spread Windows Forms Developer’s Guide 158
Copyright © GrapeCity, Inc. All rights reserved.
thestyleforthegridlineintheconstructor.2. AssigntheGridLine('GridLineClass'intheon-linedocumentation)objecttothespecifiedheaderby
settingtheRowHeader('RowHeaderClass'intheon-linedocumentation)object(orColumnHeader('ColumnHeaderClass'intheon-linedocumentation)object)HorizontalGridLine('HorizontalGridLineProperty'intheon-linedocumentation)orVerticalGridLine('VerticalGridLineProperty'intheon-linedocumentation)propertytotheGridLine('GridLineClass'intheon-linedocumentation)objectyoucreatedinstep1.
3. YoucanalternativelyassigntheGridLine('GridLineClass'intheon-linedocumentation)objecttotheRowHeaderHorizontalGridLine('RowHeaderHorizontalGridLineProperty'intheon-linedocumentation),RowHeaderVerticalGridLine('RowHeaderVerticalGridLineProperty'intheon-linedocumentation),ColumnHeaderHorizontalGridLine('ColumnHeaderHorizontalGridLineProperty'intheon-linedocumentation),orColumnHeaderVerticalGridLine('ColumnHeaderVerticalGridLineProperty'intheon-linedocumentation)propertiesintheSheetViewobject.
Example
Thisexamplecodesetstherowheadergridlinestobethree-dimensionalwithredhuesandthecolumnheadergridlinestobethree-dimensionalwithbluehuesasshownintheprecedingfigure.
C#fpSpread1.Sheets[0].VisualStyles = FarPoint.Win.VisualStyles.Off;fpSpread1.ActiveSheet.ColumnHeader.DefaultStyle.Renderer = new FarPoint.Win.Spread.CellType.ColumnHeaderRenderer();fpSpread1.ActiveSheet.RowHeader.DefaultStyle.Renderer = new FarPoint.Win.Spread.CellType.RowHeaderRenderer();FarPoint.Win.Spread.GridLine rgdln = new FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.Raised, Color.Purple, Color.Red, Color.Orange);FarPoint.Win.Spread.GridLine cgdln = new FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.Raised, Color.Purple, Color.Blue, Color.LightBlue);fpSpread1.Sheets[0].ColumnHeader.RowCount = 3;fpSpread1.Sheets[0].RowHeader.ColumnCount = 2;fpSpread1.Sheets[0].ColumnHeader.HorizontalGridLine = cgdln;fpSpread1.Sheets[0].RowHeader.HorizontalGridLine = rgdln;fpSpread1.Sheets[0].ColumnHeader.VerticalGridLine = cgdln;fpSpread1.Sheets[0].RowHeader.VerticalGridLine = rgdln;
VBFpSpread1.Sheets(0).VisualStyles = FarPoint.Win.VisualStyles.OffFpSpread1.ActiveSheet.ColumnHeader.DefaultStyle.Renderer = New FarPoint.Win.Spread.CellType.ColumnHeaderRendererFpSpread1.ActiveSheet.RowHeader.DefaultStyle.Renderer = New FarPoint.Win.Spread.CellType.RowHeaderRendererDim rgdln As New FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.Raised, Color.Purple, Color.Red, Color.Orange)Dim cgdln As New FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.Raised, Color.Purple, Color.Blue, Color.LightBlue)FpSpread1.Sheets(0).ColumnHeader.RowCount = 3FpSpread1.Sheets(0).RowHeader.ColumnCount = 2FpSpread1.Sheets(0).ColumnHeader.HorizontalGridLine = cgdlnFpSpread1.Sheets(0).RowHeader.HorizontalGridLine = rgdlnFpSpread1.Sheets(0).ColumnHeader.VerticalGridLine = cgdlnFpSpread1.Sheets(0).RowHeader.VerticalGridLine = rgdln
Spread Windows Forms Developer’s Guide 159
Copyright © GrapeCity, Inc. All rights reserved.
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosetthegridlinecolors.Youcanselectthesheetfromthedrop-downlistorselectthesheetcornerorselecttheSpreadcomponent,thenselecttheSheetspropertyanddisplaytheSheetsEditor.
2. Tosettherowheader(orcolumnheader)horizontalgridlinecolororverticalgridlinecolor,a. IntheAppearancecategory,selecttheRowHeaderHorizontalGridLineorRowHeaderVerticalGridLineobject(orColumnHeaderHorizontalGridLineorColumHeaderVerticalGridLineobject)inthepropertylist,andexpandthelistofproperties.
b. Ifyouwanttodisplaythree-dimensionalgridlines,settheTypepropertytoLoweredorRaised.c. Ifthegridlinesarenotthree-dimensional,selecttheColorproperty,andthenclickthedrop-downbuttontodisplaythecolorpicker.Selectacolorinthecolorpicker.
d. Ifthegridlinesarethree-dimensional,selecttheHighlightColorproperty,andthenclickthedrop-downbuttontodisplaythecolorpicker.Selectacolorinthecolorpicker.DothesamefortheShadowColorproperty.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting the Height or Width of Header Cells
Youcancustomizetheappearanceofheadercellsbychangingtherowheightorcolumnwidth,orboth,inanyoftherowsorcolumnsofheaders.
YoucanchangethesizebyaccessingpropertiesintheRowHeader('RowHeaderClass'intheon-linedocumentation)classfortherowheaderortheColumnHeader('ColumnHeaderClass'intheon-linedocumentation)classforthecolumnheaderorboth.
UsingCode
UsetheHeight('HeightProperty'intheon-linedocumentation)propertyintheColumnHeader('ColumnHeaderClass'intheon-linedocumentation)classandtheWidth('WidthProperty'intheon-linedocumentation)propertyintheRowHeader('RowHeaderClass'intheon-linedocumentation)class.
Example
Thisexamplesetsthecolumnheaderheightandrowheaderwidth.
Spread Windows Forms Developer’s Guide 160
Copyright © GrapeCity, Inc. All rights reserved.
C#private void Form1_Load(object sender, System.EventArgs e){ // Change the column header height to 90 pixels. fpSpread1.ActiveSheet.ColumnHeader.Rows[0].Height = 90; // Change the row header width to 80 pixels. fpSpread1.ActiveSheet.RowHeader.Columns[0].Width = 80; }
VBPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Change the column header height to 90 pixels. FpSpread1.ActiveSheet.ColumnHeader.Rows(0).Height = 90 ' Change the row header width to 80 pixels. FpSpread1.ActiveSheet.RowHeader.Columns(0).Width = 80End Sub
Creating a Span in a Header
Youcancreatecellspansinaheader,forexample,tomakeaheaderformultiplecolumnsorrows,orboth,asshowninthefigurebelow.
Youcancreatecellspansineitherthecolumnheadersorrowheadersorboth.Formorebackgroundaboutcreatingcellspans,refertoCreatingaSpanofCells.
Usethesemethodswhencreatingaspaninaheader:
AddColumnHeaderSpanCell('AddColumnHeaderSpanCellMethod'intheon-linedocumentation)AddRowHeaderSpanCell('AddRowHeaderSpanCellMethod'intheon-linedocumentation)
YoucanspecifyhowtheheaderspansareselectedwiththeCellSpanSelectionPolicy('CellSpanSelectionPolicyProperty'intheon-linedocumentation)property.
Spread Windows Forms Developer’s Guide 161
Copyright © GrapeCity, Inc. All rights reserved.
Forinformationoncreatingmultiplerowsinthecolumnheadersormultiplecolumnsintherowheaders,refertoCreatingaHeaderwithMultipleRowsorColumns.
Youcancustomizethelabelsintheseheaders.Forinstructionsforcustomizingthelabels,seeCustomizingHeaderLabelText.
UsingaShortcut
CalltheSheetsobjectAddColumnHeaderSpanCell('AddColumnHeaderSpanCellMethod'intheon-linedocumentation)orAddRowHeaderSpanCell('AddRowHeaderSpanCellMethod'intheon-linedocumentation)method.
Example
Thisexamplecodesetsthefirstcellinthecolumnheadertospanacrosstwocolumns.
C#// Set the number of rows in the column header.FpSpread1.ActiveSheet.ColumnHeader.RowCount = 3;// Set the number of columns in the row header.FpSpread1.ActiveSheet.RowHeader.ColumnCount = 2;// Define the labels for the spanned column header cells.FpSpread1.ActiveSheet.ColumnHeader.Cells[2, 0].Text = "East";FpSpread1.ActiveSheet.ColumnHeader.Cells[2, 1].Text = "West";FpSpread1.ActiveSheet.ColumnHeader.Cells[2, 2].Text = "East";FpSpread1.ActiveSheet.ColumnHeader.Cells[2, 3].Text = "West";FpSpread1.ActiveSheet.ColumnHeader.Cells[2, 4].Text = "East";FpSpread1.ActiveSheet.ColumnHeader.Cells[2, 5].Text = "West";FpSpread1.ActiveSheet.ColumnHeader.Cells[2, 6].Text = "East";FpSpread1.ActiveSheet.ColumnHeader.Cells[2, 7].Text = "West";FpSpread1.ActiveSheet.ColumnHeader.Cells[1, 0].Text = "1st Quarter";FpSpread1.ActiveSheet.ColumnHeader.Cells[1, 2].Text = "2nd Quarter";FpSpread1.ActiveSheet.ColumnHeader.Cells[1, 4].Text = "3rd Quarter";FpSpread1.ActiveSheet.ColumnHeader.Cells[1, 6].Text = "4th Quarter";FpSpread1.ActiveSheet.ColumnHeader.Cells[0, 0].Text = "Fiscal Year 2004";// Define the column header cell spans.FpSpread1.ActiveSheet.AddColumnHeaderSpanCell(1, 0, 1, 2);FpSpread1.ActiveSheet.AddColumnHeaderSpanCell(1, 2, 1, 2);FpSpread1.ActiveSheet.AddColumnHeaderSpanCell(1, 4, 1, 2);FpSpread1.ActiveSheet.AddColumnHeaderSpanCell(1, 6, 1, 2);FpSpread1.ActiveSheet.AddColumnHeaderSpanCell(0, 0, 1, 8);// Define the label for the spanned row header cells.FpSpread1.ActiveSheet.RowHeader.Cells[0,0].Text ="Branch #";// Define the row header cell span.FpSpread1.ActiveSheet.AddRowHeaderSpanCell(0, 0, 12, 1);
VB' Set the number of rows in the column header.FpSpread1.ActiveSheet.ColumnHeader.RowCount = 3' Set the number of columns in the row header.FpSpread1.ActiveSheet.RowHeader.ColumnCount = 2' Define the labels for the spanned column header cells.FpSpread1.ActiveSheet.ColumnHeader.Cells(2, 0).Text = "East"FpSpread1.ActiveSheet.ColumnHeader.Cells(2, 1).Text = "West"FpSpread1.ActiveSheet.ColumnHeader.Cells(2, 2).Text = "East"
Spread Windows Forms Developer’s Guide 162
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.ActiveSheet.ColumnHeader.Cells(2, 3).Text = "West"FpSpread1.ActiveSheet.ColumnHeader.Cells(2, 4).Text = "East"FpSpread1.ActiveSheet.ColumnHeader.Cells(2, 5).Text = "West"FpSpread1.ActiveSheet.ColumnHeader.Cells(2, 6).Text = "East"FpSpread1.ActiveSheet.ColumnHeader.Cells(2, 7).Text = "West"FpSpread1.ActiveSheet.ColumnHeader.Cells(1, 0).Text = "1st Quarter"FpSpread1.ActiveSheet.ColumnHeader.Cells(1, 2).Text = "2nd Quarter"FpSpread1.ActiveSheet.ColumnHeader.Cells(1, 4).Text = "3rd Quarter"FpSpread1.ActiveSheet.ColumnHeader.Cells(1, 6).Text = "4th Quarter"FpSpread1.ActiveSheet.ColumnHeader.Cells(0, 0).Text = "Fiscal Year 2004"' Define the column header cell spans.FpSpread1.ActiveSheet.AddColumnHeaderSpanCell(1, 0, 1, 2)FpSpread1.ActiveSheet.AddColumnHeaderSpanCell(1, 2, 1, 2)FpSpread1.ActiveSheet.AddColumnHeaderSpanCell(1, 4, 1, 2)FpSpread1.ActiveSheet.AddColumnHeaderSpanCell(1, 6, 1, 2)FpSpread1.ActiveSheet.AddColumnHeaderSpanCell(0, 0, 1, 8)' Define the label for the spanned row header cells.FpSpread1.ActiveSheet.RowHeader.Cells(0,0).Text ="Branch #"' Define the row header cell span.FpSpread1.ActiveSheet.AddRowHeaderSpanCell(0, 0, 12, 1)
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttospanheadercells.2. Selecttheroworcolumnforwhichyouwanttosetcustomheadertext,thenright-clickandchooseHeaders.3. IntheHeaderEditor,clicktheleft-mostheadercellinthesetofcellsforwhichyouwanttocreateaspan.4. Inthepropertylistforthatheadercell,settheColumnSpanorRowSpanpropertytothenumberofcellsto
spanstartingfromtheselectedheadercell.5. ClickOKtoclosetheHeaderEditor.6. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing the Appearance of a Cell
Whenyouworkwithcellsinthedataareaofthespreadsheet,youcanworkwiththeobjectsusingtheshortcutsincode(Cell('CellClass'intheon-linedocumentation)andCells('CellsClass'intheon-linedocumentation)classes)oryoucanworkdirectlywiththemodel.Mostdeveloperswhoarenotcreatingextensivecustomizationsfinditeasiertoworkwiththeshortcutobjects.
Thesetasksrelatetosettingtheappearanceofindividualcellsinthedataareaofthespreadsheet:
ColoringaCellSettingaBackgroundImagetoaCellAligningCellContentsResizingaCelltoFittheDataResizingtheDatatoFittheCellCustomizingCellBordersCreatingaSpanofCellsAllowingCellstoMergeAutomaticallyAllowingCellDatatoOverflowCreatingandApplyingaStyleforCellsUsingSparklines
Spread Windows Forms Developer’s Guide 163
Copyright © GrapeCity, Inc. All rights reserved.
Note:Theword"appearance"describesthegenerallookofthecell,notthesettingsintheAppearanceclass,whichcontainsonlyafewsettingsandisusedfortheappearanceofseveralpartsoftheinterface.MostoftheappearancesettingsforacellareintheStyleInfo('StyleInfoClass'intheon-linedocumentation)class.
Settingsappliedtoaparticularcelloverridethesettingsthataresetatthecolumnorrowlevel.Foramoredetailedexplanation,refertoObjectParentage.
Othercell-levelappearancesettingsaresetbythecelltype.Formoreinformationonsettingsrelatedtocelltypes,refertoCustomizingInteractionwithCellTypes.YoucaneditpropertiesoftheCellsclassesinthePropertieswindow(inSpreadDesignerorinVisualStudio.NET).FormoreinformationontheCells,Columns,andRowsEditorthatisavailablefromthePropertieswindow,refertotheexplanationofthiseditorintheSpreadDesignerGuide(on-linedocumentation).
Formoreinformation,refertothefollowingtopics:
Forinformationonheadercells,refertoCustomizingtheAppearanceofHeaders.Fortasksthatrelatetosettingtheuserinteractionatthecelllevel,refertoCustomizingInteractioninCells.ForinformationoncustomizingtheappearanceofcellsusingtheSpreadDesigner,refertotheSpreadDesignerGuide(on-linedocumentation).FormoreinformationontheCellandCellsobjects,refertotheAssemblyReference(on-linedocumentation).
Coloring a Cell
Youcansetthebackgroundandforeground(text)colorsforacellorforagroupofcells.Anexampleofthedifferentwaystosetthecolorsforacellisshowninthefollowingfigure.Thecodethatcreatedthesecellcolorsisprovidedintheexample.
YoucanspecifythebackgroundcolorforacellincodebyusingtheBackColor('BackColorProperty'intheon-linedocumentation)propertyforthatcell.YoucanspecifythetextcolorincodebyusingtheForeColor('ForeColorProperty'intheon-linedocumentation)property.
YoucanalsospecifythecolorstodisplaywhenthecellsareselectedusingSelectionBackColor('SelectionBackColorProperty'intheon-linedocumentation)andSelectionForeColor('SelectionForeColorProperty'intheon-linedocumentation)forthesheet.Formoreinformationonselections,refertoCustomizingtheSelectionAppearance.
Youcanalsospecifyadifferentcolor(forbackgroundorfortext)inlockedcellsusingtheLockBackColor('LockBackColorProperty'intheon-linedocumentation)andLockForeColor('LockForeColorProperty'intheon-linedocumentation)propertiesoftheSheetVieworAppearanceobjects.Formoreinformationonlockedcells,refertoLockingaCell.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.
Spread Windows Forms Developer’s Guide 164
Copyright © GrapeCity, Inc. All rights reserved.
4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertieslist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecolor.7. Inthepropertieslist,selecttheBackColorpropertyandselectacolorfromtheCustom,Web,orSystemtab.SelecttheForeColorpropertyandselectthatcolor.
8. ClickOKtoclosetheCell,Column,andRowEditor.9. ClickOKtoclosetheSheetViewCollectionEditor.
UsingaShortcut
SettheBackColor('BackColorProperty'intheon-linedocumentation)propertyortheForeColor('ForeColorProperty'intheon-linedocumentation)propertyfortheCellsobject.
Example
Thisexamplecodesetsthebackgroundcolorandtextcolorforthesecondcell,setsthecolorsforlockedcells,andsetsthecolorsforselections.
C#fpSpread1.ActiveSheet.Cells[0,1].Value = "This is default.";fpSpread1.ActiveSheet.Cells[1,1].Value = "This is custom.";fpSpread1.ActiveSheet.Cells[2,1].Value = "This is locked.";fpSpread1.ActiveSheet.Cells[3,1].Value = "This is selected.";fpSpread1.ActiveSheet.Cells[1,1].BackColor = Color.LimeGreen;fpSpread1.ActiveSheet.Cells[1,1].ForeColor = Color.Yellow;fpSpread1.ActiveSheet.Cells[2,1].Locked = true;fpSpread1.ActiveSheet.Protect = true;fpSpread1.ActiveSheet.LockBackColor = Color.Brown;fpSpread1.ActiveSheet.LockForeColor = Color.Orange;
fpSpread1.ActiveSheet.SelectionStyle = FarPoint.Win.Spread.SelectionStyles.SelectionColors;fpSpread1.ActiveSheet.SelectionPolicy = FarPoint.Win.Spread.Model.SelectionPolicy.Range;fpSpread1.ActiveSheet.SelectionUnit = FarPoint.Win.Spread.Model.SelectionUnit.Cell;fpSpread1.ActiveSheet.SelectionBackColor = Color.Pink;fpSpread1.ActiveSheet.SelectionForeColor = Color.Red;
VBFpSpread1.ActiveSheet.Cells(0,1).Value = "This is default."FpSpread1.ActiveSheet.Cells(1,1).Value = "This is custom."FpSpread1.ActiveSheet.Cells(2,1).Value = "This is locked."FpSpread1.ActiveSheet.Cells(3,1).Value = "This is selected."FpSpread1.ActiveSheet.Cells(1,1).BackColor = Color.LimeGreenFpSpread1.ActiveSheet.Cells(1,1).ForeColor = Color.YellowFpSpread1.ActiveSheet.Cells(2,1).Locked = TrueFpSpread1.ActiveSheet.Protect = TrueFpSpread1.ActiveSheet.LockBackColor = Color.BrownFpSpread1.ActiveSheet.LockForeColor = Color.Orange
FpSpread1.ActiveSheet.SelectionStyle = FarPoint.Win.Spread.SelectionStyles.SelectionColorsFpSpread1.ActiveSheet.SelectionPolicy = FarPoint.Win.Spread.Model.SelectionPolicy.Range
Spread Windows Forms Developer’s Guide 165
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.ActiveSheet.SelectionUnit = FarPoint.Win.Spread.Model.SelectionUnit.CellFpSpread1.ActiveSheet.SelectionBackColor = Color.PinkFpSpread1.ActiveSheet.SelectionForeColor = Color.Red
UsingCode
SettheBackColor('BackColorProperty'intheon-linedocumentation)propertyortheForeColor('ForeColorProperty'intheon-linedocumentation)propertyforaCell('CellClass'intheon-linedocumentation)object.
Example
ThisexamplecodesetsthebackgroundcolorforcellA1toAzureandtheforegroundcolortoNavy,thensetsthebackgroundcolorforcellsC3throughD4toBisque.
C#FarPoint.Win.Spread.Cell cellA1;cellA1 = fpSpread1.ActiveSheet.Cells[0, 0];cellA1.BackColor = Color.Azure;cellA1.ForeColor = Color.Navy;FarPoint.Win.Spread.Cell cellrange;cellrange = fpSpread1.ActiveSheet.Cells[2,2,3,3];cellrange.BackColor = Color.Bisque;
VBDim cellA1 As FarPoint.Win.Spread.CellcellA1 = FpSpread1.ActiveSheet.Cells(0, 0)cellA1.BackColor = Color.AzurecellA1.ForeColor = Color.NavyDim cellrange As FarPoint.Win.Spread.Cellcellrange = FpSpread1.ActiveSheet.Cells(2, 2, 3, 3)cellrange.BackColor = Color.Bisque
UsingtheSpreadDesigner
1. Intheworkarea,selectthecellorcellsforwhichyouwanttosetthebackgroundcolor.2. Inthepropertieslist(intheMisccategory),selecttheBackColorpropertytosetthebackgroundcolor.3. Clickthedrop-downbuttontodisplaythecolorpickerandchoosethecolorfromtheavailablecolors.4. Tosetthetextcolor,repeatthosestepsandselectForeColorpropertyinthepropertieslist.5. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Background Image to a Cell
Youcancustomizethebackgroundofacellbyaddingagraphicimage.
Spread Windows Forms Developer’s Guide 166
Copyright © GrapeCity, Inc. All rights reserved.
Formoreinformationonimagecelltypes,refertoSettinganImageCell.
Formoreinformationonsettinganimageforallthecellsinasheet(aspartofthedefaultstyle)refertoSettingaBackgroundImageforaSheet.
Example
Thefollowingexampleaddsanimagetoatextcell.
C#private void Form1_Load(object sender, System.EventArgs e){// Create an instance of a text cell.FarPoint.Win.Spread.CellType.TextCellType t = new FarPoint.Win.Spread.CellType.TextCellType();// Load an image file and set it to BackgroundImage property.FarPoint.Win.Picture p = new FarPoint.Win.Picture(Image.FromFile("D:\\images\\lionstatue.jpg"), FarPoint.Win.RenderStyle.Stretch);t.BackgroundImage = p;// Apply the text cell.fpSpread1.ActiveSheet.Cells[1, 1].CellType = t;// Set the size of the cell so the image is displayedfpSpread1.ActiveSheet.Rows[1].Height = 50;fpSpread1.ActiveSheet.Columns[1].Width = 150;}
VBPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Create an instance of a text cell. Dim t As New FarPoint.Win.Spread.CellType.TextCellType ' Load an image file and set it to BackgroundImage property. Dim p As New FarPoint.Win.Picture(Image.FromFile("D:\\images\\lionstatue.jpg"), FarPoint.Win.RenderStyle.Stretch) t.BackgroundImage = p ' Apply the text cell. FpSpread1.ActiveSheet.Cells(1, 1).CellType = t ' Set the size of the cell so the image is displayed
Spread Windows Forms Developer’s Guide 167
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.ActiveSheet.Rows(1).Height = 50 FpSpread1.ActiveSheet.Columns(1).Width = 150End Sub
Aligning Cell Contents
Youcandeterminehowthecontentsarealignedinacellorinagroupofcells.Incode,simplysettheHorizontalAlignment('HorizontalAlignmentProperty'intheon-linedocumentation)propertyandtheVerticalAlignment('VerticalAlignmentProperty'intheon-linedocumentation)properties,andmakeuseoftheCellHorizontalAlignment('CellHorizontalAlignmentEnumeration'intheon-linedocumentation)andCellVerticalAlignment('CellVerticalAlignmentEnumeration'intheon-linedocumentation)enumerations.IntheSpreadDesigner,setthosepropertiesaccordingly.Thefollowingfigureshowstheresultofthecodeinthefirstexample.
ThereareadditionalpropertiesintheCell('CellClass'intheon-linedocumentation)classsuchasTextIndent('TextIndentProperty'intheon-linedocumentation)andCellPadding('CellPaddingProperty'intheon-linedocumentation)thatcanbeusedtocreateextramarginsaroundcelltext.
Foranexplanationofhowthealignmentaffectstheoverflowofdata,refertoAllowingCellDatatoOverflow
YoucankeepthecellalignmentwheneditingwiththeAllowEditorVerticalAlign('AllowEditorVerticalAlignProperty'intheon-linedocumentation)property.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertieslist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthealignment.7. Inthepropertieslist,selecttheHorizontalAlignmentpropertyandchoosethealignment.8. Tosettheverticalalignment,selecttheVerticalAlignmentpropertyinthepropertieslistandchoosethe
alignment.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingaShortcut
SettheHorizontalAlignment('HorizontalAlignmentProperty'intheon-linedocumentation)propertyand
Spread Windows Forms Developer’s Guide 168
Copyright © GrapeCity, Inc. All rights reserved.
theVerticalAlignment('VerticalAlignmentProperty'intheon-linedocumentation)propertiesfortheCellsshortcutobject.
Example
Thisexamplecodesetsthehorizontalalignmentofthefirstcell(A1)toberight-aligned,theverticalalignmentofthatcelltobebottom-aligned,andthehorizontalalignmentandverticalalignmentofcellsfromB2toC3tobecentered.Theprecedingfigureillustratestheresults.
C#fpSpread1.Sheets[0].Cells[0,0].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Right;fpSpread1.Sheets[0].Cells[0,0].VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Bottom;fpSpread1.Sheets[0].Cells[1,1,2,2].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;fpSpread1.Sheets[0].Cells[1,1,2,2].VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;
VBFpSpread1.Sheets(0).Cells(0,0).HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.RightFpSpread1.Sheets(0).Cells(0,0).VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.BottomFpSpread1.Sheets(0).Cells(1,1,2,2).HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.CenterfpSpread1.Sheets(0).Cells(1,1,2,2).VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center
UsingCode
SettheHorizontalAlignment('HorizontalAlignmentProperty'intheon-linedocumentation)propertyandtheVerticalAlignment('VerticalAlignmentProperty'intheon-linedocumentation)propertiesfortheCell('CellClass'intheon-linedocumentation)object.
Example
Thisexamplecodesetsthehorizontalalignmentforaspecificcellandtheverticalalignmentforarangeofcells.
C#FarPoint.Win.Spread.Cell cellA1;cellA1 = fpSpread1.ActiveSheet.Cells[0, 0];cellA1.HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Right;cellA1.VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Bottom; FarPoint.Win.Spread.Cell cellrange;cellrange = fpSpread1.ActiveSheet.Cells[1,1,2,2];cellrange.HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;cellrange.VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;
VBDim cellA1 As FarPoint.Win.Spread.CellcellA1 = FpSpread1.ActiveSheet.Cells(0, 0)cellA1.HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Right
Spread Windows Forms Developer’s Guide 169
Copyright © GrapeCity, Inc. All rights reserved.
cellA1.VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Bottom Dim cellrange As FarPoint.Win.Spread.Cellcellrange = FpSpread1.ActiveSheet.Cells(1, 1, 2, 2)cellrange.HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Centercellrange.VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center
UsingtheSpreadDesigner
1. Intheworkarea,selectthecellorcellsforwhichyouwanttosetthehorizontalalignmentofthecellcontents.2. Inthepropertieslist(intheMisccategory),selecttheHorizontalAlignmentproperty.3. Clickthedrop-downbuttontodisplaythechoicesandchoosethealignment.4. Repeatthesestepsandinthepropertieslist,selectVerticalAlignmenttosettheverticalalignmentofthecell
orcells.5. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Resizing a Cell to Fit the Data
Youcanresizethecellbasedonthelengthofthedatainthecell.Thesizeofthecellwiththelargestdataiscalledthepreferredsize.
TheSheetViewGetPreferredCellSize('GetPreferredCellSizeMethod'intheon-linedocumentation)methodretrievesthepreferredsizeofthespecifiedcell.
Thisfigureshowstheresultoftheexamplecodethatresizesthecolumnbasedonthetextinthecellsofthatcolumn.
Somecelltypesignorethesizeparameterwhileothercelltypesusethesizeparameter.Forexample,asinglelinetextcelltypeignoresthesizeparameterwhileaword-wrappingmultiple-linetextcelltypeusesthesizeparameter'swidthpropertytodeterminelinebreaks.Basically,thesizeparameter'swidth(orheight)isusedindeterminingwrappingbreaksforhorizontal(orvertical)content.Thesheet'sGetPreferredRowHeight('GetPreferredRowHeightMethod'intheon-linedocumentation)methodpassesthecell'scurrentsizetothecellrenderer'sGetPreferredSizemethodsanditassumesthatyouwantmultiple-linetextcellstoexpandverticallyusingthecell'scurrentwidth.Formoreinformationonhowcelltypesdisplaydata,refertoUnderstandingHowCellTypesDisplayandFormatData.
BesidesgettingtheheightforarowwiththeGetPreferredRowHeight('GetPreferredRowHeightMethod'intheon-linedocumentation)method,youcangetawidthforacolumnusingtheGetPreferredColumnWidth('GetPreferredColumnWidthMethod'intheon-linedocumentation)method.
Forinformationonsettinganentireroworcolumnofcellsbasedonthesizeofthedata,refertoResizingtheRoworColumntoFittheData.
UsingCode
Setthewidthofthecelltothevalueofthepreferredsizetoshowtheentirecontentsofthecell.
Example
Aftersettingthetextinthecontents,resizethecolumnwidthofthecelltomatchthemaximumsizeofthecell.
C#System.Drawing.Size sz;
Spread Windows Forms Developer’s Guide 170
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.ActiveSheet.SetValue(0, 0, "Expand the cell to fit the text.");sz = fpSpread1.ActiveSheet.GetPreferredCellSize(0,0);fpSpread1.ActiveSheet.Columns[0].Width = sz.Width;MessageBox.Show("The width of the cell is " + sz.Width.ToString());
VBDim sz As System.Drawing.SizefpSpread1.ActiveSheet.SetValue(0, 0, "Expand the cell to fit the text.")sz = fpSpread1.ActiveSheet.GetPreferredCellSize(0, 0)fpSpread1.ActiveSheet.Columns(0).Width = sz.WidthMessageBox.Show("The width of the editor is " & sz.Width.ToString())
Resizing the Data to Fit the Cell
Youcandisplayallthetextinthecellwiththeshrinktofitoption.Thefontsizeisreducedifthetextistoolongforthevisibleareaofthecell.
Thispropertyisavailableforthecurrency,datetime,mask,number,percent,regularexpression,text,orgeneralcell.
ThefollowingimageshowsthedifferencebetweenacellwiththeShrinkToFit('ShrinkToFitProperty'intheon-linedocumentation)propertysettoTrueandacellwiththepropertysettoFalse.
UsingCode
1. Createacellthatsupportstheshrinktofitoptionsuchastheregularexpressioncell.2. SettheShrinkToFitproperty.3. SettheCellTypeproperty.4. Typeavalidvalueforthecellsuchas11240082777fortheregularexpressioncellinthisexample.
Example
Thisexamplereducesthefontsizesothetextisdisplayedinthecell.
C#FarPoint.Win.Spread.CellType.RegularExpressionCellType testcell = new FarPoint.Win.Spread.CellType.RegularExpressionCellType();testcell.ShrinkToFit = true;testcell.RegularExpression = "^\\d{11}$";fpSpread1.Sheets[0].Cells[0, 0].CellType = testcell;
VB
Spread Windows Forms Developer’s Guide 171
Copyright © GrapeCity, Inc. All rights reserved.
Dim testcell As New FarPoint.Win.Spread.CellType.RegularExpressionCellType()testcell.ShrinkToFit = Truetestcell.RegularExpression = "^\d{11}$"FpSpread1.Sheets(0).Cells(0, 0).CellType = testcell
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosethecelltype.3. ExpandtheCellTypepropertyandsettheShrinkToFitpropertytoTrue.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing Cell Borders
Youcancustomizetheappearanceofcellsbysettingbordersforacellorrangeofcells.
Tasksthatrelatetocustomizingcellbordersinclude:
CreatingandCustomizingCellBordersCreatingBorderswithDiagonalLinesCreatingaComplexBorderwithMultipleLines
Creating and Customizing Cell Borders
Youcancustomizetheappearanceofthecellsbysettingbordersforacellorrangeofcells.Bordersaresetonlyforcells;youcansetaborderforacolumn,row,sheet,orrangeofcells,buttheeffectisthesameasassigningthesameborderobjecttoeachindividualcellinthecolumn,row,sheet,orrangeofcells.Forarangeofcells,thesameborderobjectisusedbyeachcell.Abordercanbedisplayedontheleft,right,top,orbottom,oraroundallfoursidesofacellorcellrange.Abordercanbedisplayedasanyofthebuilt-instylesshowninthefollowingtableorcustomizedbordersthatyoudefine.Bydefault,noborderisdisplayed.Tosettheborder,usetheCellBorder('BorderProperty'intheon-linedocumentation)property,ColumnBorder('BorderProperty'intheon-linedocumentation)property,orRowBorder('BorderProperty'intheon-linedocumentation)property.
IntheSheetView('SheetViewClass'intheon-linedocumentation)class,thereistheSetOutlineBorder('SetOutlineBorderMethod'intheon-linedocumentation)methodthathastheeffectofsettingaborderaroundtheoutsideofarangeofcells.Actually,itsetsindividualbordersineachcellintheperimeteroftherangetoachievethiseffect.Fortheinsidebordersofthatrange,thereistheSetInsideBorder('SetInsideBorderMethod'intheon-linedocumentation)methodforsettingthebordersinside.
Youcanspecifymorethanonestyleandcolorforthesamecell,column,row,orblockofcells.Thecellbordersaredrawnfromlefttorightandtoptobottominthesheet.Iftwoadjacentbordershaveadifferentstyleorcolor,thelastonedrawnhasprecedenceandistheonethatisdisplayed.Cellbordersreflecttheprecedenceusedbythesheettodeterminethecharacteristicsforsheetelements.Thatis,cellsettingsoverriderow,column,andsheetsettings,inthatorder.Formoreinformation,seethelistofprecedenceinthedescriptionofObjectParentage.
ForinformationoncustomizingbordersusingtheSpreadDesigner,refertothedescriptionoftheBorderEditor(on-linedocumentation)intheSpreadDesignerGuide.
BorderDisplay
ThecellbordersoftheleftandtopedgesarepainteddependingonthesettingoftheBorderCollapse('BorderCollapseProperty'intheon-linedocumentation)property.WhenBorderCollapseissettoSeparate,(whichisthedefault)theleftandtopedgesofthecellborderarepaintedjustinsidethegridlines.Thus,theleftandtopcellborderedgesaredisplayedintheleftandtoprows.WhenBorderCollapseissettoCollapse,theleftandtopedgesofthecellborderarepaintedoverthegridlinestotheleftandtopofthecell.
Spread Windows Forms Developer’s Guide 172
Copyright © GrapeCity, Inc. All rights reserved.
Theleftcolumnandtoprow(ofaviewport,rowheader,columnheader,orsheetcorner)arepositionedsothatthosegridlinesarejustoutsideoftheviewableareaandthusthosecellborderedgesarejustoutsideoftheviewablearea(thatis,thosecellborderedgesarenotdisplayed).KeepthisinmindifyouchoosenottodisplayaborderfortheSpreadcomponentorheadersforthesheet,astheresultmightbevisuallyconfusing.Therightandbottomedgesofthecellborderarealwayspaintedoverthegridlinestotherightandbottomofthecell,regardlessoftheBorderCollapsesetting.Formoreinformation,seetheOverlappingBorderssectioninthistopic.
BorderStyles
Thetablebelowsummarizesthedifferentcellborderstyles.
Style Example Description FarPoint.WinClassName
Beveled Hasthree-dimensionalappearanceifthehighlightandshadowaresettodifferentcolors.
BevelBorder('BevelBorderClass'intheon-linedocumentation)
Complex Eachsideofthecellcandisplayadifferentcolorandtypeofborder,withborderpatternssuchasdashedordotted.(SeeCreatingaComplexBorderwithMultipleLines.)
ComplexBorder('ComplexBorderClass'intheon-linedocumentation)
Compound Hastwobeveledborders,whichcanbeseparatedbyaframe
CompoundBorder('CompoundBorderClass'intheon-linedocumentation)
Double-line
Hastwoparallellines. DoubleLineBorder('DoubleLineBorderClass'intheon-linedocumentation)
Single-lineborder
Hasasimple,singleline. LineBorder('LineBorderClass'intheon-linedocumentation)
Rounded-edge,single-line
Hasasinglelinebutthecornersarerounded. RoundedLineBorder('RoundedLineBorderClass'intheon-linedocumentation)
Differentborderstylesletyousetdifferentoptions.Forexample,thecomplexborderletsyousetdifferentstylesofborderdisplayforeachsideofthecell.TheComplexBorder('ComplexBorderClass'intheon-linedocumentation)classalsoallowsyoutocreatediagonalborderlines.Intheexampleshownabove,thetopandbottombordersaredashedbordersandhaveadifferentcolorfromtheleftandrightborders.Foreachoftheseborderstyles,youcanturnoffthedisplayoftheborderonanysideofthecell.
OverlappingBorders
Cellbordersareappliedaroundtheedgeofeachcell,andcanoverlapothercellbordersbutdonotdosobydefault.Thefollowingfigureshowstwosetsofcells.Inthefirstset,thecellbordersdonotoverlap,andareseparate.Inthesecondset,thecellbordersoverlap.
Borders ExampleAppearanceSeparateborders(notcollapsed)
Spread Windows Forms Developer’s Guide 173
Copyright © GrapeCity, Inc. All rights reserved.
Collapsedborders(overlapping)
WhetherbordersoverlapisdeterminedbythesettingoftheBorderCollapse('BorderCollapseProperty'intheon-linedocumentation)propertyoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class.Iftwoadjacentcellshavedifferentsettings,andthepropertyissettohavethecellbordersoverlap,thecellthatistotherightortothebottomhasprecedence.Keepinmindthatthesheetisdrawnfromlefttorightandfromtoptobottomonthescreen.Eachsubsequentcell'sborderpropertiestakeprecedenceoverthecelldrawnbeforeit.
Cellbordersonlyoverlaptheamountofthegridlinewidth.Therefore,iftwo3pixelbordersoverlap,andthegridlineis1pixel,theoverlappedbordersare5pixelswide.
DifferentfromGridLines
Bordersaredifferentfromgridlinesinthattheycreateaborderaroundacellorrangeofcellsratherthandistinguishingrowsandcolumns.Bordersaredrawnoverthegridlines.
Ifyoudisplaycellbordersforallthecellsinasheet,youmightwanttoturnoffthegridlinedisplaybysettingthegridlinetypeoftheHorizontalGridLine('HorizontalGridLineProperty'intheon-linedocumentation)andVerticalGridLine('VerticalGridLineProperty'intheon-linedocumentation)propertiesofthesheettoNone.FormoreinformationongridlinesrefertoDisplayingGridLinesonaSheet.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. Clickthesheetforwhichyouwanttosetcellborders.5. SelecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.6. Selectthecellorcellsforwhichyouwanttosettheborder.7. Inthepropertylist,settheBorderproperty.8. Ifyouwanttocustomizetheborderyouhaveset,double-clicktheBorderpropertytodisplaytheborder
propertiesfortheborderstyleyouhaveselected.9. Settheborderpropertiesforyourborder.10. ClickOKtoclosetheCell,Column,andRowEditor.11. ClickOKtoclosetheSheetViewCollectionEditor.
UsingaShortcut
1. Createanewborderobjectofthetypeofborderyouwanttocreate(BevelBorder,ComplexBorder,andsoon).2. SettheCellsshortcutobjectBorderpropertytothenewborderobjectyoucreated.
Example
Thisexamplecodecreatesabevelborderandthensetsacell’sbordertobethebevelborder.
C#// Create the bevel border.FarPoint.Win.BevelBorder bevelbrdr = new FarPoint.Win.BevelBorder(FarPoint.Win.BevelBorderType.Raised, Color.Cyan, Color.DarkCyan);// Set the bevel border to the cell B3 border.fpSpread1.Sheets[0].Cells[4, 3].Border = bevelbrdr;
Spread Windows Forms Developer’s Guide 174
Copyright © GrapeCity, Inc. All rights reserved.
VB' Create the bevel border.Dim bevelbrdr As New FarPoint.Win.BevelBorder(FarPoint.Win.BevelBorderType.Raised, Color.Cyan, Color.DarkCyan)' Set the bevel border to the cell B3 border.FpSpread1.Sheets(0).Cells(4, 3).Border = bevelbrdr
UsingCode
1. Createanewborderobjectofthetypeofborderyouwanttocreate(BevelBorder('BevelBorderClass'intheon-linedocumentation),ComplexBorder('ComplexBorderClass'intheon-linedocumentation),andsoon).
2. CreateanewSheetView('SheetViewClass'intheon-linedocumentation)object.3. SettheBorder('BorderProperty'intheon-linedocumentation)propertyforacell(orroworcolumn)
objectequaltotheborderobjectyoucreated.4. AssigntheSheetView('SheetViewClass'intheon-linedocumentation)objecttoasheetinthe
component.
Example
Thisexamplecodecreatesabevelborderandthensetsacell’sbordertobethebevelborder.
C#// Create a new bevel border.FarPoint.Win.BevelBorder bevelbrdr = new FarPoint.Win.BevelBorder(FarPoint.Win.BevelBorderType.Raised, Color.Cyan, Color.DarkCyan);// Create a new SheetView object.FarPoint.Win.Spread.SheetView newsheet=new FarPoint.Win.Spread.SheetView();// Set a cell's border to be the bevel border.newsheet.Cells[4, 3].Border = bevelbrdr;// Assign the SheetView object to the first sheet.fpSpread1.Sheets[0] = newsheet;
VB' Create a new bevel border.Dim bevelbrdr As New FarPoint.Win.BevelBorder(FarPoint.Win.BevelBorderType.Raised, Color.Cyan, Color.DarkCyan)' Create a new SheetView object.Dim newsheet As New FarPoint.Win.Spread.SheetView()' Set a cell's border to be the bevel border.newsheet.Cells(4, 3).Border = bevelbrdr' Assign the SheetView object to the first sheet.FpSpread1.Sheets(0) = newsheet
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosetacellborder.2. Selectthecellorrangeofcellsforwhichyouwanttosettheborder.3. Right-clickandselectBorders,orinthepropertylist(intheMisccategory),settheBorderproperty.4. Ifyouwanttocustomizetheborderyouhaveset,double-clicktheBorderpropertytodisplaytheborder
Spread Windows Forms Developer’s Guide 175
Copyright © GrapeCity, Inc. All rights reserved.
propertiesfortheborderstyleyouhaveselected.5. Settheborderpropertiesforyourborder.6. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Creating Borders with Diagonal Lines
Youcancreatecellborderswithdiagonallinesasshowninthefollowingimage.
Youcanalsodisplaythediagonallinesinacellborderthatispartofashapeasdisplayedinthefollowingimage.
Thecellmusthaveaborderandthetextorientationmustnotbezero.TheEnableDiagonalLine('EnableDiagonalLineProperty'intheon-linedocumentation)propertyshouldalsobesettotrue.
TheComplexBorder('ComplexBorderClass'intheon-linedocumentation)classalsoallowsyoutocreatediagonalborderlinesinthecell.
UsingCode
Spread Windows Forms Developer’s Guide 176
Copyright © GrapeCity, Inc. All rights reserved.
1. Createatextcell.2. SettheTextOrientation('TextOrientationProperty'intheon-linedocumentation)property.3. SettheTextRotationAngle('TextRotationAngleProperty'intheon-linedocumentation)property.
Example
Thisexamplecodecreatesatextcellwithadiagonalborder.
C#fpSpread1.Sheets[0].Cells[1, 3].Text = "Test"; //Cell has to have valuefpSpread1.Sheets[0].Cells[1, 3].Border = new FarPoint.Win.ComplexBorder(new FarPoint.Win.ComplexBorderSide(Color.Red, 2));// Cell has to have border
FarPoint.Win.Spread.CellType.TextCellType cellType = new FarPoint.Win.Spread.CellType.TextCellType();cellType.TextOrientation = FarPoint.Win.TextOrientation.TextRotateCustom;cellType.TextRotationAngle = 60; // Cell has to have rotation angle to see the effect.fpSpread1.Sheets[0].Cells[1, 3].CellType = cellType;fpSpread1.Sheets[0].EnableDiagonalLine = true;
VBFpSpread1.Sheets(0).Cells(1, 3).Text = "Test" 'Cell has to have valueFpSpread1.Sheets(0).Cells(1, 3).Border = New FarPoint.Win.ComplexBorder(New FarPoint.Win.ComplexBorderSide(Color.Red, 2)) ' Cell has to have border
Dim cellType As New FarPoint.Win.Spread.CellType.TextCellType()cellType.TextOrientation = FarPoint.Win.TextOrientation.TextRotateCustomcellType.TextRotationAngle = 60 ' Cell has to have rotation angle to see the effect.FpSpread1.Sheets(0).Cells(1, 3).CellType = cellTypeFpSpread1.Sheets(0).EnableDiagonalLine = True
Example
Thisexamplecodecreatesatextcellwithadiagonalborderandashapethatcontainsthecell.
C#fpSpread1.Sheets[0].Cells[1, 3].Text = "Test"; //Cell has to have valuefpSpread1.Sheets[0].Cells[1, 3].Border = new FarPoint.Win.ComplexBorder(new FarPoint.Win.ComplexBorderSide(Color.Red, 2));// Cell has to have border
FarPoint.Win.Spread.CellType.TextCellType cellType = new FarPoint.Win.Spread.CellType.TextCellType();cellType.TextOrientation = FarPoint.Win.TextOrientation.TextRotateCustom;cellType.TextRotationAngle = 60; // Cell has to have rotation angle to see the effect.fpSpread1.Sheets[0].Cells[1, 3].CellType = cellType;
FarPoint.Win.Spread.DrawingSpace.TriangleShape a = new FarPoint.Win.Spread.DrawingSpace.TriangleShape();a.BackColor = Color.Blue;fpSpread1.ActiveSheet.AddShape(a, 1, 1);FarPoint.Win.Spread.DrawingSpace.SpreadCameraShape test = new FarPoint.Win.Spread.DrawingSpace.SpreadCameraShape();test.Formula = "B1:E6";
Spread Windows Forms Developer’s Guide 177
Copyright © GrapeCity, Inc. All rights reserved.
test.Location = new System.Drawing.Point(20, 20);fpSpread1.Sheets[0].AddShape(test);fpSpread1.Sheets[0].EnableDiagonalLine = true;
VBFpSpread1.Sheets(0).Cells(1, 3).Text = "Test" 'Cell has to have valueFpSpread1.Sheets(0).Cells(1, 3).Border = New FarPoint.Win.ComplexBorder(New FarPoint.Win.ComplexBorderSide(Color.Red, 2)) ' Cell has to have border
Dim cellType As New FarPoint.Win.Spread.CellType.TextCellType()cellType.TextOrientation = FarPoint.Win.TextOrientation.TextRotateCustomcellType.TextRotationAngle = 60 ' Cell has to have rotation angle to see the effect.FpSpread1.Sheets(0).Cells(1, 3).CellType = cellType
Dim a As New FarPoint.Win.Spread.DrawingSpace.TriangleShape()a.BackColor = Color.BlueFpSpread1.ActiveSheet.AddShape(a, 1, 1)Dim test As New FarPoint.Win.Spread.DrawingSpace.SpreadCameraShape()test.Formula = "B1:E6"test.Location = New System.Drawing.Point(20, 20)FpSpread1.Sheets(0).AddShape(test)FpSpread1.Sheets(0).EnableDiagonalLine = True
Creating a Complex Border with Multiple Lines
Youcancreateacellborderwithmultiplelinesusingthecomplexborder.
UsingCode
UsetheCompoundArraypropertyoftheComplexBorderSide('ComplexBorderSideClass'intheon-linedocumentation)classtocreatemultiple-linebordersforacell.
Reviewthefollowingexamplesformoreinformation.
Example
ThisexamplecodecreatesaComplexBorderSidethathastwounderlines(twolineswithablankspaceinbetween)eachtakingathirdofthewidthofthepen.
Spread Windows Forms Developer’s Guide 178
Copyright © GrapeCity, Inc. All rights reserved.
C#// Create a new complex border side with two lines.FarPoint.Win.ComplexBorderSide bottomborder = new FarPoint.Win.ComplexBorderSide(true, Color.Black, 3, System.Drawing.Drawing2D.DashStyle.Solid, null, new Single[] {0f, 0.33f, 0.66f, 1f});fpSpread1.Sheets[0].Cells[3, 7].Border = new FarPoint.Win.ComplexBorder(null, null, null, bottomborder);
VB' Create a new complex border side with two lines.Dim bottomborder As New FarPoint.Win.ComplexBorderSide(Color.Black, 3, System.Drawing.Drawing2D.DashStyle.Solid, Nothing, New Single() {0, 0.33, 0.66, 1})FpSpread1.Sheets(0).Cells(3, 7).Border = New FarPoint.Win.ComplexBorder(Nothing, Nothing, Nothing, bottomborder)
Example
ThisexamplecodecreatesaComplexBorderSidethathasthreelineswithvaryingamountsofthicknessandwithsomeblankspaceoneitheredgeofthepen.
Spread Windows Forms Developer’s Guide 179
Copyright © GrapeCity, Inc. All rights reserved.
C#// Create a new complex border side with three lines.FarPoint.Win.ComplexBorderSide bottomborder = new FarPoint.Win.ComplexBorderSide(true, Color.Black, 3, System.Drawing.Drawing2D.DashStyle.Solid, null, new Single[] {0.1f, 0.2f, 0.3f, 0.6f, 0.7f, 0.9f});fpSpread1.Sheets[0].Cells[3, 7].Border = new FarPoint.Win.ComplexBorder(null, null, null, bottomborder);
VB' Create a new complex border side with three lines.Dim bottomborder As New FarPoint.Win.ComplexBorderSide(True, Color.Black, 3, System.Drawing.Drawing2D.DashStyle.Solid, Nothing, New Single() {0.1, 0.2, 0.3, 0.6, 0.7, 0.9})FpSpread1.Sheets(0).Cells(3, 7).Border = New FarPoint.Win.ComplexBorder(Nothing, Nothing, Nothing, bottomborder)
Creating a Span of Cells
Youcancombinecellstocreateaspanofcells,asshowninthefigurebelow.Creatingaspanofcellscreatesonelargecellwheretherehadpreviouslybeenseveral.Forexample,ifyoucreateaspanofcellsfromcellB2tocellD3,cellB2thenappearstooccupythespacefromcellB2throughcellD3.
Thecomponentisdividedintofourparts:sheetcorner,columnheaders,rowsheaders,anddataarea.Youcancreatespanswithinapart,butyoucannotcreateaspanthatgoesacrossparts.Forexample,youcannotspancellsinthedataareawithcellsintherowheadersandyoucannotspancellsinthecolumnheaderwiththesheetcorner.Thistopicdiscussesspanningcellsinthedataarea.Formoreinformationoncreatingaspanofheadercells,refertoCreatingaSpaninaHeader.
Spread Windows Forms Developer’s Guide 180
Copyright © GrapeCity, Inc. All rights reserved.
Whenyoucreateaspanofcells,thedatainthefirstcellinthespan(theanchorcell)occupiesallthespaceinthespan.Whenyoucreateaspan,thedatathatwasineachofthecellsinthespanisstillineachcell,butnotdisplayed.Thedataissimplyhiddenbythespanrange.Ifyouremovethespanfromagroupofcells,thecontentofthespannedcells,whichpreviouslywashidden,isdisplayedasappropriate.CreateaspanofcellsbycallingtheAddSpanCell('AddSpanCellMethod'intheon-linedocumentation)method.Thecelltypesofthecellscombinedinthespanarenotchanged.Thespannedcelltakesthetypeoftheleft-mostcellinthespan.
YoucanreturnwhetheraspecifiedcellisinaspanofcellswiththeGetSpanCell('GetSpanCellMethod'intheon-linedocumentation)method.
YoucanremoveaspanfromarangeofcellsbycallingtheRemoveSpanCell('RemoveSpanCellMethod'intheon-linedocumentation)method.Youcanremoveaspanrangebycallingthismethod,specifyingtheanchorcellofthespanrangetoremovetherange.Whenyouremoveaspanrange,thedatathatwaspreviouslyineachofthecellsinthespanisre-displayedinthecell.Thedatawasneverremovedfromthecell,butsimplyhiddenbythespanrange.
Note:Spansthatareaddedtoasortedsheetarenotshown,andspanswillbehiddenwhenthesheetoranypartofitissortedwithanysortmethodotherthanSortRange('SortRangeMethod'intheon-linedocumentation).CellrangesthatcontainspanscannotbesortedwithSortRange('SortRangeMethod'intheon-linedocumentation).
Whateverpropertiesyousetontheanchorcellareappliedtothecellspan.Thisincludessettingacellnote,too.Ifyousetacellnotetooneofthecellsinthespanthatisnottheanchor,thecellnoteisnotdisplayed.
CalltheGetSpanCellmethodtoreturnwhetheracellisinaspanofcells,andifitisinaspanofcells,itreturnstheCellRange('CellRangeClass'intheon-linedocumentation)objectthatcontainsthecolumnandrownumberoftheanchorcellandthenumberofcolumnsandrowsinthespanrange.ThismethodiscalledforthecurrentlyselectedsheetunlessyoufirstsettheSheetsobjecttospecifythesheetwithwhichtowork.
Ifamergedcolumnoverlapsaspan,thenthemergedcolumnreplacesthespan.Itisrecommendedthatyoudonotmergecellsthatarepartofaspan.Formoreinformationonautomaticallymergingcellswithidenticalcontent,refertoAllowingCellstoMergeAutomatically.
Forinformationontheunderlyingmodelforspans,refertoUnderstandingtheSpanModel.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. InthePropertieswindowontherightsideoftheSheetViewCollectionEditor,selecttheCellspropertyfor
thesheet.5. ClickthebuttontodisplaytheCell,Column,andRowEditor.6. Intheeditor,selecteithertheRowSpanorColumnSpanpropertyandsetthenumbertothenumberofcells
tospanstartingfromtheselectedcell.Toremoveaspan,setthevaluebackto1.Thepreviewontheleftsideoftheeditorshowsthecellsspanned.
7. Ifyouwanttoapplythischange,clickApply.8. ClickOKtocloseeacheditor.
UsingaShortcut
Tospancells(orremovespanning)useanyofthefollowingmembers:
AddSpanCell,GetSpanCell,andRemoveSpanCellAddColumnHeaderSpanandAddRowHeaderSpan
Formoreinformationonthesepropertiesandmethods,refertotheSheetView('SheetViewClass'intheon-linedocumentation)class.
Spread Windows Forms Developer’s Guide 181
Copyright © GrapeCity, Inc. All rights reserved.
CalltheSheetsobjectAddSpanCellmethodtospanthecells.
Example
Thisexamplecodedefinessomecontentthenspanssixadjoiningcells.
C#// Create some content in two cells.fpSpread1.ActiveSheet.Cells[1,1].Text = "These six cells are spanned.";fpSpread1.ActiveSheet.Cells[2,2].Text = "This is text in 2,2.";// Span six cells including the ones with different content.fpSpread1.ActiveSheet.AddSpanCell(1, 1, 2, 3);
VB' Create some content in two cells.fpSpread1.ActiveSheet.Cells(1,1).Text = "These six cells are spanned."fpSpread1.ActiveSheet.Cells(2,2).Text = "This is text in 2,2."' Span six cells including the ones with different content.fpSpread1.ActiveSheet.AddSpanCell(1, 1, 2, 3)
UsingtheSpreadDesigner
1. Onthespreadsheet,selectthecellstospan.2. Right-clickandselectSpanorinthepropertylist(intheMisccategory),selecteithertheRowSpanorColumnSpanpropertyandsetthenumbertoavaluegreaterthan1tospancells.Toremoveaspan,setthevaluebackto1.TheDesignershowsthecellsspanned.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Allowing Cells to Merge Automatically
YoucanhaveSpreadautomaticallymergecellsbetweencolumnsorbetweenrowsifthecellshavethesamevaluebasedonthepolicythatyouset.Thecomponentcanautomaticallycombinecellsthathavethesamecontents.Youmightwanttodothis,forexample,whenboundtoadatabase,asshowninthefigurebelowwherethecellsintheYearcolumnmergewheretheyearvalueisthesame,aswith1995and2003.
Spread Windows Forms Developer’s Guide 182
Copyright © GrapeCity, Inc. All rights reserved.
Unlikespanningcells,mergingisanautomaticfeature.Youtellthecomponentwhichcolumnsandrowsallowcellstobecombinedautomatically,andanycellswithinthatsetthathavethesamecontentsarecombinedforyou.
Formoreinformationonspanningcells,refertoCreatingaSpanofCells.
Thepolicyyousetdetermineshowthecomponenthandlesmerging,asfollows:
IfthemergepolicyissettoNone,cellswithinaroworcolumnarenotmerged.IfthemergepolicyissettoAlways,cellswithinaroworcolumnaremergedwhenthecellshavethesamevalues.IfthemergepolicyissettoRestricted,cellswithinaroworcolumnaremergedwhenthecellshavethesamevaluesandthecorrespondingcellsinthepreviousroworcolumnalsohavethesamevalue.Forexample,supposecellsA1:A8contain{a;a;b;b;b;b;c;c}andcellsB1:B8contain{1;1;1;1;2;2;2;2}.IfcolumnB'smergepolicyisAlways,thecellsincolumnBaremergedintotwoblocksB1:B4andB5:B8.IfcolumnB'smergepolicyisRestrictedthenthecellsincolumnBaremergedintofourblocksB1:B2,B3:B4,B5:B6,andB7:B8.
Youcanhavethecellsinthespecifiedroworcolumncombinethecellsautomatically,oronlycombinethemifthecellstotheirleft(incolumns)orabovethem(inrows)aremerged.Typically,ifyousetthemergepolicyonseveraladjacentrowsorcolumns,thenyouwoulduseAlwaysonthefirstroworcolumnandRestrictedontheremainingrowsorcolumns.
Mergedcellstakeonthepropertiesofthetop-leftmergedcell.Forexample,ifthetop-leftmergedcellhasabluebackgroundcolor,thecellsthatmergewithitdisplaythesamebackgroundcolor.
Mergedcellsdonotlosetheirdata;itissimplyhiddenbythemerge.Ifyouremovethemerge,thedataappearsineachcellthatwasinthemerge.Youcaneditacellthatismergedwithanothercell.Whenyoudouble-clickthecelltoturneditmodeon,thecontentsofthecellappearinthecellforyoutoeditthem.Whenyouleaveeditmode,ifthecontentsofthecellarenolongeridenticaltothecellorcellswithwhichitwaspreviouslymerged,thecellsarenolongerdisplayedasmerged.
Cellsthataredifferentcelltypesbuthavethesamecontentscanmerge.Forexample,adatecellmightcontainthecontents"01/31/02"andtheadjacenteditcellmightcontainthesamecontents;ifthecolumncontainingthecellsissettomerge,thecellswillmerge.Ifthecontentschangeorthemergeisremoved,thecellsmaintaintheircelltypesaswellastheirdata.
Tosetcellstobemergediftheyhavethesamevalue,usethefollowingmembers:
GetColumMerge('GetColumnMergeMethod'intheon-linedocumentation)andSetColumMerge('SetColumnMergeMethod'intheon-linedocumentation)GetRowMerge('GetRowMergeMethod'intheon-linedocumentation)andSetRowMerge('SetRowMergeMethod'intheon-linedocumentation)GetMergePolicy('GetMergePolicyMethod'intheon-linedocumentation)andSetMergePolicy('SetMergePolicyMethod'intheon-linedocumentation)
Formoreinformationonthesemembers,refertotheSheetView('SheetViewClass'intheon-linedocumentation)class(ortheRow('RowClass'intheon-linedocumentation)orColumn('ColumnClass'
Spread Windows Forms Developer’s Guide 183
Copyright © GrapeCity, Inc. All rights reserved.
intheon-linedocumentation)class)ortheDefaultSheetAxisModel('DefaultSheetAxisModelClass'intheon-linedocumentation)oftheFarPoint.Win.Spread.Model('FarPoint.Win.Spread.ModelNamespace'intheon-linedocumentation)namespace.
UsingaShortcut
UsetheSetColumMerge('SetColumnMergeMethod'intheon-linedocumentation)orSetRowMerge('SetRowMergeMethod'intheon-linedocumentation)methodfortheSheetsorActiveSheetshortcutobject.
Example
Thisexamplecodesetstherowandcolumnmergepoliciesforallrowsandallcolumns.
C#fpSpread1.Sheets[0].SetRowMerge(-1, FarPoint.Win.Spread.Model.MergePolicy.Always);fpSpread1.Sheets[0].SetColumnMerge(-1, FarPoint.Win.Spread.Model.MergePolicy.Always);
VBFpSpread1.Sheets(0).SetRowMerge(-1, FarPoint.Win.Spread.Model.MergePolicy.Always)FpSpread1.Sheets(0).SetColumnMerge(-1, FarPoint.Win.Spread.Model.MergePolicy.Always)
UsingCode
SettheSetColumMerge('SetColumnMergeMethod'intheon-linedocumentation)orSetRowMerge('SetRowMergeMethod'intheon-linedocumentation)methodforaSheetView('SheetViewClass'intheon-linedocumentation)object.
Example
Thisexamplecodemergescolumnsandrows.
C#FarPoint.Win.Spread.SheetView Sheet0;Sheet0 = fpSpread1.Sheets[0];Sheet0.SetRowMerge(-1, FarPoint.Win.Spread.Model.MergePolicy.Always);Sheet0.SetColumnMerge(-1, FarPoint.Win.Spread.Model.MergePolicy.Always);
VBDim Sheet0 As FarPoint.Win.Spread.SheetViewSheet0 = FpSpread1.Sheets(0)Sheet0.SetRowMerge(-1, FarPoint.Win.Spread.Model.MergePolicy.Always)Sheet0.SetColumnMerge(-1, FarPoint.Win.Spread.Model.MergePolicy.Always)
Allowing Cell Data to Overflow
Youcandeterminehowthecontentsofacelloragroupofcellsoverflowintoadjoiningcells.Ifyouallowcellcontentstooverflow:
Left-alignedtextinacelloverflowstotheadjacentrightcell.Right-alignedtextinacelloverflowstotheadjacentleftcell.Centeredtextinacelloverflowstoboththeleftandrightadjacentcells.
Spread Windows Forms Developer’s Guide 184
Copyright © GrapeCity, Inc. All rights reserved.
Anexampleofeachoftheseisshowninthefollowingfigure.
Tosettheoverflowbehavior,usethefollowingmembersfortheoverallcomponent(FpSpread('FpSpreadClass'intheon-linedocumentation)class)orthechildsheet(SpreadView('SpreadViewClass'intheon-linedocumentation)class):
AllowCellOverflow('AllowCellOverflowProperty'intheon-linedocumentation)GetMaximumCellOverflowWidth('GetMaximumCellOverflowWidthMethod'intheon-linedocumentation)SetMaximumCellOverflowWidth('SetMaximumCellOverflowWidthMethod'intheon-linedocumentation)AllowEditOverflow('AllowEditOverflowProperty'intheon-linedocumentation)
YoucanspecifytheamountofcontentthatwilloverflowintoadjacentcellsbyspecifyingthenumberofpixelsofoverflowallowedusingtheSetMaximumCellOverflowWidth('SetMaximumCellOverflowWidthMethod'intheon-linedocumentation)method.
Formoreinformationoncellcontentsalignment,refertoAligningCellContents.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. Select(intheBehaviorcategory)theAllowCellOverflowpropertyortheAllowEditOverflowproperty.3. SelectTruefromthedrop-downlisttoallowcellstooverflow,orselectFalsetoprohibitcellsfromoverflowing.
UsingaShortcut
1. AllowthecontentsofasetofcellstooverflowbysettingtheAllowCellOverflow('AllowCellOverflowProperty'intheon-linedocumentation)property.
2. SpecifythemaximumamountofcontentallowedtooverflowbycallingtheSetMaximumCellOverflowWidth('SetMaximumCellOverflowWidthMethod'intheon-linedocumentation)methodtospecifythenumberofpixelsallowedtooverflow.
Example
Thisexamplecodesetsthecomponenttoallowcellstooverflowbutonlyuptothemaximumof130pixels.
C#fpSpread1.AllowCellOverflow = true;fpSpread1.SetMaximumCellOverflowWidth(130);
Spread Windows Forms Developer’s Guide 185
Copyright © GrapeCity, Inc. All rights reserved.
VBFpSpread1.AllowCellOverflow = TrueFpSpread1.SetMaximumCellOverflowWidth(130)
UsingCode
1. AllowthecontentsofasetofcellstooverflowbysettingtheFpSpread('FpSpreadClass'intheon-linedocumentation)AllowCellOverflow('AllowCellOverflowProperty'intheon-linedocumentation)property.
2. SpecifythemaximumamountofcontentallowedtooverflowbycallingtheSetMaximumCellOverflowWidth('SetMaximumCellOverflowWidthMethod'intheon-linedocumentation)methodtospecifythenumberofpixelsallowedtooverflow.
Example
Thisexamplecodesetsthechildsheettoallowcellstooverflowuptoamaximumwidthof130.
C#FarPoint.Win.Spread.SpreadView sv = fpSpread1.GetRootWorkbook();sv.AllowCellOverflow = true;sv.SetMaximumCellOverflowWidth(130);
VBDim sv As FarPoint.Win.Spread.SpreadView = FpSpread1.GetRootWorkbooksv.AllowCellOverflow = Truesv.SetMaximumCellOverflowWidth(130)
UsingtheSpreadDesigner
1. SelecttheSpreadcomponent(orselectSpreadfromthepull-downmenu).2. Inthepropertylistforthecomponent,intheBehaviorcategory,selecttheAllowCellOverflowpropertyortheAllowEditOverflowandselectthevalueTrue.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Creating and Applying a Style for Cells
Youcanquicklycustomizetheappearanceofacellorrangeofcells(orrowsorcolumns)byapplyinga"style".Youcancreateyourownnamedstyleandsaveittouseagain,similartoatemplate,oryoucansimplychangethepropertiesofthedefaultstyle.Thestyleincludesappearancesettingsthatapplytocells,suchasbackgroundcolor,textcolor,font,borders,andcelltype.Astylecanbeappliedtoanynumberofcells.Justasaskincanbeappliedtoasheet,soastylecanbeappliedtocells.
Note:Theword"appearance"isusedforthegenerallookofthecell,notsimplythesettingsintheAppearanceclass,whichcontainsonlyafewsettingsandisusedfortheappearanceofseveralpartsoftheinterface.MostoftheappearancesettingsforacellareintheStyleInfo('StyleInfoClass'intheon-linedocumentation)class.
YoutypicallysetthestyleforthecellbyusingtheStyleName('StyleNameProperty'intheon-linedocumentation)propertyforthecell.YoucanalsousetheParentStyleName('ParentStyleNameProperty'intheon-linedocumentation)tosetastyleforarangeofcellsthatmayindividuallyhavedifferentStyleNamevaluesset.Acellinheritsallthestyleinformationfromtheparentstyle(ParentStyleName).Whenyousettheparentstyle,
Spread Windows Forms Developer’s Guide 186
Copyright © GrapeCity, Inc. All rights reserved.
youaresettingtheParentpropertyoftheStyleInfoobjectassignedtoeachcellintherange.TheparentforanamedstylecanalsobesetbytheParentpropertyoftheNamedStyleobject.Sodifferentcells(forexample,cellsindifferentrowsorcolumns)mayhavedifferentnamedstylesbuthavethesameparentstyle.Forexample,thecellsmayhavedifferenttextcolors(setinthenamedstyle)butinheritthesamebackgroundcolor(setintheparentstyle).
Formoreinformation,refertotheDefaultStyleCollection('DefaultStyleCollectionClass'intheon-linedocumentation)classandtheNamedStyle('NamedStyleClass'intheon-linedocumentation)class.Whenyousetthestyle(StyleName),yousettheentireStyleInfo('StyleInfoClass'intheon-linedocumentation)objectinthestylemodelforeachcellintherangetotheoneintheNamedStyleCollection('NamedStyleCollectionClass'intheon-linedocumentation)withthespecifiedname.ThedefaultparentstyleissetintheDataAreaDefaultfieldintheDefaultStyleCollectionclass.
Youcanalsocreateandapplyappearancesettingstoanentiresheetbyusingsheetskins.Forinstructionsoncreatingsheetskins,seeCreatingaCustomSkinforaSheet.
Formoreinformationontheunderlyingmodelforstyles,refertoUnderstandingtheStyleModel.
UsingCode
1. CalltheNamedStyle('NamedStyleClass'intheon-linedocumentation)objectconstructor,andsetitsparameterstospecifythenameandsettingsforthestyle.Youcanalsosettheparentname.
2. Setthestylesettings.3. Setthecustomnamedstylebyassigningthestylenametothecellorcells.
Example
Thisexamplecodesetsthefirstsquareofcellsontheactivesheettousethesamecustomstylethatsetsthebackgroundcolortoblueandsetsthetextcolordependingonwhichcolumn.
C#FarPoint.Win.Spread.NamedStyle backstyle = new FarPoint.Win.Spread.NamedStyle("BlueBack");backstyle.BackColor = Color.Blue;FarPoint.Win.Spread.NamedStyle text1style = new FarPoint.Win.Spread.NamedStyle("OrangeText", "BlueBack");text1style.ForeColor = Color.Orange;FarPoint.Win.Spread.NamedStyle text2style = new FarPoint.Win.Spread.NamedStyle("YellowText", "BlueBack");text2style.ForeColor = Color.Yellow;fpSpread1.NamedStyles.Add(backstyle);fpSpread1.NamedStyles.Add(text1style);fpSpread1.NamedStyles.Add(text2style);fpSpread1.ActiveSheet.Cells[0,0,4,0].StyleName = "OrangeText";fpSpread1.ActiveSheet.Cells[0,1,4,1].StyleName = "YellowText";
VBDim backstyle As New FarPoint.Win.Spread.NamedStyle("BlueBack")backstyle.BackColor = Color.BlueDim text1style As New FarPoint.Win.Spread.NamedStyle("OrangeText", "BlueBack")text1style.ForeColor = Color.OrangeDim text2style As New FarPoint.Win.Spread.NamedStyle("YellowText", "BlueBack")text2style.ForeColor = Color.YellowFpSpread1.NamedStyles.Add(backstyle)FpSpread1.NamedStyles.Add(text1style)FpSpread1.NamedStyles.Add(text2style)FpSpread1.ActiveSheet.Cells(0,0,4,0).StyleName = "OrangeText"
Spread Windows Forms Developer’s Guide 187
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.ActiveSheet.Cells(0,1,4,1).StyleName = "YellowText"
Example
ConfigurethedefaultstylefortheentiresheetsbyspecifyingDefaultStyleproperty(StyleInfo)inSheetViewclass.Thisapproachisconvenientwhenyouwanttoapplyoneuniquestyletoallcellsinasheet,asshowninthedataareaofthespreadsheetinthisfigure.
C#private void Form1_Load(object sender, System.EventArgs e){ fpSpread1.ActiveSheet.RowCount = 5; fpSpread1.ActiveSheet.ColumnCount = 5; // Configure respective default styles. fpSpread1.ActiveSheet.DefaultStyle.BackColor = Color.LemonChiffon; fpSpread1.ActiveSheet.DefaultStyle.ForeColor = Color.Red; fpSpread1.ActiveSheet.DefaultStyle.CellType = new FarPoint.Win.Spread.CellType.NumberCellType(); fpSpread1.ActiveSheet.DefaultStyle.HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center; fpSpread1.ActiveSheet.DefaultStyle.Border = new FarPoint.Win.LineBorder(Color.Green); for (int i = 0; i < fpSpread1.ActiveSheet.RowCount; i++) { for (int j = 0; j < fpSpread1.ActiveSheet.ColumnCount; j++) { fpSpread1.ActiveSheet.SetValue(i, j, i + j); } }}
VBPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load FpSpread1.ActiveSheet.RowCount = 5 FpSpread1.ActiveSheet.ColumnCount = 5 ' Configure respective default styles. FpSpread1.ActiveSheet.DefaultStyle.BackColor = Color.LemonChiffon FpSpread1.ActiveSheet.DefaultStyle.ForeColor = Color.Red FpSpread1.ActiveSheet.DefaultStyle.CellType = New FarPoint.Win.Spread.CellType.NumberCellType FpSpread1.ActiveSheet.DefaultStyle.HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center FpSpread1.ActiveSheet.DefaultStyle.Border = New FarPoint.Win.LineBorder(Color.Green) For i As Integer = 0 To FpSpread1.ActiveSheet.RowCount - 1 For j As Integer = 0 To FpSpread1.ActiveSheet.ColumnCount - 1
Spread Windows Forms Developer’s Guide 188
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.ActiveSheet.SetValue(i, j, i + j) Next NextEnd Sub
UsingtheNamedStyleCollectionEditor
1. IntheFormwindow,clicktheSpreadcomponentortheSheetobjectforwhichyouwanttocreatethestyleintheNamedStyleCollection.FortheSpreadcomponent,intheAppearancecategory,selecttheNamedStylesproperty.FortheSheetobject,intheMisccategory,selecttheNamedStylesproperty.
2. ClickonthebuttontolaunchtheNamedStyleCollectionEditor.3. IntheNamedStyleCollectionEditor,selecttheAddtab.4. SetthepropertiesintheNamedStylePropertieslisttocreatethestyleyouwant.5. SettheNamepropertytospecifythenameforyourcustomstyle.6. ClickOKtoclosetheeditor.7. Selectthecells(orrowsorcolumns)toapplythestyleto.8. Inthepropertywindow,settheStyleNametothecustomnamedstylepreviouslyadded.
Using Sparklines
Youcancreateasparklineinacellwhichisasmallgraphthatusesdatafromarangeofcells.Thedataforthesparklineislimitedtoonecolumnorrowofvalues.Youcansetthesparklinetypetocolumn,line,orwinloss,asshowninthefollowingfigure.Theseimageswerecreatedusingaminimumaxisof-9andamaximumaxisof15.
Thecolumnsparklinedrawsthevaluesasacolumnchart.Thelinesparklinedrawsthevaluesasalinechart.Thewinlosssparklineshowsthepointswiththesamesize.Negativepointsextenddownfromtheaxisandpositivepointsextendup.
Thegraphscandisplaycolorsforthemarkerpoints.Youcansetcolorsforthehigh,low,negative,first,andlastpoints.
Thegraphshavehorizontalandverticalaxes.
Sparklinesarestoredasgroups.Agroupcontainsatleastonesparkline.
Formoreinformation,seethefollowingtopics:
AddingaSparklinetoaCellCustomizingMarkersandPointsSpecifyingHorizontalandVerticalAxesWorkingwithSparklines
Adding a Sparkline to a Cell
Youcanaddasparklinetoacellusingcodeorthedesigner.
Spread Windows Forms Developer’s Guide 189
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
1. Specifyacellinwhichtocreatethesparkline.2. Specifyarangeofcellsforthedata.3. Setanypropertiesforthesparkline(suchaspointsandcolors).4. Addthesparklinetothecell.
Example
Thisexamplecreatesacolumnsparklineinacellandshowsnegativeandseriescolors.
C#FarPoint.Win.Spread.SheetView sv = new FarPoint.Win.Spread.SheetView();FarPoint.Win.Spread.Chart.SheetCellRange data = new FarPoint.Win.Spread.Chart.SheetCellRange(sv, 0,0,1, 5);FarPoint.Win.Spread.Chart.SheetCellRange data2 = new FarPoint.Win.Spread.Chart.SheetCellRange(sv, 5,0,1,1);FarPoint.Win.Spread.ExcelSparklineSetting ex = new FarPoint.Win.Spread.ExcelSparklineSetting();ex.ShowMarkers = true;ex.ShowNegative = true;ex.NegativeColor = Color.Red;// Use with a Column or Winloss typeex.SeriesColor = Color.Olive;fpSpread1.Sheets[0] = sv;sv.Cells[0, 0].Value = 2;sv.Cells[0, 1].Value = 5;sv.Cells[0, 2].Value = 4;sv.Cells[0, 3].Value = -1;sv.Cells[0, 4].Value = 3;fpSpread1.Sheets[0].AddSparkline(data, data2, FarPoint.Win.Spread.SparklineType.Column, ex);
VBDim sv As New FarPoint.Win.Spread.SheetView()Dim data As New FarPoint.Win.Spread.Chart.SheetCellRange(sv, 0, 0, 1, 5)Dim data2 As New FarPoint.Win.Spread.Chart.SheetCellRange(sv, 5, 0, 1, 1)Dim ex As New FarPoint.Win.Spread.ExcelSparklineSetting()ex.ShowMarkers = Trueex.ShowNegative = Trueex.NegativeColor = Color.Red' Use with a Column or Winloss typeex.SeriesColor = Color.Olive
Spread Windows Forms Developer’s Guide 190
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.Sheets(0) = svsv.Cells(0, 0).Value = 2sv.Cells(0, 1).Value = 5sv.Cells(0, 2).Value = 4sv.Cells(0, 3).Value = -1sv.Cells(0, 4).Value = 3FpSpread1.Sheets(0).AddSparkline(data, data2, FarPoint.Win.Spread.SparklineType.Column, ex)
UsingtheSpreadDesigner
1. Typedatainacelloracolumnorrowofcellsinthedesigner.2. Selectacellforthesparkline.3. SelecttheInsertmenu.4. Selectasparklinetype.5. SettheDataRangeintheEditSparklinesdialog(suchas=Sheet1!$E$1:$E$3).Youcanalsosettherangebyselectingthecellsintherangeusingthepointer.
6. SelectOK.7. SelectApplyandExitfromtheFilemenutosaveyourchangesandclosethedesigner.
Customizing Markers and Points
Youcanshowmarkersorpointsinthesparklinegraphs.Thefollowingimagedisplaysthepointsinalinesparkline.Youcanspecifydifferentcolorsforlowornegative,high,first,andlastpoints.
Thehighpointisthepointforthelargestvalue.Thelowpointisthesmallestvalue.Thenegativepointrepresentsnegativevalues.Thefirstpointisthefirstpointthatisdrawnonthegraph.Thelastpointisthelastpointthatisdrawnonthegraph.
TheSeriesColorpropertyappliestothelineforthelinesparktype.TheMarkersColorpropertyisonlyforthelinetypesparkline.SeetheExcelSparklineSetting('ExcelSparklineSettingClass'intheon-linedocumentation)classforalistofsparklinepropertiesandadditionalcodesamples.
UsingCode
1. Specifyacelltocreatethesparklinein.2. Specifyarangeofcellsforthedata.3. Setanypropertiesforthesparkline(suchasShowFirstandFirstMarkerColor).4. Addthesparklinetothecell.
Example
Thisexamplecreatesalinesparklineinacellandshowsdifferentmarkersandcolors.
Spread Windows Forms Developer’s Guide 191
Copyright © GrapeCity, Inc. All rights reserved.
C#FarPoint.Win.Spread.SheetView sv = new FarPoint.Win.Spread.SheetView();FarPoint.Win.Spread.Chart.SheetCellRange data = new FarPoint.Win.Spread.Chart.SheetCellRange(sv, 0,0,1, 5);FarPoint.Win.Spread.Chart.SheetCellRange data2 = new FarPoint.Win.Spread.Chart.SheetCellRange(sv, 5,0,1,1);FarPoint.Win.Spread.ExcelSparklineSetting ex = new FarPoint.Win.Spread.ExcelSparklineSetting();ex.AxisColor = Color.SaddleBrown;ex.ShowFirst = true;ex.ShowHigh = true;ex.ShowLow = true;ex.ShowLast = true;ex.FirstMarkerColor = Color.Blue;ex.HighMarkerColor = Color.DarkGreen;ex.MarkersColor = Color.Aquamarine;ex.LowMarkerColor = Color.Red;ex.LastMarkerColor = Color.Orange;ex.ShowMarkers = true;fpSpread1.Sheets[0] = sv;sv.Cells[0, 0].Value = 2;sv.Cells[0, 1].Value = 5;sv.Cells[0, 2].Value = 4;sv.Cells[0, 3].Value = 1;sv.Cells[0, 4].Value = 3;fpSpread1.Sheets[0].AddSparkline(data, data2, FarPoint.Win.Spread.SparklineType.Line, ex);
VBDim sv As New FarPoint.Win.Spread.SheetView()Dim data As New FarPoint.Win.Spread.Chart.SheetCellRange(sv, 0, 0, 1, 5)Dim data2 As New FarPoint.Win.Spread.Chart.SheetCellRange(sv, 5, 0, 1, 1)Dim ex As New FarPoint.Win.Spread.ExcelSparklineSetting()ex.AxisColor = Color.SaddleBrownex.ShowFirst = Trueex.ShowHigh = Trueex.ShowLow = Trueex.ShowLast = Trueex.FirstMarkerColor = Color.Blueex.HighMarkerColor = Color.DarkGreenex.MarkersColor = Color.Aquamarineex.LowMarkerColor = Color.Redex.LastMarkerColor = Color.Orangeex.ShowMarkers = TrueFpSpread1.Sheets(0) = svsv.Cells(0, 0).Value = 2sv.Cells(0, 1).Value = 5sv.Cells(0, 2).Value = 4sv.Cells(0, 3).Value = 1sv.Cells(0, 4).Value = 3FpSpread1.Sheets(0).AddSparkline(data, data2, FarPoint.Win.Spread.SparklineType.Line, ex)
UsingtheSpreadDesigner
Spread Windows Forms Developer’s Guide 192
Copyright © GrapeCity, Inc. All rights reserved.
1. Typedatainacelloracolumnorrowofcellsinthedesigner.2. Selectacellforthesparkline.3. SelecttheInsertmenu.4. Selectasparklinetype.5. SelectthedataforthegraphwhentheCreateSparklinesdialogisdisplayed.6. SelectOK.7. Selectthesparklinecell,selecttheMarkerColororSparklineColoricon,andsetthecolors.8. SelectApplyandExitfromtheFilemenutosaveyourchangesandclosethedesigner.
Specifying Horizontal and Vertical Axes
Thehorizontalaxishasageneralandadatetype.Thegeneraltypespecifiesthatallthepointsarepaintedalongtheaxisatthesamedistance.Thedatetypespecifieswhichpointsaredrawnandcanhavedifferentdistancesbetweenthepointsbasedonthedayunit.
SettheDateAxispropertytotrueintheExcelSparklineSetting('ExcelSparklineSettingClass'intheon-linedocumentation)classtousethedatehorizontalaxisandtheDisplayXAxispropertyifyouwishtodisplaytheaxisline.Ifacellisblankinthedaterange,thenthatpointisnotdrawnbydefaultwiththedateaxis.ThefollowingimagedisplaysallthreepointsonthegraphbutleavesalargergapbetweenthesecondandthirdpointstoshowthedistancebetweenJanuary3rdandJanuary5th.
Youcanspecifydifferentminimumandmaximumvalueoptionsfortheverticalaxis.Theautomaticoptionallowseachsparklinetohaveadifferentminimumandmaximumvalue.Thesameoptionusesthesameminimumandmaximumvalueforallthesparklines.Thecustomoptionallowsyoutospecifytheminimumandmaximumvalueforallthesparklinesinagroup.
Ifthecustomoptionisusedfortheverticalaxis,andtheminimumvalueisequaltoorlargerthanalldatapoints,pointsorlinesarenotdrawn.Linesorcolumnsaretruncatediftheyarenotcompletelyinthedrawingarea.Ifacolumnsparklinehasatleastonepointdrawncompletelyorpartially,thenallcolumnswithvalueslessthantheminimumaredrawnasthincolumnsthatextenddown.
SeetheManualMax,ManualMin,MaxAxisType,andMinAxisTypepropertiesintheExcelSparklineSetting('ExcelSparklineSettingClass'intheon-linedocumentation)classforverticalaxisexamples.
UsingCode
1. CreateanExcelSparklineSettingobject.2. SettheDateAxispropertytousethedateforthex-axis.3. SettheDisplayXAxispropertytotrueifyouwishtodisplaytheaxis.4. Addvaluesanddatestothecells.5. Addthesparklinetothecell.
Example
Thisexamplecreatesacolumnsparklineinacellwithadatehorizontalaxis.
C#FarPoint.Win.Spread.ExcelSparklineSetting ex = new FarPoint.Win.Spread.ExcelSparklineSetting();
Spread Windows Forms Developer’s Guide 193
Copyright © GrapeCity, Inc. All rights reserved.
ex.DisplayXAxis = true;ex.DateAxis = true;ex.Formula = "Sheet1!$A$1:$C$1";fpSpread1.Sheets[0].Cells[0, 0].Text = "1/2/2011";fpSpread1.Sheets[0].Cells[0, 1].Text = "1/3/2011";fpSpread1.Sheets[0].Cells[0, 2].Text = "1/5/2011";fpSpread1.Sheets[0].Cells[1, 0].Value = 2;fpSpread1.Sheets[0].Cells[1, 1].Value = 11;fpSpread1.Sheets[0].Cells[1, 2].Value = 4;fpSpread1.Sheets[0].AddSparkline("Sheet1!$A$2:$C$2", "Sheet1!$D$2:$D$2", FarPoint.Win.Spread.SparklineType.Column, ex);
VBDim ex As New FarPoint.Win.Spread.ExcelSparklineSetting()ex.DisplayXAxis = Trueex.DateAxis = Trueex.Formula = "Sheet1!$A$1:$C$1"FpSpread1.Sheets(0).Cells(0, 0).Text = "1/2/2011"FpSpread1.Sheets(0).Cells(0, 1).Text = "1/3/2011"FpSpread1.Sheets(0).Cells(0, 2).Text = "1/5/2011"FpSpread1.Sheets(0).Cells(1, 0).Value = 2FpSpread1.Sheets(0).Cells(1, 1).Value = 11FpSpread1.Sheets(0).Cells(1, 2).Value = 4FpSpread1.Sheets(0).AddSparkline("Sheet1!$A$2:$C$2", "Sheet1!$D$2:$D$2", FarPoint.Win.Spread.SparklineType.Column, ex)
UsingtheSpreadDesigner
1. Typedatainacelloracolumnorrowofcellsinthedesigner.2. Typedatesinacelloracolumnorrowofcellsinthedesigner.3. Selectacellforthesparkline.4. SelecttheInsertmenu.5. Selectasparklinetype.6. SelectthedataforthegraphwhentheCreateSparklinesdialogisdisplayed.7. SelectOK.8. Selectthesparklinecell,selecttheAxisicon,andthenmakeanychangestotheaxis.9. SelectApplyandExitfromtheFilemenutosaveyourchangesandclosethedesigner.
Working with Sparklines
Youcangroup,delete,cut,copy,andswitchrowsandcolumnswithsparklines.
Groupingmergessparklinesintoanewgroupandremovesthemfromtheoldgroups.Iftheselectedsparklinesbelongtodifferentgroupswithdifferenttypes,thenewgroupwillhavethetypeofthelastselectedgroup.Thenewgroupwillalsohavetheemptycell,style,andaxissettingsofthelastselectedgroup.
Ungroupingselectedsparklinegroupsseparatesthemintodifferentgroupsthatcontainonlyonesparkline.Thedataandlocationrangeoftheoriginalsparklineareusedinthenewgroups.Thesettingsoftheoriginalgrouparealsousedinthenewgroups.
Ifyoudeleteagroup,allsparklinesinthegrouparealsodeleted.YoucanclearasparklineincodewiththeClearSparklines('ClearSparklinesMethod'intheon-linedocumentation)methodintheSheetviewclass.
YoucanusestandardWindowsshortcutkeystocut,copy,orpastesparklines.
Spread Windows Forms Developer’s Guide 194
Copyright © GrapeCity, Inc. All rights reserved.
Ifyoucopyagroupofsparklines,theywillbecomeanewgroupwhentheyarepastedtoanewlocation.Copyingasinglesparklinefromagroup,willcreateanewgroupwithasinglesparkline.
Youcanswitchtherangeofdatausedinthesparklinefromrowtocolumnorcolumntorow.UsetheSwitchRowColumn('SwitchRowColumnMethod'intheon-linedocumentation)methodintheExcelSparklineGroup('ExcelSparklineGroupClass'intheon-linedocumentation)classincode.Therangeofdatashouldhavethesamenumberofrowsandcolumns.UsetheAddSquareSparkline('AddSquareSparklineMethod'intheon-linedocumentation)methodintheSheetViewclasstoaddasparklinethatcanbeswitched.
UsingCode
1. UsetheGroupSparkline('GroupSparklineMethod'intheon-linedocumentation)methodtogroupsparklinecells.
2. UsetheUnGroupSparkline('UngroupSparklineMethod'intheon-linedocumentation)methodtoungroupsparklinecells.
Example
ThisexampleshowshowtousetheGroupSparkline('GroupSparklineMethod'intheon-linedocumentation)methodortheUnGroupSparkline('UngroupSparklineMethod'intheon-linedocumentation)method.
C#FarPoint.Win.Spread.SheetView sv = new FarPoint.Win.Spread.SheetView();private void Form1_Load(object sender, EventArgs e){FarPoint.Win.Spread.Chart.SheetCellRange test = new FarPoint.Win.Spread.Chart.SheetCellRange(sv, 0, 0, 2, 4);FarPoint.Win.Spread.Model.CellRange data2 = new FarPoint.Win.Spread.Model.CellRange(0, 5, 2, 1);FarPoint.Win.Spread.ExcelSparklineSetting ex = new FarPoint.Win.Spread.ExcelSparklineSetting();ex.ShowFirst = true;ex.FirstMarkerColor = Color.Violet;fpSpread1.Sheets[0] = sv;sv.Cells[0, 0].Value = 2;sv.Cells[0, 1].Value = 5;sv.Cells[0, 2].Value = 4;sv.Cells[0, 3].Value = -1;sv.Cells[0, 4].Value = 3;sv.Cells[1, 0].Value = 3;sv.Cells[1, 1].Value = 1;sv.Cells[1, 2].Value = 2;sv.Cells[1, 3].Value = -1;sv.Cells[1, 4].Value = 5;
sv.Cells[2, 0].Value = 3;sv.Cells[2, 1].Value = 1;sv.Cells[2, 2].Value = 2;sv.Cells[2, 3].Value = -1;sv.Cells[2, 4].Value = 5;fpSpread1.Sheets[0].AddSparkline(test, data2, FarPoint.Win.Spread.SparklineType.Column, ex);
FarPoint.Win.Spread.Chart.SheetCellRange test1 = new FarPoint.Win.Spread.Chart.SheetCellRange(sv, 2, 0, 1, 4);
Spread Windows Forms Developer’s Guide 195
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Spread.Model.CellRange data3 = new FarPoint.Win.Spread.Model.CellRange(2, 5, 1, 1);FarPoint.Win.Spread.ExcelSparklineSetting ex1 = new FarPoint.Win.Spread.ExcelSparklineSetting();ex1.FirstMarkerColor = Color.Red;ex1.ShowFirst = true;fpSpread1.Sheets[0].AddSparkline(test1, data3, FarPoint.Win.Spread.SparklineType.Column, ex1); sv.Cells[4, 0].Value = 2;sv.Cells[4, 1].Value = 1;sv.Cells[5, 0].Value = 5;sv.Cells[5, 1].Value = 3;FarPoint.Win.Spread.Chart.SheetCellRange newdata = new FarPoint.Win.Spread.Chart.SheetCellRange(sv, 4, 0, 2, 2);FarPoint.Win.Spread.Model.CellRange newlocation = new FarPoint.Win.Spread.Model.CellRange(6, 0, 1, 2);FarPoint.Win.Spread.ExcelSparklineSetting ex2 = new FarPoint.Win.Spread.ExcelSparklineSetting();fpSpread1.Sheets[0].AddSquareSparkline(newdata, newlocation, FarPoint.Win.Spread.SparklineType.Column, ex2, true);}
private void button1_Click(object sender, EventArgs e) {
fpSpread1.Sheets[0].GroupSparkline(new FarPoint.Win.Spread.Model.CellRange[] { new FarPoint.Win.Spread.Model.CellRange(5, 0, 3, 1) });// fpSpread1.Sheets[0].UnGroupSparkline(new FarPoint.Win.Spread.Model.CellRange[] { new FarPoint.Win.Spread.Model.CellRange(5, 0, 3, 1) });}
VBDim sv As New FarPoint.Win.Spread.SheetView()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadDim data2 As New FarPoint.Win.Spread.Chart.SheetCellRange(sv, 0, 0, 2, 4)Dim test As New FarPoint.Win.Spread.Model.CellRange(0, 5, 2, 1)
Dim ex As New FarPoint.Win.Spread.ExcelSparklineSetting()ex.ShowFirst = Trueex.FirstMarkerColor = Color.VioletFpSpread1.Sheets(0) = svsv.Cells(0, 0).Value = 2sv.Cells(0, 1).Value = 5sv.Cells(0, 2).Value = 4sv.Cells(0, 3).Value = -1sv.Cells(0, 4).Value = 3sv.Cells(1, 0).Value = 3sv.Cells(1, 1).Value = 1sv.Cells(1, 2).Value = 2sv.Cells(1, 3).Value = -1sv.Cells(1, 4).Value = 5
sv.Cells(2, 0).Value = 3
Spread Windows Forms Developer’s Guide 196
Copyright © GrapeCity, Inc. All rights reserved.
sv.Cells(2, 1).Value = 1sv.Cells(2, 2).Value = 2sv.Cells(2, 3).Value = -1sv.Cells(2, 4).Value = 5FpSpread1.Sheets(0).AddSparkline(data2, test, FarPoint.Win.Spread.SparklineType.Column, ex)
Dim data3 = New FarPoint.Win.Spread.Chart.SheetCellRange(sv, 2, 0, 1, 4)Dim test1 = New FarPoint.Win.Spread.Model.CellRange(2, 5, 1, 1)Dim ex1 As New FarPoint.Win.Spread.ExcelSparklineSetting()ex1.FirstMarkerColor = Color.Redex1.ShowFirst = TrueFpSpread1.Sheets(0).AddSparkline(data3, test1, FarPoint.Win.Spread.SparklineType.Column, ex1)
sv.Cells(4, 0).Value = 2sv.Cells(4, 1).Value = 1sv.Cells(5, 0).Value = 5sv.Cells(5, 1).Value = 3Dim newdata = New FarPoint.Win.Spread.Chart.SheetCellRange(sv, 4, 0, 2, 2)Dim newlocation = New FarPoint.Win.Spread.Model.CellRange(6, 0, 1, 2)Dim ex2 As New FarPoint.Win.Spread.ExcelSparklineSetting()FpSpread1.Sheets(0).AddSquareSparkline(newdata, newlocation, FarPoint.Win.Spread.SparklineType.Column, ex2, True)End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.ClickFpSpread1.Sheets(0).GroupSparkline(New FarPoint.Win.Spread.Model.CellRange() {New FarPoint.Win.Spread.Model.CellRange(5, 0, 3, 1)})'FpSpread1.Sheets(0).UnGroupSparkline(New FarPoint.Win.Spread.Model.CellRange() {New FarPoint.Win.Spread.Model.CellRange(5, 0, 3, 1)})End Sub
UsingtheSpreadDesigner
1. Selectthesparklinecells.2. SelectGrouporUngroupintheGroupsectionofthetoolbartogrouporungroupsparklines.3. SelectClearifyouwishtoremoveanysparklines.4. UsetheEditDataoptiontoeditthedataorswitchtherangeofdatausedinthesparkline.5. SelectApplyandExitfromtheFilemenutosaveyourchangesandclosethedesigner.
Spread Windows Forms Developer’s Guide 197
Copyright © GrapeCity, Inc. All rights reserved.
Customizing Sheet Interaction
YoucancustomizevariousaspectsofuserinteractionofthespreadsheetintheSpreadcomponent.Thetasksthatrelatetocustomizingtheuserinteractionwiththespreadsheetinclude:
CustomizingInteractionintheOverallComponentCustomizingInteractionwithaSheetCustomizingUserSearchingofDataCustomizingUserSelectionofDataSettingandResettingUserInteractionCustomizingDrawing
Youcancustomizewhatyouallowtheusertodo.Thereareseveralfeaturesthatarecoveredinvarioustopicsinthissection,buttheyaresummarizedinonetopicforeasyreferenceinAllowingUserFunctionality.
Forinformationaboutinteractionsinotherareas,referto:
AllowingtheUsertoAutomaticallySortRowsManagingKeyboardInteractionManagingPrinting
Customizing Interaction in the Overall Component
YoucancustomizeseveralaspectsoftheuserinterfacetocustomizeuserinteractionwiththeSpreadcomponent.Youcanalsocustomizehowuserinteractionishandled.Formoreinformation,seethefollowingtopicsconcerningthesetwoareasofcustomization:
UserInterface
CustomizingtheScrollBarsoftheComponentCustomizingScrollBarTipsCustomizingtheSheetNameTabsoftheComponentCustomizingtheUserInterfaceImagesAllowingtheUsertoZoomtheDisplayoftheComponentCustomizingtheScaleModeAddingaContextMenutoaComponentAddingaStatusBar(on-linedocumentation)HostingtheComponentonaWebPage
InteractionHandling
CustomizingClipboardOperationOptionsCustomizingUndoandRedoActionsLocatingthePointerUsingHitTestCustomizingInteractionBasedonEventsHandlingEventsofSubeditorsCustomizingtheUserErrorMessages
YoucanalsosupplytheuserwithaSearchdialog.Formoreinformation,seeAllowingtheUsertoPerformaStandardSearch.
Customizing the Scroll Bars of the Component
Youcancustomizethedisplayandoperationofthescrollbarsonthespreadsheet.Thereareseveralaspectsofthe
Spread Windows Forms Developer’s Guide 198
Copyright © GrapeCity, Inc. All rights reserved.
displayofscrollbarsthatyoucanspecify.Thepartsofthescrollbarsareshowninthefollowingfigure.
OnewaytocustomizethescrollbardisplayandoperationistousetheEnhancedScrollBarRenderer('EnhancedScrollBarRendererClass'intheon-linedocumentation)classmembers.
AnotherwayistosetthesecustomizationstothescrollbarsfortheentirecomponentusingthepropertiesintheFpSpread('FpSpreadClass'intheon-linedocumentation)class.Tosetthescrollbarsfortheviewports,usethepropertiesintheSpreadView('SpreadViewClass'intheon-linedocumentation)class.ThetablebelowlinkstopropertiesintheFpSpread('FpSpreadClass'intheon-linedocumentation)class.
Customization PropertyinFpSpreadWhentodisplayeitheraverticalorhorizontalscrollbarorbothontheedgesofthesheetinthecomponent
HorizontalScrollBarPolicy('HorizontalScrollBarPolicyProperty'intheon-linedocumentation)
VerticalScrollBarPolicy('VerticalScrollBarPolicyProperty'intheon-linedocumentation)
Dimensionsofthescrollbars HorizontalScrollBarHeight('HorizontalScrollBarHeightProperty'intheon-linedocumentation)
VerticalScrollBarWidth('VerticalScrollBarWidthProperty'intheon-linedocumentation)
Whetherthespreadsheetscrollsacrossthedisplaywhentheusermovesthescrollbox(tracking)
ScrollBarTrackPolicy('ScrollBarTrackPolicyProperty'intheon-linedocumentation)
Whetherscrollbarsarebasedononlytheareathathasdataorontheentirespreadsheet
ScrollBarShowMax('ScrollBarShowMaxProperty'intheon-linedocumentation)
Whethertoalignthescrollbarswiththelastrowandcolumn
ScrollBarMaxAlign('ScrollBarMaxAlignProperty'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 199
Copyright © GrapeCity, Inc. All rights reserved.
Whetherscrollbartipsaredisplayed SeeCustomizingScrollBarTips
Ifyouwanttosetthewidthofahorizontalscrollbar,youcanchangethetabstripratio,whichdeterminesthewidthofthetabstrip,butalsodeterminesthewidthofthescrollbar.Bydefault,theTabStripRatio('TabStripRatioProperty'intheon-linedocumentation)propertyissetto0.50(areaisdivided50%tabstripand50%scrollbar).Toincreasethewidthofthescrollbar,forexample,youcouldchangethetabstripratioto0.25,whichwoulddividetheareabetween25%forthetabstripand75%forthescrollbar.Formoreinformationoncustomizingthetabstrip,refertoCustomizingtheSheetNameTabsoftheComponent.
Therearetwoeventsthatindicatethattheenduserhasmovedthescrollbars.TheTopChange('TopChangeEvent'intheon-linedocumentation)eventisraisedwhentheendusermovestheverticalscrollbar.TheLeftChange('LeftChangeEvent'intheon-linedocumentation)eventisraisedwhenthehorizontalscrollbarismoved.Thereisnoeventraisedtoindicatethattheuserhasresizedthetabstrip.
Thescrollbarsarecontrolsandsoinheritthebenefitsofthosecontrols.Forexample,therearecontextmenusavailableonboththehorizontalandverticalscrollbarsthatareavailablebydefault.
Thedefaultscrollbarsdonotdisplaythepage,home,orendarrows.
SmoothScrolling
YoucanprovidesmoothscrollingwiththeVerticalScrollBarMode('VerticalScrollBarModeProperty'intheon-linedocumentation)andHorizontalScrollBarMode('HorizontalScrollBarModeProperty'intheon-linedocumentation)properties.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. Select(intheBehaviorcategory)eachofthescrollbarpropertiesandsetthevaluesaccordingly.3. Repeatforeachproperty.
UsingCode
Tosetthescrollbarsforthecomponent,settheFpSpread('FpSpreadClass'intheon-linedocumentation)componentscrollbarproperties.
Example
ThisexamplecreatesanewSpreadcontrolontheformandspecifiesseveralaspectsofthescrollbarsforthecomponent.Scrollbarsappearlargerthanthedefaultsize.Forscrollinghorizontally,thespreadsheetscrollsasyoumovethescrollbox;forscrollingvertically,thescrollbartipshowstherownumber,butthespreadsheetdoesnotscrolluntilyouaredone.
C#FarPoint.Win.Spread.FpSpread fpSpread1 = new FarPoint.Win.Spread.FpSpread();FarPoint.Win.Spread.SheetView shv = new FarPoint.Win.Spread.SheetView();fpSpread1.Location = new Point(10, 10);fpSpread1.Height = 250;fpSpread1.Width = 400;Controls.Add(fpSpread1);fpSpread1.Sheets.Add(shv);fpSpread1.HorizontalScrollBarPolicy = FarPoint.Win.Spread.ScrollBarPolicy.Always;fpSpread1.VerticalScrollBarPolicy = FarPoint.Win.Spread.ScrollBarPolicy.AsNeeded;fpSpread1.HorizontalScrollBarHeight = 30;fpSpread1.VerticalScrollBarWidth = 30;fpSpread1.ScrollBarMaxAlign = true;
Spread Windows Forms Developer’s Guide 200
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.ScrollBarShowMax = true;fpSpread1.ScrollBarTrackPolicy = FarPoint.Win.Spread.ScrollBarTrackPolicy.Horizontal;fpSpread1.ScrollTipPolicy = FarPoint.Win.Spread.ScrollTipPolicy.Vertical;
VBDim FpSpread1 As New FarPoint.Win.Spread.FpSpread()Dim shv As New FarPoint.Win.Spread.SheetView()FpSpread1.Location = New Point(10, 10)FpSpread1.Height = 250FpSpread1.Width = 400Controls.Add(FpSpread1)FpSpread1.Sheets.Add(shv)FpSpread1.HorizontalScrollBarPolicy = FarPoint.Win.Spread.ScrollBarPolicy.AlwaysFpSpread1.VerticalScrollBarPolicy = FarPoint.Win.Spread.ScrollBarPolicy.AsNeededFpSpread1.HorizontalScrollBarHeight = 30FpSpread1.VerticalScrollBarWidth = 30FpSpread1.ScrollBarMaxAlign = TrueFpSpread1.ScrollBarShowMax = TrueFpSpread1.ScrollBarTrackPolicy = FarPoint.Win.Spread.ScrollBarTrackPolicy.HorizontalFpSpread1.ScrollTipPolicy = FarPoint.Win.Spread.ScrollTipPolicy.Vertical
UsingCode
Todisplayallthescrollbarbuttons,settheFpSpread('FpSpreadClass'intheon-linedocumentation)componentscrollbarproperties.
Example
Thisexampleshowsallthescrollbarbuttons.
C#fpSpread1.VerticalScrollBar.Buttons = FarPoint.Win.Spread.ScrollBarButtons.HomeEnd | FarPoint.Win.Spread.ScrollBarButtons.PageUpDown | FarPoint.Win.Spread.ScrollBarButtons.LineUpDown | FarPoint.Win.Spread.ScrollBarButtons.Thumb;fpSpread1.HorizontalScrollBar.Buttons = FarPoint.Win.Spread.ScrollBarButtons.HomeEnd | FarPoint.Win.Spread.ScrollBarButtons.LineUpDown | FarPoint.Win.Spread.ScrollBarButtons.PageUpDown | FarPoint.Win.Spread.ScrollBarButtons.Thumb;
VBFpSpread1.VerticalScrollBar.Buttons = FarPoint.Win.Spread.ScrollBarButtons.HomeEnd Or FarPoint.Win.Spread.ScrollBarButtons.PageUpDown Or FarPoint.Win.Spread.ScrollBarButtons.LineUpDown Or FarPoint.Win.Spread.ScrollBarButtons.ThumbFpSpread1.HorizontalScrollBar.Buttons = FarPoint.Win.Spread.ScrollBarButtons.HomeEnd Or FarPoint.Win.Spread.ScrollBarButtons.LineUpDown Or FarPoint.Win.Spread.ScrollBarButtons.PageUpDown Or FarPoint.Win.Spread.ScrollBarButtons.Thumb
UsingtheSpreadDesigner
1. FromtheSettingsmenu,selectScrollbars.
Spread Windows Forms Developer’s Guide 201
Copyright © GrapeCity, Inc. All rights reserved.
2. IntheScrollBartab,setthedisplayandtrackingbyselectingtheoptions.3. ClickOK.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
or
1. SelecttheSpreadcomponent(orselectSpreadfromthepull-downmenu).2. Inthepropertylistforthecomponent(intheBehaviorcategory),selectoneofthescrollbarproperties.3. Clickthedrop-downarrowtodisplaythechoicesandselectavalue.Repeatthisforeachproperty.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing Scroll Bar Tips
Asanadditionalaidtotheendusers,youcanturnonscrollbartipswhich,bydefault,displaytherownumberwhenthepointerisovertheverticalscrollbarandthecolumnnumberwhenthepointerisoverthehorizontalscrollbar.Inthefollowingfigure,thescrollbartipshowsthecolumnnumberforhorizontalscrolling.
IntheexamplecodeinthetopicCustomizingtheScrollBarsoftheComponent,thescrollbartipsaresetfortheverticalscrollingbutturnedoffforhorizontalscrollingbyusingtheScrollTipPolicy('ScrollTipPolicyProperty'intheon-linedocumentation)propertyintheFpSpread('FpSpreadClass'intheon-linedocumentation)class.
YoucanspecifyhowthescrollbartipsaredisplayedfortheverticalscrollbarusingpropertiesintheScrollingContentInfo('ScrollingContentInfoClass'intheon-linedocumentation)class.Thisallowsyoutospecifythelocationoftheindexnumbersandthemaximumheightfortheverticalscrollbartips.
Youcanalsoshowimageorbuttoncellsinthescrollbartips.Ifyousetthecolumnindicestocolumnswithbuttonorimagecells,thenthecellswillbedisplayedintheverticalscrolltip.Thefollowingimageshowsaverticalscrolltipwithabuttoncell.TheextratextinthescrolltipisaddedusingtheScrollTipFetch('ScrollTipFetchEvent'intheon-linedocumentation)event.Thecolumnindexofzerocausesthebuttoncelltobedisplayedandthecolumnindexoftwocausesthenametobedisplayedinthescrolltip.
YoucanalsocustomizethetextforthescrollbartexttipbyusingtheTipText('TipTextProperty'intheon-linedocumentation)propertyoftheScrollTipFetchEventArgs('ScrollTipFetchEventArgsClass'intheon-linedocumentation)(fortheScrollTipFetchevent).ThiseventcanbeusedwiththesettingsintheScrollingContentInfo('ScrollingContentInfoClass'intheon-linedocumentation)classtocombinethecolumncontentwiththetextsetintheevent(asillustratedintheaboveimage).
Example
Inthisexample,thescrollbartipdisplayscustomtextfortheverticalscrollbaranddefaulttextforthehorizontalscrollbar.
C#private void Form1_Load(object sender, System.EventArgs e){
Spread Windows Forms Developer’s Guide 202
Copyright © GrapeCity, Inc. All rights reserved.
// Display pop-ups when scrolled horizontally/vertically. fpSpread1.ScrollTipPolicy = FarPoint.Win.Spread.ScrollTipPolicy.Both; // Scroll sheets all together. fpSpread1.ScrollBarTrackPolicy = FarPoint.Win.Spread.ScrollBarTrackPolicy.Both;}
private void fpSpread1_ScrollTipFetch(object sender, FarPoint.Win.Spread.ScrollTipFetchEventArgs e){ if (e.Column == -1) { // Customize text to be displayed. e.TipText = "Currently, row " + e.Row.ToString() + " is scrolled."; }}
VBPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Display pop-ups when scrolled horizontally/vertically. FpSpread1.ScrollTipPolicy = FarPoint.Win.Spread.ScrollTipPolicy.Both ' Scroll sheets all together. FpSpread1.ScrollBarTrackPolicy = FarPoint.Win.Spread.ScrollBarTrackPolicy.BothEnd Sub
Private Sub FpSpread1_ScrollTipFetch(ByVal sender As Object, ByVal e As FarPoint.Win.Spread.ScrollTipFetchEventArgs) Handles FpSpread1.ScrollTipFetch If e.Column = -1 Then ' Customize text to be displayed. e.TipText = "Currently, row " + e.Row.ToString + " is scrolled." End IfEnd Sub
Example
Inthisexample,thescrollbartipissetusingtheScrollingContentInfoclass.YoucanalsousetheScrollTipFetcheventcodeintheprevioussamplewiththissample.
C#fpSpread1.ScrollTipPolicy = FarPoint.Win.Spread.ScrollTipPolicy.Both;FarPoint.Win.Spread.ScrollingContentInfo scrollingContentInfo = new FarPoint.Win.Spread.ScrollingContentInfo();scrollingContentInfo.ColumnIndices = "0,2";scrollingContentInfo.MaxHeight = 100;scrollingContentInfo.RowNumberPolicy = FarPoint.Win.Spread.ScrollingContentRowNumberPolicy.Last;fpSpread1.Sheets[0].ScrollingContentInfo = scrollingContentInfo;// The following code creates button cells for the text tip// FarPoint.Win.Spread.CellType.ButtonCellType btest = new FarPoint.Win.Spread.CellType.ButtonCellType();// btest.Text = "test";// fpSpread1.Sheets[0].Columns[0].CellType = btest;
VB
Spread Windows Forms Developer’s Guide 203
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.ScrollTipPolicy = FarPoint.Win.Spread.ScrollTipPolicy.BothDim scrollingContentInfo As New FarPoint.Win.Spread.ScrollingContentInfo()scrollingContentInfo.ColumnIndices = "0,2"scrollingContentInfo.MaxHeight = 100scrollingContentInfo.RowNumberPolicy = FarPoint.Win.Spread.ScrollingContentRowNumberPolicy.LastFpSpread1.Sheets(0).ScrollingContentInfo = scrollingContentInfo' The following code creates button cells for the text tip' Dim btest As New FarPoint.Win.Spread.CellType.ButtonCellType' btest.Text = "test"' FpSpread1.Sheets(0).Columns(0).CellType = btest
Customizing the Sheet Name Tabs of the Component
Ifthereismorethanonesheetintheworkbook,thetabstripdisplaysthesheetnamestabsinatabstripwiththetabfortheactivesheethighlighted.Thesheettabsprovideawayfortheusertonavigatetodifferentsheets.
YoucancustomizehowandiftodisplaythesheetnamesintabsoftheSpreadcomponent.Bydefault,thetabstripisnotdisplayedbecausethereisonlyonesheetinthecomponentuntilmoresheetsareadded.Ifyouaddadditionalsheets,thetabstripbydefaultisthendisplayedshowingthesheetnametabs.
Youcancustomizethefollowingfeaturesforthetabstrip:
DisplayAppearancePlacementWidthPointerdisplayFirsttabdisplayedEvents
Youcancustomizeallthesefeaturesusingcode,andsomecanbesetintheSpreadDesigner.FormoreinformationonhowtoworkwiththetabstripsettingsinSpreadDesigner,refertotheSpreadSettings,GeneralTab(on-linedocumentation)intheSpreadDesignerGuide.
Forgeneralinformation,refertotheseclasses:
FpSpread('FpSpreadClass'intheon-linedocumentation)SheetTab('SheetTabClass'intheon-linedocumentation)TabStrip('TabStripClass'intheon-linedocumentation)
TabStripDisplay
Youcansetthecomponenttoalwaysorneverdisplaythetabstrip,ortodisplayonlywhenthereareatleasttwosheets.Formoreinformationandcodeexamples,refertothesemembers:
FpSpreadclass,TabStripPolicy('TabStripPolicyProperty'intheon-linedocumentation)propertyFpSpreadclass,TabStrip('TabStripProperty'intheon-linedocumentation)propertyTabStripclass,ButtonPolicy('ButtonPolicyProperty'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 204
Copyright © GrapeCity, Inc. All rights reserved.
TabStripButtonPolicy('TabStripButtonPolicyEnumeration'intheon-linedocumentation)enumeration
Note:IfyouareplanningtoexportthecontentsoftheSpreadtoimportintoExcel,donotusecharactersinthesheetnamethatareinvalidinExcel.InvalidExcelsheetnamecharactersinclude:?/\*[]
Formoreinformationonhowtoaddsheetstotheworkbook,refertoAddingaSheet.
TabStripAppearance
Youcancustomizetheappearanceoftheentiretabstripaswellastheindividualsheetnametabs.
Youcansetpropertiesforthetabstripsuchasthebackgroundcolor(settheInterfaceRenderertoNothingornullandvisualstylestoOff)andtextfontforthesheettabs.ThedefaultsheetnamesareSheet1,Sheet2,andsoon.Youcanspecifyothernamesforthesheetsandtheseappearinthesheettabs.Youcanalsoallowtheusertoeditthesheetnames.
Youcancustomizethenameofeachsheet.UsetheSheetName('SheetNameProperty'intheon-linedocumentation)propertyintheSheetView('SheetViewClass'intheon-linedocumentation)class.Formoreinformation,refertothesemembers:
SheetTab('SheetTabClass'intheon-linedocumentation)classmembersTabStrip('TabStripClass'intheon-linedocumentation)classmembers
TabStripPlacement
Youcancustomizewherethetabstripisdisplayedintheoverallcomponent.
PlacementValue SampleShowingPlacementTop(atthetopofthecomponentabovetheheaders)
Spread Windows Forms Developer’s Guide 205
Copyright © GrapeCity, Inc. All rights reserved.
Bottom(underthescrollbaratthebottomofthecomponent)
WithScrollBar(alongsidethescrollbaratthebottomofthecomponent)
Ifthetabstripisplacedatthetopofthesheet,andthegroupingdisplayisturnedon,thetabstripappearsbelowthegroupbarbutabovethecolumnheadersandtherestofthesheet.
Formoreinformationandcodeexamples,refertotheFpSpread('FpSpreadClass'intheon-linedocumentation)classTabStripPlacement('TabStripPlacementProperty'intheon-linedocumentation)property.
TabStripWidth
Youcanspecifythewidthofthetabstripinrelationtotheoverallscrollbarwidth,ifthetabstripandscrollbararedisplayedtogetherinline.
Youcansethowwidethetabstripis,andtherefore,howmanysheettabsaredisplayed.Ifthenumberoftabsexceedsthewidthofthetabstrip,thecomponentdisplaysbuttons.Clickthebuttonstodisplaythenext(orprevious)sheettabs.ThewidthissetbysettingtheFpSpreadTabStripRatio('TabStripRatioProperty'intheon-linedocumentation)property,whichsetsthewidthofthetabstripasapercentageofthelengthoftheentirecomponent.Bydefault,theratioissetto0.50(areaisdivided50%tabstripand50%scrollbar).Formoreinformationonsettingthescrollbarproperties,refertoCustomizingtheScrollBarsoftheComponent.
PointerDisplayoverTabStrip
Youcanspecifythatthepointerchangesappearancewhenitisoverthetabstrip.UsetheTabStripvalueoftheCursorType('CursorTypeEnumeration'intheon-linedocumentation)enumerationtodisplayapointerinthesheettabs.
Spread Windows Forms Developer’s Guide 206
Copyright © GrapeCity, Inc. All rights reserved.
FirstTabinTabStrip
Youcansetwhichsheettabtodisplayastheleft-mosttabwiththeLeftTab('LeftTabProperty'intheon-linedocumentation)propertyoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class.
TabStripEvents
Youcanworkwiththefollowingeventsandeventhandlers.
FpSpreadClass,OnSheetTabClick('OnSheetTabClickMethod'intheon-linedocumentation)MethodandOnSheetTabDoubleClick('OnSheetTabDoubleClickMethod'intheon-linedocumentation)MethodSheetTabClick('SheetTabClickEvent'intheon-linedocumentation)EventSheetTabClickEventArgs('SheetTabClickEventArgsClass'intheon-linedocumentation)ClassSheetTabClickEventHandler('SheetTabClickEventHandlerDelegate'intheon-linedocumentation)DelegateSheetTabDoubleClick('SheetTabDoubleClickEvent'intheon-linedocumentation)EventSheetTabDoubleClickEventArgs('SheetTabDoubleClickEventArgsClass'intheon-linedocumentation)ClassSheetTabDoubleClickEventHandler('SheetTabDoubleClickEventHandlerDelegate'intheon-linedocumentation)Delegate
ThenameoftheeventthatoccurswhenauserclicksonthesheetnametabistheSheetTabClick('SheetTabClickEvent'intheon-linedocumentation)event.
ThetabthattheuserhasclickedcanbedeterminedbygettingtheSheetTabIndex('SheetTabIndexProperty'intheon-linedocumentation)value.Thee.SheetTabIndexeventparameterreturnsthetabthatwasclickedon.
Todisplaythetabnameyoucanuseamessageboxasshowninthiscode:
MsgBox(FpSpread1.Sheets(e.SheetTabIndex).SheetName)
UsingthePropertiesWindow
1. InthePropertieswindow,selecttheSpreadcomponent.2. SpecifythewidthofthetabstripbysettingtheTabStripRatioproperty.3. SpecifywhensheettabsaredisplayedbysettingtheTabStripPolicyproperty.4. SpecifythelocationofthetabstripbysettingtheTabStripPlacementproperty.5. SpecifywhenthebuttonsaredisplayedbyclickingtheTabStripproperty,thensettingtheButtonPolicyproperty.
6. SpecifythebackgroundcolorforthesheettabsbyclickingtheTabStripproperty,thensettingtheBackColorproperty.
UsingaShortcut
1. SpecifythewidthofthetabstripbysettingFpSpread('FpSpreadClass'intheon-linedocumentation)classTabStripRatio('TabStripRatioProperty'intheon-linedocumentation)property.
2. SpecifywhensheettabsaredisplayedbysettingFpSpread('FpSpreadClass'intheon-linedocumentation)classTabStripPolicy('TabStripPolicyProperty'intheon-linedocumentation)property.
3. SpecifywherethetabstripisdisplayedbysettingtheFpSpread('FpSpreadClass'intheon-linedocumentation)classTabStripPlacement('TabStripPlacementProperty'intheon-linedocumentation)property.
4. SpecifywhenthebuttonsaredisplayedbysettingTabStrip('TabStripClass'intheon-linedocumentation)classButtonPolicy('ButtonPolicyProperty'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 207
Copyright © GrapeCity, Inc. All rights reserved.
property.5. SpecifythebackgroundcolorforthesheettabsbysettingTabStrip('TabStripClass'intheon-linedocumentation)classBackColor('BackColorProperty'intheon-linedocumentation)property.
Example
Thisexamplesetsthesheettabstoalwaysappear,setsthetabstripbuttonstoonlyappearasneeded,setsthebackgroundcolorofthesheettabstoBisque,andsetsthewidthofthetabstripto60%.
C#// Set the sheet tabs to always appear.fpSpread1.TabStripPolicy = FarPoint.Win.Spread.TabStripPolicy.Always;// Set the width to 60%.fpSpread1.TabStripRatio = 0.60;// Display the tab strip buttons as needed.fpSpread1.TabStrip.ButtonPolicy = FarPoint.Win.Spread.TabStripButtonPolicy.AsNeeded;// Set the background color.fpSpread1.TabStrip.BackColor = Color.Bisque;fpSpread1.InterfaceRenderer = null;
VB' Set the sheet tabs to always appear.FpSpread1.TabStripPolicy = FarPoint.Win.Spread.TabStripPolicy.Always' Set the width to 60%.FpSpread1.TabStripRatio = 0.60' Display the tab strip buttons as needed.FpSpread1.TabStrip.ButtonPolicy = FarPoint.Win.Spread.TabStripButtonPolicy.AsNeeded' Set the background color.FpSpread1.TabStrip.BackColor = Color.BisqueFpSpread1.InterfaceRenderer = Nothing
UsingCode
1. SpecifythewidthofthetabstripbysettingtheFpSpread('FpSpreadClass'intheon-linedocumentation)classTabStripRatio('TabStripRatioProperty'intheon-linedocumentation)property.
2. SpecifywhensheettabsaredisplayedbysettingtheFpSpread('FpSpreadClass'intheon-linedocumentation)classTabStripPolicy('TabStripPolicyProperty'intheon-linedocumentation)property.
3. CreateanewTabStrip('TabStripClass'intheon-linedocumentation)object,andsetitsvalueequaltotheFpSpread('FpSpreadClass'intheon-linedocumentation)objectTabStrip('TabStripProperty'intheon-linedocumentation)property.
4. SettheTabStrip('TabStripClass'intheon-linedocumentation)objectButtonPolicy('ButtonPolicyProperty'intheon-linedocumentation)propertytospecifywhenthebuttonsaredisplayed,andsetitsBackColor('BackColorProperty'intheon-linedocumentation)propertytospecifythebackgroundcolor.
Example
Thisexamplesetsthesheettabstoalwaysappear,setsthetabstripbuttonstoonlyappearasneeded,setsthebackgroundcolorofthesheettabstoBisque,andsetsthewidthofthetabstripto60%.
C#
Spread Windows Forms Developer’s Guide 208
Copyright © GrapeCity, Inc. All rights reserved.
// Set the sheet tabs to always appear.fpSpread1.TabStripPolicy = FarPoint.Win.Spread.TabStripPolicy.Always;// Set the width to 60%.fpSpread1.TabStripRatio = 0.60;// Create new tab strip.FarPoint.Win.Spread.TabStrip tstrip;tstrip = fpSpread1.TabStrip;// Display the tab strip buttons as needed.tstrip.ButtonPolicy = FarPoint.Win.Spread.TabStripButtonPolicy.AsNeeded;// Set the background color.tstrip.BackColor = Color.Bisque;fpSpread1.InterfaceRenderer = null;
VB' Set the sheet tabs to always appear.FpSpread1.TabStripPolicy = FarPoint.Win.Spread.TabStripPolicy.Always' Set the width to 60%.FpSpread1.TabStripRatio = 0.60' Create new tab strip.Dim tstrip As New FarPoint.Win.Spread.TabStrip()tstrip = FpSpread1.TabStrip' Display the tab strip buttons as needed.tstrip.ButtonPolicy = FarPoint.Win.Spread.TabStripButtonPolicy.AsNeeded' Set the background color.tstrip.BackColor = Color.BisqueFpSpread1.InterfaceRenderer = Nothing
UsingtheSpreadDesigner
1. FromtheSettingsmenu,chooseTabStrip(Appearancesection).2. UnderTabStripPolicy,selectwhenyouwantthesheettabstobedisplayedorselectNevertohidethesheet
tabs.Nomatterwhichitemyouselect,insideSpreadDesignerthesheettabsarealwaysdisplayedtoassistyouindesigningyourcomponent.WhenyouexitSpreadDesignerandapplyyourchanges,youcanseetheeffectofthetabsettingsinyourcomponent,oryoucanseeitbypreviewingthecomponentinsideSpreadDesigner.TopreviewinsideSpreadDesigner,fromtheFilemenuchoosePreview.
3. SetthewidthofthetabstripbysettingthevalueintheSheetTabPercentagebox.4. ClickOKtoclosetheSpreadOptionsdialog.5. SelecttheSpreadobject.6. Inthepropertylist,selecttheTabStrippropertytoseeitsproperties.7. ChangetheButtonPolicypropertyifyouwanttochangewhenthetabstripbuttonsaredisplayed.8. ChangetheBackColorpropertyifyouwanttochangethebackgroundcolorforthetabstrip.9. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing the User Interface Images
Youcancustomizevariousimagesintheuserinterfacebyselectingyourowncustomimagesandapplyingthemtoreplacedefaultimages.Thepartsoftheuserinterfacethatyoucancustomizeare:
Hierarchy(expandingandcollapsing)iconsFilteringindicatorsSortingindicators
Spread Windows Forms Developer’s Guide 209
Copyright © GrapeCity, Inc. All rights reserved.
Rowselector
Todeterminetheimagesforthesepartsoftheuserinterface,usetheGetImage('GetImageMethod'intheon-linedocumentation)andSetImage('SetImageMethod'intheon-linedocumentation)methodsintheSpreadView('SpreadViewClass'intheon-linedocumentation)class.ThevariousfieldsoftheSpreadView('SpreadViewClass'intheon-linedocumentation)classallowyoutospecifytowhichpartoftheinterfacethegraphicimageisassigned.Theseimagescanbesetatruntimeonly,notatdesigntime.
Foranexampleofthesemethodsrefertotheexamplesgivenfortheindividualfields:
CollapseImage('CollapseImageField'intheon-linedocumentation)CollapseImageDisabled('CollapseImageDisabledField'intheon-linedocumentation)ExpandImage('ExpandImageField'intheon-linedocumentation)ExpandImageDisabled('ExpandImageDisabledField'intheon-linedocumentation)FilterActive('FilterActiveField'intheon-linedocumentation)FilterActiveDisabled('FilterActiveDisabledField'intheon-linedocumentation)FilterBarFilterActive('FilterBarFilterActiveField'intheon-linedocumentation)FilterBarFilterDateTime('FilterBarFilterDateTimeField'intheon-linedocumentation)FilterBarFilterInactive('FilterBarFilterInactiveField'intheon-linedocumentation)FilterInactive('FilterInactiveField'intheon-linedocumentation)FilterInactiveDisabled('FilterInactiveDisabledField'intheon-linedocumentation)RowSelectorImage('RowSelectorImageField'intheon-linedocumentation)RowSelectorImageDisabled('RowSelectorImageDisabledField'intheon-linedocumentation)SortAscendingImage('SortAscendingImageField'intheon-linedocumentation)SortAscendingImageDisabled('SortAscendingImageDisabledField'intheon-linedocumentation)SortDescendingImage('SortDescendingImageField'intheon-linedocumentation)SortDescendingImageDisabled('SortDescendingImageDisabledField'intheon-linedocumentation)SortUnsortedImage('SortUnsortedImageField'intheon-linedocumentation)SortUnsortedImageDisabled('SortUnsortedImageDisabledField'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 210
Copyright © GrapeCity, Inc. All rights reserved.
ToresetanimagebacktoaSpreaddefaultimage,simplysettheimagevaluetonullintheSetImage('SetImageMethod'intheon-linedocumentation)method.
Anotherwaytosettheimagesforthefilteringandsortingindicators,istooverridethePaintFilterIndicator('PaintFilterIndicatorMethod'intheon-linedocumentation)andPaintSortIndicator('PaintSortIndicatorMethod'intheon-linedocumentation)methodsintheCellTypeColumnHeaderRenderer('ColumnHeaderRendererClass'intheon-linedocumentation)class.Formoreinformation,referto:
SettingtheAppearanceofFilterIndicatorsSettingtheAppearanceofSortIndicators
Formoreinformationaboutfeatures,seethefollowingtopics:
WorkingwithHierarchicalDataDisplay.AllowingtheUsertoAutomaticallySortRows.UnderstandingSimpleRowFiltering.
Allowing the User to Zoom the Display of the Component
YoucanallowtheusertochangethescaleofthedisplayoftheSpreadcomponent,inotherwordstozoominorzoomout.UsetheAllowUserZoom('AllowUserZoomProperty'intheon-linedocumentation)propertyoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class.ThisallowstheusertozoominoroutbypressingtheCtrlkeyandturningthemousewheel.Theusercanzoominupto400%andoutto10%ofthedefaultdisplay.Thescrollbarsareunaffectedbyzooming;onlythecorner,headers,anddataareachangetheirappearancewithzooming.
UsingtheSpreadDesigner
1. SelecttheViewmenuandthentheZoomoption.2. Setthepercentage.3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexittheSpread
Designer.
Customizing the Scale Mode
Youcanprovidesupportforthe120dpiscalemodeinSpreadwiththeSpreadScaleMode('SpreadScaleModeProperty'intheon-linedocumentation)property.Spreadsupportsresizingrows,columns,cells,anddatabasedonthedpi.
Theautomaticscalingonlyoccurswhentheformisloaded.Thescalingcanchangeatruntimeiftherearechangestothecontrolsizeandlocationandthecontainerlayoutissuspended.
Forthebestresults,settheAutoScaleModepropertyofthecontainertoDpiwhenusingtheZoomDpiSupportoptionoftheSpreadScaleMode('SpreadScaleModeProperty'intheon-linedocumentation)property.
UsingCode
1. Suspendthelayout.2. Setthelocationandsizeforthecontrol.3. SettheSpreadScaleMode('SpreadScaleModeProperty'intheon-linedocumentation)propertytoZoomDpiSupport.
4. UsetheResumeLayout('ResumeLayoutMethod'intheon-linedocumentation)methodtoseethechanges.
Spread Windows Forms Developer’s Guide 211
Copyright © GrapeCity, Inc. All rights reserved.
Example
ThisexamplesetstheSpreadScaleModepropertytoZoomDpiSupportandsuspendsandresumesthelayout.
C#fpSpread.SuspendLayout();
AutoScaleDimensions = new System.Drawing.SizeF(96.0F, 96.0F);AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;fpSpread1.Location = new System.Drawing.Point(23, 86);fpSpread1.Size = new System.Drawing.Size(356, 161);fpSpread1.SpreadScaleMode = FarPoint.Win.Spread.ScaleMode.ZoomDpiSupport;fpSpread1.ResumeLayout();
VBFpSpread1.SuspendLayout()
AutoScaleDimensions = New System.Drawing.SizeF(96.0F, 96.0F)AutoScaleMode = System.Windows.Forms.AutoScaleMode.DpiFpSpread1.Location = New System.Drawing.Point(23, 86)FpSpread1.Size = New System.Drawing.Size(356, 161)FpSpread1.SpreadScaleMode = FarPoint.Win.Spread.ScaleMode.ZoomDpiSupportFpSpread1.ResumeLayout()
Adding a Context Menu to a Component
YoucancreateacontextmenuandaddittotheContextMenupropertyoftheFpSpread('FpSpreadClass'intheon-linedocumentation)component(whichisinheritedfromtheSystem.Windows.Forms.Control).Thecomponentautomaticallydisplaysthismenuofcontext-specificmenuoptionswhenyourightclickonthecomponent.Acontextmenuisalsoknownasashortcutmenu.Formoreinformation,refertotheMicrosoft.NETdocumentationaboutcontextmenu(orshortcutmenu).Thefigureshowsacontextmenuwithtwochoices.Thecodeforthisfigureisshownintheexample.
Thescrollbarshave,bydefault,acontextmenuoftheirown.
UsingCode
1. AddacontextmenuusingtheContextMenuproperty.2. Definethemenuitems.
Atdesigntime,youcouldalsodropinaContextMenufromtheToolboxandlookatthecodegeneratedbythattolearnmore.
Spread Windows Forms Developer’s Guide 212
Copyright © GrapeCity, Inc. All rights reserved.
Example
Thisexamplecreatesacontextmenu.
C#ContextMenu custommenu = new ContextMenu();custommenu.MenuItems.Add("&Table");custommenu.MenuItems.Add("&Color", new EventHandler(ContextMenu_Color));fpSpread1.ContextMenu = custommenu;
private void ContextMenu_Color(object sender, System.EventArgs e){ MessageBox.Show("You chose color.");}
VBDim custommenu As New ContextMenucustommenu.MenuItems.Add("&Table")custommenu.MenuItems.Add("&Color", New EventHandler(AddressOf ContextMenu_Color))FpSpread1.ContextMenu = custommenu
Private Sub ContextMenu_Color(ByVal sender As Object, ByVal e As System.EventArgs) MsgBox("You chose color.")End Sub
Hosting the Component on a Web Page
IfyouarehostingtheSpreadWindowsFormscomponentasausercontrolonaWebpageinMicrosoftInternetExplorer(IE),youshouldmakesecuritypermissionadjustmentsbysettingtheleveloftrust.
ForMicrosoftIE
InMicrosoftIE,selectTools->InternetOptions->SecurityandselectTrustedSites.ClicktheSitesbuttonandaddtheWebsitewhereyourusercontrolresides(forexample,http://localhost).InMicrosoftWindows,selectStart->Settings->ControlPanelandselectAdministrativeTools.SelectMicrosoft.NETFrameworkConfiguration.Inthe.NETFrameworkConfigurationwindow,selectRuntimeSecurityPolicyandclickAdjustZoneSecurity.IntheAdjustZoneSecuritywizard,answerthefirstscreen(whichcomputeritappliesto)andinthenextscreen,clickTrustedSitesandslidetheindicatortogivethatzoneFullTrust.FinishthewizardbyclickingNext.
Customizing Clipboard Operation Options
ThereareseveralClipboardoperations(suchascopy,cut,andpaste)thatareautomaticallysetforasheetwithdefaultsettings;theyarebuilt-intoSpread.ButSpreadalsogivesyoutheabilitytocustomizetheseoperationsonactualapplicationsthatyoudevelop,dependingonyourspecificneeds.YoucancustomizehowtheusercaninteractwiththecontentsoftheClipboardwhenusersperformcopyingandpastingactionsincellsinthespreadsheet.Youcanimplementthoseoperationsatyourdiscretionincode.Thesecustomizationsinclude:
DeactivatingclipboardoperationsExcludingheadersfromclipboardoperationsObtainingtheclipboardcontents
Spread Windows Forms Developer’s Guide 213
Copyright © GrapeCity, Inc. All rights reserved.
DeactivatingpastingChangingthescopeofpastingPerformingtheclipboardoperationsincode
ThefollowingmembersareusedtodetermineClipboard-relatedinteraction:
ClipboardOptions('ClipboardOptionsProperty'intheon-linedocumentation)property(andClipboardOptions('ClipboardOptionsEnumeration'intheon-linedocumentation)enumeration)AutoClipboard('AutoClipboardProperty'intheon-linedocumentation)propertyClipboardCopyOptions('ClipboardCopyOptionsEnumeration'intheon-linedocumentation)enumerationClipboardPasteOptions('ClipboardPasteOptionsEnumeration'intheon-linedocumentation)enumeration
ThespreadsheetmethodsintheSheetView('SheetViewClass'intheon-linedocumentation)classthatinvolveClipboardoperationare:
ClipboardCopy('ClipboardCopyMethod'intheon-linedocumentation),whichcopiesthecontentsfromthesheettotheClipboardClipboardCut('ClipboardCutMethod'intheon-linedocumentation),whichcutsthecontentsfromthesheettotheClipboardClipboardPaste('ClipboardPasteMethod'intheon-linedocumentation),whichpastesthecontentsfromtheClipboardtothesheet
ThecorrespondingshapemethodsintheSheetView('SheetViewClass'intheon-linedocumentation)classthatinvolveClipboardoperationare:
ClipboardCopyShape('ClipboardCopyShapeMethod'intheon-linedocumentation),whichcopiestheactiveshapetotheClipboardClipboardCutShape('ClipboardCutShapeMethod'intheon-linedocumentation),whichcutstheactiveshapetotheClipboardClipboardPasteShape('ClipboardPasteShapeMethod'intheon-linedocumentation),whichpastestheshapefromtheClipboard
IftherearelockedcellsintherangetocutorpastethentheClipboardoperationisnotperformed.
The.NETversionoftheproducthandlesClipboardoperationsdifferentlyfromthewaythattheCOMversiondoes.
YoucanalsosethowsomeClipboard-relatedfeaturesperformwhentheuserisineditmodeinacellontheSpread.Youcansetwhetherthepop-upmenuappearswhileineditmodewithinacellusingtheAutoMenupropertyinSuperEditBaseclassandwhethertheusercanperformClipboardoperationswiththeshortcutkeyswiththeAllowClipboardKeyspropertyinSuperEditBaseclass.
Formoreinformationaboutcopyingandpasting,seeCopyingDataonaSheet.
DeactivatingClipboardOperations
YoucansetwhethertheshortcutkeysareavailabletotheenduserforthemtousetoperformClipboardoperationsbysettingtheAutoClipboardpropertyintheFpSpread('FpSpreadClass'intheon-linedocumentation)class.YoucandeactivatealltheClipboardoperationswithcomponentsbysettingtheAutoClipboardpropertytoFalseintheFpSpread('FpSpreadClass'intheon-linedocumentation)class.ThedefaultsettingisTrue.YoucandeactivatesomeClipboardoperationssuchaspasting(Ctrl+V)bydeactivatingtheinputmapdefinitionforshort-cutkeysandClipboardoperations(Ctrl+C,Ctrl+V,andCtrl+X).
ExcludingHeadersfromClipboardOperations
YoucansetwhethertoincludeheaderswhenusingClipboardoperationsbysettingtheClipboardOptionspropertyin
Spread Windows Forms Developer’s Guide 214
Copyright © GrapeCity, Inc. All rights reserved.
theFpSpread('FpSpreadClass'intheon-linedocumentation)classandtheClipboardOptionsenumeration.Thedefaultsetting,AllHeaders,allowsallheaderstobeincluded.
ObtainingtheClipboardContents
ValueswhicharecopiedonsheetsarecontrolledbytheClipboardclasswhichisprovidedfromthe.NETFramework.YoucanobtainClipboardcontentsbyusingrespectiveoperationsinthisClipboardclass.
CelldataiscopiedontotheClipboardinadvancebycallingClipboardCopymethodintheSheetView('SheetViewClass'intheon-linedocumentation)classattheLoadevent.Then,callingGetDataObjectmethodenablesyoutoobtainthoseClipboardcontentsforuse,suchasfortextformatdetermination.
DeactivatingPasting
TheClipboardPastingeventoccurswhenpastingisperformed(Ctrl+V)onsheets.Youcandeactivatepastingbycancelingthiseventundercertaincircumstances.Youcanpreventpastingbyobtainingthetimingwhenpastingisperformed,andcancelingtheaction.
ChangingtheScopeofPasting
WhencellsarecopiedorcuttotheClipboard,allthedataaspectsincludingvalues,formats,andformulas,areavailablebydefaultforpasting.Youcanconfiguretopastevaluesonly,forexample,bychangingtheinputmapdefinitions.ThedefaultsettingisClipboardPasteAll,whichenablespastingalltheaspectsofthedata.TheClipboardPasteOptionsenumerationallowsyoutosetthescopeofwhatispastedwhenaClipboardpasteisperformedbytheuser.
PerformingtheClipboardOperationsinCode
VariousmethodsareprovidedintheSheetView('SheetViewClass'intheon-linedocumentation)classforClipboardprocesses.Youcanrunthemwhenyouwant.Theseinclude:
ClipboardCopy('ClipboardCopyMethod'intheon-linedocumentation)ClipboardCopyShape('ClipboardCopyShapeMethod'intheon-linedocumentation)ClipboardCut('ClipboardCutMethod'intheon-linedocumentation)ClipboardCutShape('ClipboardCutShapeMethod'intheon-linedocumentation)ClipboardPaste('ClipboardPasteMethod'intheon-linedocumentation)ClipboardPasteShape('ClipboardPasteShapeMethod'intheon-linedocumentation)
Customizing Undo and Redo Actions
Withtheundo/redofeature,youcanaddcapabilitytoyourapplicationtoundovariousactionsinthespreadsheetperformedbyyourenduser.YoucanusetheUndoAction('UndoActionClass'intheon-linedocumentation)classandseveralspecificclassesthatcorrespondwithvarioususeractions.Thereisalsoamanagerclassthatkeepstrackoftheenduseractionsthatcanbeundoneandre-done.
TheSpreadView('SpreadViewClass'intheon-linedocumentation)classandFpSpread('FpSpreadClass'intheon-linedocumentation)classhaveproperties,AllowUndoandUndoManager,whichturnonandofftheundo/redofeatureandreturntheUndoManagerforthatSpreadViewinstance,respectively.EachSpreadViewhasitsownUndoManager.
ActionAssignment
TheUndoAction('UndoActionClass'intheon-linedocumentation)classisanabstractclassthatinheritsfromActionandaddsnewmethodstotheclass:UndoandSaveUndoState.ItalsoinheritsthePerformActionmethodfromAction.
Spread Windows Forms Developer’s Guide 215
Copyright © GrapeCity, Inc. All rights reserved.
SaveUndoStateisusedtosaveundostateinformation(infieldsoftheclass).PerformActionisusedtoperformtheaction.Undoisusedtoreversetheaction(usingtheundostateinformationinthefields).
EachoftheclassesinheritingfromUndoActionisdesignedtodoonespecificaction(forexample,editacell,resizeacolumn,movearange,andsoon),andtoundothataction.Allrelevantinformationtodothatactionshouldbepassedintotheconstructorfortheobject,andallrelevantinformationtoundothatactionshouldbestoredintheSaveUndoStateimplementation.OncetheUndoActionobjectiscreated,thevariablesofthatspecificactionarefixed(specifiedbythevaluespassedtotheconstructor).Forexample,editcellA1insheet1andchangethevalueto"test",resizecolumnBto24pixels,andmovetherangeC4:F6toA1:D:3.Theactioncanonlydothatspecificactioninthatspecificway.
ManagingtheActions
TheUndoManager('UndoManagerClass'intheon-linedocumentation)classmanagestheundoandredostacks.Itkeepstrackofwhichactionshavebeendoneandundone,andinwhatorder.AnUndoActionmustbepassedintothePerformUndoActionmethodofUndoManagertodotheactioninorderforittobeundoablebytheUndoManager.Whenthathappens,theUndoManagerpushestheUndoActionontotheundostackandcallsPerformActionontheUndoAction,andthentheCanUndomethodreturnstrue(indicatingthereissomethingtoundo).WhenCanUndoreturnsfalse,thatmeanstheundostackisempty,andthereisnoactionreadytoundo.YoumightwanttousethistodisabletheUndomenuitemintheEditmenu,forexample,ifyourapplicationhasanEditmenu.
Whenanactionisreadytoundo,youcancallUndoontheUndoManager,anditmovesthelastactionperformedfromtheundostacktotheredostack,andcallsUndoontheaction,andthentheCanRedomethodreturnsTrue(indicatingthereissomethingtoredo).
WhenCanRedoreturnsFalse,thatmeanstheredostackisempty,andthereisnoactionreadytoredo.YoumightwanttousethistodisabletheRedomenuitemintheEditmenu,forexample,ifyourapplicationhasEditmenu.
Whenanactionisreadytoredo,youcancallRedoontheUndoManager,anditmovesthelastactionundonefromtheredostacktotheundostack,andcallsPerformActionontheaction,andtheCanUndomethodreturnstrue.
YoucancallPerformActionontheUndoManagerwithasequenceofUndoActionobjects,anditperformseachactioninsequence,andrememberseachactionandtheorderinwhichtheyaredone.ThenyoucancallUndotoundosomeofthoseactions,andeachcanbere-donewithRedo(andthenun-doneagainwithUndo).
But,whenyoucallPerformActiontoperformanewaction,ifthereareanyactionspendingintheredostack,thoseactionsarecleared,andCanRedoreturnsFalse(thatis,onceyouperformanewaction,youwillnotbeabletoredoanyactionsthatyouhaveundonewithUndo).ThatiswhythePushUndomethodintheUndoManagerclasshasaflagtoindicatewhethertheredostackshouldbeclearedwhentheactionispushedontotheundostack.
SomeoftheUndoActionclasseswillbereplacingActionobjectsintheactionmaps,sothatthoseactionsareroutedthroughtheUndoManagerandbecomeundoable.OtherUndoActionclasseswillnotbepartoftheactionmaps,butinsteadareusedintheSheetVieworSpreadViewcodetomaketheactionundoable.
OtherAPIUpdates
TheinputmapsincludenewitemstomaptheCtrl+ZandCtrl+YkeystothenewUndoActionandRedoActionactionobjects,respectively.TheseactionsmakecallsintotheUndoManagertotheUndoandRedomethods,respectively.
Locating the Pointer Using HitTest
YoucanlocatethepointeratanytimeincodeusingtheHitTestmethodoftheSpreadcomponent.Whetheryouaremeetingaccessibilitystandardsanddisplayinginformationfortheuserbasedonpointerlocation,orwanttoprovideadditionalsupportbasedonpointerlocation,youcanusethiscapabilitytocustomizethedisplayanduserinteraction.
Thelistofmemberscorrespondingtothiscapabilityarelistedhere:
Component ClassName
Spread Windows Forms Developer’s Guide 216
Copyright © GrapeCity, Inc. All rights reserved.
AreaSpreadcomponent FpSpread.HitTest('HitTestMethod'intheon-linedocumentation)method
Spreadcomponent HitTestType('HitTestTypeEnumeration'intheon-linedocumentation)enumeration
Spreadcomponent HitTestInformation('HitTestInformationClass'intheon-linedocumentation)class
Roworcolumnheader
HeaderHitTestInformation('HeaderHitTestInformationClass'intheon-linedocumentation)class
Outline(rangegroup)area
RangeGroupHitTestInformation('RangeGroupHitTestInformationClass'intheon-linedocumentation)class
Tabstrip TabStripHitTestInformation('TabStripHitTestInformationClass'intheon-linedocumentation)class
Viewport ViewportHitTestInformation('ViewportHitTestInformationClass'intheon-linedocumentation)class
Customizing Interaction Based on Events
YoucancustomizehowtheSpreadcomponentrespondstouser-initiatedevents.IntheFpSpread('FpSpreadClass'intheon-linedocumentation)classthereareseveralevents,fromButtonClicked('ButtonClickedEvent'intheon-linedocumentation)toLeaveCell('LeaveCellEvent'intheon-linedocumentation)toSelectionChanged('SelectionChangedEvent'intheon-linedocumentation).Useeventsthatcorrespondtouseractionstoinitiateresponses.Foralistofeventsinthecomponent,refertotheFpSpread('FpSpreadClass'intheon-linedocumentation)classmembers.Foreventsavailableforthesheet,refertotheSheetView('SheetViewClass'intheon-linedocumentation)classmembers.Foralistofeventsthatcanbeusedwhileineditmode,refertotheFarPoint.Win.SuperEditBase('FarPoint.Win.SuperEditNamespace'intheon-linedocumentation)class.
TheFpSpreadclassisderivedfromtheControlclassthathasthefollowingpropertiesandeventsthatarerelevanttoourunderstandingofeventsinSpread:
TextpropertyandTextChangedeventClickeventEnterevent
TheTextpropertyandTextChangedeventareusedbysimplecontrolsthathaveasingleTextattribute(forexample,theTextBoxcontrol).TheSpreadcomponentisamorecomplexcontrolthatconsistsofrowsandcolumnsofcells.EachcellhasitsownTextproperty.TheTextpropertyofthecellisseparatefromtheTextpropertyoftheSpreadcomponent.SincetheSpreadcomponentdoesnotusethecomponent’sTextproperty,theTextChangeeventisneverraised.
TheClickeventisusedbysimplecontrolsthathaveasinglearea(forexample,theButtoncontrol).TheSpreadcomponentisamorecomplexcontrolthatconsistsofrowsandcolumnsofcells.TheSpreadcomponentraisesaCellClickeventinsteadofaClickevent.TheCellClick('CellClickEvent'intheon-linedocumentation)eventcontainsmoredetailedinformationthantheClickevent.
TheEntereventisraisedwhenkeyboardfocusismovedfromanothercontrolontheformtotheSpreadcomponent.
Handling Events of Subeditors
YoucanhandleeventsofsubeditorswithinacellintheSpreadcomponent.
ThesubeditorhasaSubEditorClosed('SubEditorClosedEvent'intheon-linedocumentation)eventandaSubEditorOpening('SubEditorOpeningEvent'intheon-linedocumentation)event.Thisallowsyoutoknow
Spread Windows Forms Developer’s Guide 217
Copyright © GrapeCity, Inc. All rights reserved.
whenthesubeditoropensandcloses.
Thecelltypebringsupaneditorwheneditingthecell.Theeditorcontrolcanbetextbasedorgraphicsbased.Theeditorcontrolcandrop-downlists,bringuppop-updialogs,andsoon.Thedrop-downlistorpop-updialogisknownasthesubeditor.TheISubEditor('ISubEditorInterface'intheon-linedocumentation)interfacecanbeusedtocreateacustomsubeditor.TheIEditor('IEditorInterface'intheon-linedocumentation)interfacecanbeusedtocreateacustomeditor.
Existingeditorscanbeusedincells.Thefollowingcodeusesthedefaultdatetimecellformattingoncell(1,1):
C#fpSpread1.Sheets[0].Cells[1, 1].Editor = new FarPoint.Win.Spread.CellType.DateTimeCellType();
VisualBasicFpSpread1.Sheets(0).Cells(1,1).Editor = New FarPoint.Win.Spread.CellType.DateTimeCellType
Customizing the User Error Messages
Youcansettheerrormessagesthatthecomponentdisplayswhentheuserperformsinvalidactions.Todeterminethedisplayoferrormessages,usetheEditError('EditErrorEvent'intheon-linedocumentation)eventandtheEditError('EditErrorEnumeration'intheon-linedocumentation)enumeration.
Customizing Interaction with a Sheet
Youcancustomizeaspectsoftheviewofanindividualsheetthatprovidewaysfortheusertointeractwiththesheet.Tocustomizethisaspectofuserinteraction,youcanperformanyofthefollowingtasks:
CustomizingViewportsCustomizingSplitBoxesCustomizingthePositionintheDisplayPlacingChildControlsonaSheetCreatingTables
Youcanalsoallowaspectsoftheuserinteractionthataredescribedelsewhereinthedocumentation,includingthefollowingfeaturesthatworkwithanentiresheet:
CustomizingtheSheetNameTabsoftheComponentRearrangingDataonaSheetCustomizingUserSearchingofDataWorkingwithHierarchicalDataDisplayCustomizingDrawingLockingaCellCustomizingInteractioninCellsCustomizingtheIndividualSheetAppearance
Customizing Viewports
Youcandivideupthedisplayintoseparatelyscrollableviewports.Youcansetupthefollowingconfigurations:
Asetofhorizontalviewports(calledaviewportrowsinceitisarowofviewports)
Spread Windows Forms Developer’s Guide 218
Copyright © GrapeCity, Inc. All rights reserved.
Asetofverticalviewports(calledaviewportcolumnsinceitisacolumnofviewports)Asetofboth(asshowninthefollowingfigure)
Theviewportsallowyoutodisplaydifferentpartsofaverylargespreadsheetinaverylimitedviewingarea.Youcanadd,remove,andcustomizeviewportsprogrammatically,andyoucanallowyourendusertocreateanduseviewports.
Foranendusertocreateaviewport,theendusercanclickonthesplitboxanddragittothedesiredlocation.Toallowtheendusertodividethedisplay,setthepolicyfordisplayingthesplitboxes.Theendusercancreatemultipleviewportsineitherorientation.Youcanallowsplitbarsinonlyoneorientationbysettingthepolicytodisplayonlythesplitboxinthatorientation.Formoreinformationonsplitboxes,refertoCustomizingSplitBoxes.Thefigurebelowshowshowtocreateaviewport.
Thesplitbarsshowtheborderofeachviewport.Eachviewportroworviewportcolumnhasitsownscrollbars.
Spread Windows Forms Developer’s Guide 219
Copyright © GrapeCity, Inc. All rights reserved.
Thescrollbarmustbevisibleforthesplitboxestobeaccessible.Formoreinformationaboutscrollbars,refertoCustomizingtheScrollBarsoftheComponent.
Toremoveasplitbar,theendusercaneitherdouble-clickonthesplitbarorclickanddragitallthewaytotheedgeofthesheet.
Thereareseveralpropertiesandmethodsthatrelatetotheuseofviewports;manyoftheseprovidecustomizationsprogrammaticallyassummarizedinthistable.
Customization MethodorPropertyinFpSpread(orSpreadView)class
Addandremoveviewports AddViewport('AddViewportMethod'intheon-linedocumentation)
RemoveViewport('RemoveViewportMethod'intheon-linedocumentation)
Settheheightandwidthofviewports SetViewportPreferredHeight('SetViewportPreferredHeightMethod'intheon-linedocumentation)
SetViewportPreferredWidth('SetViewportPreferredWidthMethod'intheon-linedocumentation)
GetViewportPreferredHeight('GetViewportPreferredHeightMethod'intheon-linedocumentation)
GetViewportPreferredWidth('GetViewportPreferredWidthMethod'intheon-linedocumentation)
Determinetheviewportforagivenlocationinthedisplay
GetViewPortX('GetViewportXMethod'intheon-linedocumentation)
GetViewPortY('GetViewportYMethod'intheon-linedocumentation)
GetViewPortHeight('GetViewportHeightMethod'intheon-linedocumentation)
GetViewPortWidth('GetViewportWidthMethod'intheon-linedocumentation)
Determinetheroworcolumnofcellsinaparticularviewportroworviewportcolumn
GetViewportBottomRow('GetViewportBottomRowMethod'intheon-linedocumentation)
GetViewportLeftColumn('GetViewportLeftColumnMethod'intheon-linedocumentation)
GetViewportRectangle('GetViewportRectangleMethod'intheon-linedocumentation)
GetViewportTopRow('GetViewportTopRowMethod'intheon-linedocumentation)
SetViewportLeftColumn('SetViewportLeftColumnMethod'intheon-linedocumentation)
SetViewportTopRow('SetViewportTopRowMethod'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 220
Copyright © GrapeCity, Inc. All rights reserved.
Determinewhichistheactiveviewport GetActiveColumnViewportIndex('GetActiveColumnViewportIndexMethod'intheon-linedocumentation)
GetActiveRowViewportIndex('GetActiveRowViewportIndexMethod'intheon-linedocumentation)
SetActiveViewport('SetActiveViewportMethod'intheon-linedocumentation)
Determinetheindexofaparticularviewportroworviewportcolumn
GetColumnViewportIndexFromX('GetColumnViewportIndexFromXMethod'intheon-linedocumentation)
GetRowViewportIndexFromY('GetRowViewportIndexFromYMethod'intheon-linedocumentation)
Determinethenumberofviewportsineitherorientation
GetColumnViewportCount('GetColumnViewportCountMethod'intheon-linedocumentation)
GetRowViewportCount('GetRowViewportCountMethod'intheon-linedocumentation)
Positiontheviewportinthedisplay ShowColumn('ShowColumnMethod'intheon-linedocumentation)
ShowRow('ShowRowMethod'intheon-linedocumentation)
Thepreferredheightandpreferredwidtharesuggestedsizes.TheSpreadcomponentattemptstolayouttheviewportsascloseaspossibletothesuggestedsizes.However,ifthesumofthesuggestedsizesislarger(orsmaller)thanthesizeofthecomponentthentheactualsizesofoneormoreoftheviewportsmustbelarger(orsmaller)thanthesuggestedsize.
Thepreferredheightandpreferredwidthcansetto-1orapositivenumber.A-1indicatesavariablesize.Apositivenumberindicatesafixedsizeinpixels.Whenthecomponentlaysouttheviewports,availablespaceisfirstallocatedforthefixed-sizeviewports.Anyremainingspaceisevenlydividedamongthevariable-sizedviewports.
TheColumnViewportWidthChanged('ColumnViewportWidthChangedEvent'intheon-linedocumentation)andtheRowViewportHeightChanged('RowViewportHeightChangedEvent'intheon-linedocumentation)eventsareraisedanytimethesplitboxesaremovedbytheenduser.Theseeventsarenotraisedwhenyouaddaviewportprogrammatically;theyareraisedonlywhentheuserchangesthewidthorheightofaviewport.
Forfrozenrowsandcolumns,thefrozenroworcolumnisaseparateviewport.Theleadingfrozenroworcolumnisaseparateviewportwhilethetrailingfrozenroworcolumnisalsoaseparateviewport.Indexesforthefrozenviewportsare:
Index FrozenViewport-1 Leadingfrozen
0 Firstscrollable
1 Secondscrollable
n-1 Lastscrollable
n Trailingfrozen
Formoreinformationaboutfrozenrowsandcolumns,refertoSettingFixed(Frozen)RowsorColumns.
Spread Windows Forms Developer’s Guide 221
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
Tocreateorcustomizeaviewportincode,usethefollowingaddandsetmethodsintheFpSpread('FpSpreadClass'intheon-linedocumentation)class.Refertotheprecedingtablefordescriptionsofthese.RefertotheAssemblyReference(on-linedocumentation)formoredetailsoneach.
AddViewport('AddViewportMethod'intheon-linedocumentation)RemoveViewport('RemoveViewportMethod'intheon-linedocumentation)GetViewportPreferredWidth('GetViewportPreferredWidthMethod'intheon-linedocumentation)andSetViewportPreferredWidth('SetViewportPreferredWidthMethod'intheon-linedocumentation)GetViewportPreferredHeight('GetViewportPreferredHeightMethod'intheon-linedocumentation)andSetViewportPreferredHeight('SetViewportPreferredHeightMethod'intheon-linedocumentation)SetActiveViewport('SetActiveViewportMethod'intheon-linedocumentation)
Formoreinformation,refertomethodsintheFpSpread('FpSpreadClass'intheon-linedocumentation)class.
Example
Thisexampleaddsaviewportandsetsitsvariousproperties.
C#fpSpread1.AddViewport(1, 2);fpSpread1.SetViewportLeftColumn(1, 3);fpSpread1.SetViewportTopRow(0, 6);fpSpread1.SetViewportPreferredHeight(0, 100);fpSpread1.SetViewportPreferredWidth(0, 100);
VBFpSpread1.AddViewport(1, 2)FpSpread1.SetViewportLeftColumn(1, 3)FpSpread1.SetViewportTopRow(0, 6)FpSpread1.SetViewportPreferredHeight(0, 100)FpSpread1.SetViewportPreferredWidth(0, 100)
UsingtheSpreadDesigner
1. SelecttheSpreadcomponent(orselectSpreadfromthepull-downmenu).2. Inthemainwindow,selectthesplitboxesfromtheedgeofthescrollbarsanddragthemeachtothepositionto
createtheviewportsasneeded.3. FromtheSettingsmenu,choosePreferencesandselectSaveSplitBarsonApplytoallowSpreadDesigner
tosavetheseviewportswhenyouapplythechanges.Somedeveloperscreatesplitbarsforviewingcertainaspectsoftheirspreadsheet,butdonotwantthemsaved.
4. FromtheFilemenu,chooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing Split Boxes
Youcandeterminethedisplayandplacementofthesplitboxes.Bydefault,thesplitboxesareshownandappearattheleadingedgeofeachofthescrollbars,asshowninthefigurebelow.YoucanchangethesebysettingapropertyorbyusingSpreadDesigner.
Spread Windows Forms Developer’s Guide 222
Copyright © GrapeCity, Inc. All rights reserved.
Whentheenduserclicksanddragsthesplitbox,theviewissplitintoseparateviewports.Formoreinformationonviewports,refertoCustomizingViewports.
Customization PropertyandEnumerationPlacementofsplitboxrelativetothescrollbar
ColumnSplitBoxAlignment('ColumnSplitBoxAlignmentProperty'intheon-linedocumentation)propertyinFpSpread('FpSpreadClass'intheon-linedocumentation)class
RowSplitBoxAlignment('RowSplitBoxAlignmentProperty'intheon-linedocumentation)propertyinFpSpread('FpSpreadClass'intheon-linedocumentation)class
SplitBoxAlignment('SplitBoxAlignmentEnumeration'intheon-linedocumentation)enumeration
Whetherorwhentodisplaythesplitbox
ColumnSplitBoxPolicy('ColumnSplitBoxPolicyProperty'intheon-linedocumentation)propertyinFpSpread('FpSpreadClass'intheon-linedocumentation)class
RowSplitBoxPolicy('RowSplitBoxPolicyProperty'intheon-linedocumentation)propertyinFpSpread('FpSpreadClass'intheon-linedocumentation)class
SplitBoxPolicy('SplitBoxPolicyEnumeration'intheon-linedocumentation)enumeration
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.
Spread Windows Forms Developer’s Guide 223
Copyright © GrapeCity, Inc. All rights reserved.
2. Select(intheSplitterscategory)theColumnSplitBoxAlignment,RowSplitBoxAlignment,ColumnSplitBoxPolicy,orRowSplitBoxPolicyproperty.
3. Clickthedrop-downarrowtodisplaythechoicesandselectthevalue.Repeatthisforeachproperty.
UsingCode
SettheColumnSplitBoxAlignment('ColumnSplitBoxAlignmentProperty'intheon-linedocumentation),RowSplitBoxAlignment('RowSplitBoxAlignmentProperty'intheon-linedocumentation),ColumnSplitBoxPolicy('ColumnSplitBoxPolicyProperty'intheon-linedocumentation),andRowSplitBoxPolicy('RowSplitBoxPolicyProperty'intheon-linedocumentation)propertiesfortheroworcolumnofviewportsfortheFpSpread('FpSpreadClass'intheon-linedocumentation)component.
Example
Inthisexample,thesplitboxforthecolumnsisattheleadingedgeofthescrollbarandisdisplayedasneeded;fortherows,thesplitboxisatthetrailingedgeofthescrollbarandisalwaysdisplayed.
C#fpSpread1.ColumnSplitBoxAlignment = FarPoint.Win.Spread.SplitBoxAlignment.Leading;fpSpread1.RowSplitBoxAlignment = FarPoint.Win.Spread.SplitBoxAlignment.Trailing;fpSpread1.ColumnSplitBoxPolicy = FarPoint.Win.Spread.SplitBoxPolicy.AsNeeded;fpSpread1.RowSplitBoxPolicy = FarPoint.Win.Spread.SplitBoxPolicy.Always;
VBFpSpread1.ColumnSplitBoxAlignment = FarPoint.Win.Spread.SplitBoxAlignment.LeadingFpSpread1.RowSplitBoxAlignment = FarPoint.Win.Spread.SplitBoxAlignment.TrailingFpSpread1.ColumnSplitBoxPolicy = FarPoint.Win.Spread.SplitBoxPolicy.AsNeededFpSpread1.RowSplitBoxPolicy = FarPoint.Win.Spread.SplitBoxPolicy.Always
UsingtheSpreadDesigner
1. FromtheSettingsmenu,selectSplitBox.2. IntheSplitBoxtab,setthevaluesfortheColumnSplitBoxAlignment,RowSplitBoxAlignment,ColumnSplitBoxPolicy,orRowSplitBoxPolicyproperty.
3. ClickOK.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
or
1. SelecttheSpreadcomponent(orselectSpreadfromthepull-downmenu).2. Inthepropertylistforthecomponent(intheSplitterscategory),selecttheColumnSplitBoxAlignment,RowSplitBoxAlignment,ColumnSplitBoxPolicy,orRowSplitBoxPolicyproperty.
3. Clickthedrop-downarrowtodisplaythechoicesandselectthevalue.Repeatthisforeachproperty.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing the Position in the Display
Youcancustomizethepositionofthedataareaofthespreadsheetinthedisplaybychoosingarow,column,orcell,andmovingittoaparticularpositioninthedisplayedportionofthespreadsheetintheSpreadcomponent.
UsetheShowRow('ShowRowMethod'intheon-linedocumentation),ShowColumn('ShowColumnMethod'intheon-linedocumentation),ShowCell('ShowCellMethod'intheon-linedocumentation),orShowActiveCell('ShowActiveCellMethod'intheon-linedocumentation)methodsintheFpSpread
Spread Windows Forms Developer’s Guide 224
Copyright © GrapeCity, Inc. All rights reserved.
('FpSpreadClass'intheon-linedocumentation)class,andtheHorizontalPosition('HorizontalPositionEnumeration'intheon-linedocumentation)andVerticalPosition('VerticalPositionEnumeration'intheon-linedocumentation)enumerations.Thesemethodsscrollthedisplayuntilthespecifieditemisdisplayedinthespecifiedlocation.
UsingCode
SettheShowActiveCell('ShowActiveCellMethod'intheon-linedocumentation)method.
Example
Thisexamplesetstheactivecellandthendisplaysthecellinthetop,centerofthespreadsheet.
C#fpSpread1.Sheets[0].SetActiveCell(3,4);fpSpread1.ShowActiveCell(FarPoint.Win.Spread.VerticalPosition.Top, FarPoint.Win.Spread.HorizontalPosition.Center);
VBFpSpread1.Sheets(0).SetActiveCell(3,4)FpSpread1.ShowActiveCell(FarPoint.Win.Spread.VerticalPosition.Top, FarPoint.Win.Spread.HorizontalPosition.Center)
Placing Child Controls on a Sheet
Youcanplacecontrolsonasheet(notjusttheFpSpreadcomponentbutaspecificsheet)toprovidemoreinteractionwiththeuser.UsetheAddControl('AddControlMethod'intheon-linedocumentation)methodfortheSpreadcomponentorthesheet.AnythingthatcanbederivedfromtheControlclassinthe.NETframeworkcanbehostedonasheetinSpread.YoumustimplementtheIEmbeddedControlinterfaceandsetthefollowing:
ActivationPolicy('ActivationPolicyProperty'intheon-linedocumentation)-determineshowtheusercanactivatetheobjectCanMove('CanMoveProperty'intheon-linedocumentation)-determineswhethertheusercanmovetheobjectonceplacedCanSize('CanSizeProperty'intheon-linedocumentation)-determineswhethertheusercansizetheobjectonceplacedControlPaint('ControlPaintMethod'intheon-linedocumentation)-determineshowtheobjectisrepresentedwhennotactive;similartothepaintmethodforacell
Thechildcontrolisplacedonasheet,accordingtotheactivecell,butisnotanchoredtothatcell.Onceplaced,thecontrolhasanabsolutepositionthatdoesnotchangewhenthesheetischangedorthecelliseithermovedorremoved.Thechildcontrolisplacedonaseparatelayer,thecontrolslayer,whichisseparatefromthedataarea(onwhichcellswithdataappear)andisseparatefromthedrawinglayer(onwhichshapesandothergraphicalelementsappear).
Spread Windows Forms Developer’s Guide 225
Copyright © GrapeCity, Inc. All rights reserved.
WiththeAllowChildControlDesign('AllowChildControlDesignProperty'intheon-linedocumentation)property(inFpSpread),youcandeterminewhethertheusercaninteractwiththechildcontrolindesignmode.Whendesignisallowed,thecontrolcangetfocusanddisplaysgrabhandlestoallowmovingandsizing,anddisplaysahighlightbordertoindicateitisinfocus.Whenthedesignisnotallowed,thecontrolsimplyisalivecontrolthatrespondstotheuserclickingonit(orwhateverpolicyissetwiththeActivationpropertyofIEmbeddedControlSupport('IEmbeddedControlSupportInterface'intheon-linedocumentation).
Thechildcontrolisoneofanynumberofcontrolsthatcanbeplacedonthesheet.Forthesheetthereisachildcontrolcontainer(similartotheshapecontainerforalltheshapesonthesheet).Youcanenumeratethrougheachcontrolandoverrideanypropertyoftheinterfaceofthatcontrol.Youcanseteventsandworkwitheventhandlers.
Thechildcontrolslayerisavailableonlyatruntime.ThisfeatureisnotavailableinthestandaloneversionoftheSpreadDesigner.
SomecustomizationoftheunderlyingSystem.Controlclassmaybeneededtomaketheembeddedchildcontrolstoappearproperlyinyourapplication.
Formoreinformationontheinterfaceandpolicyenumerationofthechildcontrollayer,refertothese:
IEmbeddedControlSupport('IEmbeddedControlSupportInterface'intheon-linedocumentation)ChildActivationPolicy('ChildActivationPolicyEnumeration'intheon-linedocumentation)
Formoreinformationonthemethodsandpropertiesofthechildcontrollayeronthesheet,refertothese:
SheetView.AddControl('AddControlMethod'intheon-linedocumentation)SheetView.ClearControls('ClearControlsMethod'intheon-linedocumentation)SheetView.GetControl('GetControlMethod'intheon-linedocumentation)SheetView.GetControlContainer('GetControlContainerMethod'intheon-linedocumentation)SheetView.RemoveControl('RemoveControlMethod'intheon-linedocumentation)
FormoreinformationonthemethodsandpropertiesofthechildcontrollayerfortheSpreadcomponent,refertothese:
FpSpread.ChildControlActivated('ChildControlActivatedEvent'intheon-linedocumentation)FpSpread.ChildControlDeactivated('ChildControlDeactivatedEvent'intheon-linedocumentation)FpSpread.AddControl('AddControlMethod'intheon-linedocumentation)FpSpread.AllowChildControlDesign('AllowChildControlDesignProperty'intheon-linedocumentation)FpSpread.RemoveControl('RemoveControlMethod'intheon-linedocumentation)
Creating Tables
Spread Windows Forms Developer’s Guide 226
Copyright © GrapeCity, Inc. All rights reserved.
Youcancreateatablefromarangeofcellstomakemanagingandanalyzingagroupofrelateddataeasier.Atabletypicallycontainsrelateddatainrowsandcolumns.Youcanmanagethedatainthetablerowsandcolumnsindependentlyfromthedatainotherrowsandcolumnsonthesheet.
Atablecancontainaheaderrow,bandedrows,calculatedcolumns,atotalrow,andasizinghandle.Theheaderrowcontainsiconsthatallowyoutofilterorsortthetabledataquickly.Bandedrowsarealternaterowsthathaveshadingappliedsothatthedataiseasiertoview.Youcancreateacalculatedcolumnbyenteringaformulainonecellinatablecolumn.Thiscreatesacalculatedcolumninwhichthatformulaisinstantlyappliedtoallothercellsinthattablecolumn.Youcanaddatotalrowtoyourtablethatprovidesaccesstosummaryfunctions(suchastheAVERAGE,COUNT,orSUMfunction).Adrop-downlistappearsineachtotalrowcellsothatyoucanquicklycalculatethetotalsthatyouwant.Asizinghandleinthelower-rightcornerofthetableallowsyoutochangethetablesize.
Thefollowingimageillustratesthemaintableelements.
Youcanalsomovetablesandcreatestructuredreferencesintables.
Formoreinformation,seethefollowingtopics:
AddingaTable
UsingTableFilters
ResizingaTable
SortingaTable
SettingTableStyles
AddingaTableFormula
UnderstandingStructuredReferences
Adding a Table
Youcanaddatabletoasheetusingcodeorthedesigner.YoucantypedatainthetablecellsoraddtexttothecellswiththeText('TextProperty'intheon-linedocumentation)orValue('ValueProperty'intheon-linedocumentation)property.
Spread Windows Forms Developer’s Guide 227
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
UsetheAddTable('AddTableMethod'intheon-linedocumentation)methodtoaddatabletoasheet.
Example
Thisexamplecodeaddsatableusingcelldata.
C#fpSpread1.Sheets[0].Cells[1, 1].Text = "Last Name";fpSpread1.Sheets[0].Cells[1, 2].Text = "Value";fpSpread1.Sheets[0].Cells[2, 1].Text = "Smith";fpSpread1.Sheets[0].Cells[2, 2].Value = 50;fpSpread1.Sheets[0].Cells[3, 1].Text = "Vil";fpSpread1.Sheets[0].Cells[3, 2].Value = 10;fpSpread1.Sheets[0].Cells[4, 1].Text = "Press";fpSpread1.Sheets[0].Cells[4, 2].Value = 78;fpSpread1.Sheets[0].AddTable("table", 1, 1, 5, 2);
VBFpSpread1.Sheets(0).Cells(1, 1).Text = "Last Name"FpSpread1.Sheets(0).Cells(1, 2).Text = "Value"FpSpread1.Sheets(0).Cells(2, 1).Text = "Smith"FpSpread1.Sheets(0).Cells(2, 2).Value = 50FpSpread1.Sheets(0).Cells(3, 1).Text = "Vil"FpSpread1.Sheets(0).Cells(3, 2).Value = 10FpSpread1.Sheets(0).Cells(4, 1).Text = "Press"FpSpread1.Sheets(0).Cells(4, 2).Value = 78FpSpread1.Sheets(0).AddTable("table", 1, 1, 5, 2)
UsingtheSpreadDesigner
1. Intheworkarea,selectthecellrangewhereyouwanttoaddthetable.2. FromtheInsertmenu,selectTable.3. ProvidethecellrangeforthetableandselectOK.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Using Table Filters
Youcanuseenhancedfilteringwithtables.
Thedefaultfilterthatisdisplayeddependsonthedatainthecolumn.Thefiltercanbeanumber,text,date,orcolorfilter.Thefollowingimagedisplaysthemenusforsettingupatextfilter.
Spread Windows Forms Developer’s Guide 228
Copyright © GrapeCity, Inc. All rights reserved.
Youcanalsotypeinthesearchboxinthefilterdialogtochangethelistoffilteroptions.Thefollowingimagedisplaysthesearchboxandthefilterchoicesaftertypingcharactersinthesearchbox.
Thefiltersaredescribedinthefollowingtable.
TypeofFilters DescriptionNumberFilters
Equals Valuesinrowsareequaltocondition
Spread Windows Forms Developer’s Guide 229
Copyright © GrapeCity, Inc. All rights reserved.
DoesNotEqual Valuesinrowsdonotequalcondition
GreaterThan Valuesinrowsaregreaterthancondition
GreaterThanOrEqualTo Valuesinrowsaregreaterthanorequaltocondition
LessThan Valuesinrowsarelessthancondition
LessThanOrEqualTo Valuesinrowsarelessthanorequaltocondition
Between Valuesinrowsaregreaterthanoneconditionandlessthananothercondition
Top10 Valuesintherowswiththetenhighestvalues
AboveAverage Valuesintherowsthatareabovetheaverageofthevaluesinalltherows
BelowAverage Valuesintherowsthatarebelowtheaverageofthevaluesinalltherows
CustomFilter Valuesinrowsthatmeettheconditionsofacustomfilter
TextFilters
Equals Valuesinrowsequalthecondition
DoesNotEqual Valuesinrowsdonotequalthecondition
BeginsWith Valuesinrowsbeginwiththespecifiedcharacters
EndsWith Valuesinrowsendwiththespecifiedcharacters
Contains Valuesinrowscontainthespecifiedcharacters
DoesNotContain Valuesinrowsdonotcontainthespecifiedcharacters
CustomFilter Valuesinrowsthatmeettheconditionsofacustomfilter
DateFilters
Equals Valuesinrowsequalthecondition
Before Valuesinrowsaredatesbeforethecondition
After Valuesinrowsaredatesafterthecondition
Between Valuesinrowsaredatesbetweentwospecifieddatesforthecondition
Tomorrow Valuesinrowsaretomorrow'sdate
Today Valuesinrowsaretoday'sdate
Yesterday Valuesinrowsareyesterday'sdate
NextWeek Valuesinrowsareduringnextweek
ThisWeek Valuesinrowsareduringcurrentweek
LastWeek Valuesinrowsareduringlastweek
NextMonth Valuesinrowsareduringnextmonth
ThisMonth Valuesinrowsareduringcurrentmonth
LastMonth Valuesinrowsareduringlastmonth
NextQuarter Valuesinrowsareduringnextquarter
ThisQuarter Valuesinrowsareduringcurrentquarter
LastQuarter Valuesinrowsareduringlastquarter
NextYear Valuesinrowsareduringnextyear
ThisYear Valuesinrowsareduringcurrentyear
Spread Windows Forms Developer’s Guide 230
Copyright © GrapeCity, Inc. All rights reserved.
LastYear Valuesinrowsareduringlastyear
YeartoDate Valuesinrowsareduringcurrentyeartopresentdate
AllDatesinthePeriod Valuesinrowsarewithinaspecifiedperiod
CustomFilter Valuesinrowsthatmeettheconditionsofacustomfilter
Userscanspecifywildcardsinconditions.The"?"characterrepresentsanysinglecharacter.The"*"characterrepresentsanyseriesofcharacters.
Whentheuserchoosesafilter,thetablefiltersthedatatodisplayonlytherowsthatmatchthefiltercriteria.
YoucanusetheFilter('FilterMethod'intheon-linedocumentation)methodtofilteratableusingcode.YoucanresetafilterbysettingnullintheFilter('FilterMethod'intheon-linedocumentation)method(forexample,table.Filter(3, null);resetsthefilterinthethirdcolumn).
Resizing a Table
Youcanresizethetablewiththeresizeindicatorinthebottom,rightcornerofthetableoryoucanusecodetodoso.
Selecttheindicatoranddragtotherighttoaddcolumnsordowntoaddrows.
UsingCode
UsetheResize('ResizeMethod'intheon-linedocumentation)methodtoaddcolumnsorrowstoatable.
Example
Thisexamplecodeaddsrowsandcolumnstothetable.
C#FarPoint.Win.Spread.TableStyle tstyle = fpSpread1.CreateTableStyle("Style1", FarPoint.Win.Spread.TableStyle.TableStyleLight2);fpSpread1.Sheets[0].Cells[1, 1].Text = "Last Name";fpSpread1.Sheets[0].Cells[1, 2].Text = "Value";fpSpread1.Sheets[0].Cells[2, 1].Text = "Smith";fpSpread1.Sheets[0].Cells[2, 2].Value = 50;fpSpread1.Sheets[0].Cells[3, 1].Text = "Vil";fpSpread1.Sheets[0].Cells[3, 2].Value = 10;fpSpread1.Sheets[0].Cells[4, 1].Text = "Press";fpSpread1.Sheets[0].Cells[4, 2].Value = 78;fpSpread1.TableStyleCollection.Add(tstyle);FarPoint.Win.Spread.TableView table = fpSpread1.Sheets[0].AddTable("table", 1, 1, 5, 2,
Spread Windows Forms Developer’s Guide 231
Copyright © GrapeCity, Inc. All rights reserved.
"Style1");table.Resize(6, 3);
VBDim tstyle As FarPoint.Win.Spread.TableStyletstyle = FpSpread1.CreateTableStyle("Style1", FarPoint.Win.Spread.TableStyle.TableStyleLight2)FpSpread1.Sheets(0).Cells(1, 1).Text = "Last Name"FpSpread1.Sheets(0).Cells(1, 2).Text = "Value"FpSpread1.Sheets(0).Cells(2, 1).Text = "Smith"FpSpread1.Sheets(0).Cells(2, 2).Value = 50FpSpread1.Sheets(0).Cells(3, 1).Text = "Vil"FpSpread1.Sheets(0).Cells(3, 2).Value = 10FpSpread1.Sheets(0).Cells(4, 1).Text = "Press"FpSpread1.Sheets(0).Cells(4, 2).Value = 78FpSpread1.TableStyleCollection.Add(tstyle)Dim table As FarPoint.Win.Spread.TableView = FpSpread1.Sheets(0).AddTable("table", 1, 1, 5, 2, "Style1")table.Resize(6, 3)
Sorting a Table
Youcansortatablebyselectingthedrop-downiconandselectingasortoption,asshowninthefollowingfigure,orbyusingcode.
UsingCode
Spread Windows Forms Developer’s Guide 232
Copyright © GrapeCity, Inc. All rights reserved.
UsetheSort('SortMethod'intheon-linedocumentation)methodtosortcolumnsinatable.
Example
Thisexamplecodesortsthecolumn.
C#FarPoint.Win.Spread.TableStyle tstyle = fpSpread1.CreateTableStyle("Style1", FarPoint.Win.Spread.TableStyle.TableStyleLight2);fpSpread1.Sheets[0].Cells[1, 1].Text = "Last Name";fpSpread1.Sheets[0].Cells[1, 2].Text = "Value";fpSpread1.Sheets[0].Cells[2, 1].Text = "Smith";fpSpread1.Sheets[0].Cells[2, 2].Value = 50;fpSpread1.Sheets[0].Cells[3, 1].Text = "Vil";fpSpread1.Sheets[0].Cells[3, 2].Value = 10;fpSpread1.Sheets[0].Cells[4, 1].Text = "Press";fpSpread1.Sheets[0].Cells[4, 2].Value = 78;fpSpread1.TableStyleCollection.Add(tstyle);FarPoint.Win.Spread.TableView table = fpSpread1.Sheets[0].AddTable("table", 1, 1, 5, 2, "Style1");FarPoint.Win.Spread.ComplexSortInfo[] sort = new FarPoint.Win.Spread.ComplexSortInfo[1];sort[0] = new FarPoint.Win.Spread.ComplexSortInfo(1, true);table.Sort(sort);
VBDim tstyle As FarPoint.Win.Spread.TableStyletstyle = FpSpread1.CreateTableStyle("Style1", FarPoint.Win.Spread.TableStyle.TableStyleLight2)FpSpread1.Sheets(0).Cells(1, 1).Text = "Last Name"FpSpread1.Sheets(0).Cells(1, 2).Text = "Value"FpSpread1.Sheets(0).Cells(2, 1).Text = "Smith"FpSpread1.Sheets(0).Cells(2, 2).Value = 50FpSpread1.Sheets(0).Cells(3, 1).Text = "Vil"FpSpread1.Sheets(0).Cells(3, 2).Value = 10FpSpread1.Sheets(0).Cells(4, 1).Text = "Press"FpSpread1.Sheets(0).Cells(4, 2).Value = 78FpSpread1.TableStyleCollection.Add(tstyle)Dim table As FarPoint.Win.Spread.TableView = FpSpread1.Sheets(0).AddTable("table", 1, 1, 5, 2, "Style1")Dim sort As FarPoint.Win.Spread.ComplexSortInfo() = New FarPoint.Win.Spread.ComplexSortInfo(0) {}sort(0) = New FarPoint.Win.Spread.ComplexSortInfo(1, True)table.Sort(sort)
Setting Table Styles
Youcanaddcustomorbuilt-instylestoatable.
Spread Windows Forms Developer’s Guide 233
Copyright © GrapeCity, Inc. All rights reserved.
Youcanspecifycustomstylesforthefirst,second,orlastcolumnaswellasotherareasofthetable.Foracompletelist,seetheTableStyle('TableStyleClass'intheon-linedocumentation)properties.Youcanspecifyabuilt-instylewiththeTableStylefields.
Tablestyleshaveapriorityorderwhenthestylesoverlap.Thepriorityfromhighesttolowestiscell,row,column,andtable.
Somestylepropertiesapplytoareasthatarenotvisibleordonothaveastylesettingbydefault.Forexample,theFirstRowStripestyleisnotdisplayedunlesstheBandedRows('BandedRowsProperty'intheon-linedocumentation)propertyistrue.ThefollowingtableliststheTableViewsettingthatmustbetruebeforetheassociatedtablestyleisdisplayedinthetable.
TableViewproperty
TableStyleproperty
BandedColumns('BandedColumnsProperty'intheon-linedocumentation)
FirstColumnStripe('FirstColumnStripeProperty'intheon-linedocumentation),FirstColumnStripSize('FirstColumnStripSizeProperty'intheon-linedocumentation),SecondColumnStripe('SecondColumnStripeProperty'intheon-linedocumentation),SecondColumnStripSize('SecondColumnStripSizeProperty'intheon-linedocumentation)
BandedRows('BandedRowsProperty'intheon-linedocumentation)
FirstRowStripe('FirstRowStripeProperty'intheon-linedocumentation),FirstRowStripSize('FirstRowStripSizeProperty'intheon-linedocumentation),SecondRowStripe('SecondRowStripeProperty'intheon-linedocumentation),SecondRowStripSize('SecondRowStripSizeProperty'intheon-linedocumentation)
FirstColumn('FirstColumnProperty'intheon-linedocumentation)
FirstColumn('FirstColumnProperty'intheon-linedocumentation)
HeaderRowVisible('HeaderRowVisibleProperty'intheon-linedocumentation)
HeaderRow('HeaderRowProperty'intheon-linedocumentation)
LastColumn('LastColumnProperty'intheon-linedocumentation)
LastColumn('LastColumnProperty'intheon-linedocumentation)
UsingCode
1. CreateastyleusingTableBorder('TableBorderClass'intheon-linedocumentation)and
Spread Windows Forms Developer’s Guide 234
Copyright © GrapeCity, Inc. All rights reserved.
TableElementStyle('TableElementStyleClass'intheon-linedocumentation).
2. UsetheTableStyle('TableStyleConstructor'intheon-linedocumentation)constructorandtheCreateTableStyle('CreateTableStyleMethod'intheon-linedocumentation)methodtoassignthestyle.
3. SettheTableStyleFirstColumn('FirstColumnProperty'intheon-linedocumentation)propertytoassignthestyletothecolumnorsetanyoftheTableStyleproperties.
4. SettheTableViewFirstColumn('FirstColumnProperty'intheon-linedocumentation)propertytoTruetodisplaythecolumnstyleorsettheappropriateTableViewproperty.
Example
Thisexamplecodeaddsacustomstyletothefirstcolumn.
C#FarPoint.Win.ComplexBorderSide bside = newFarPoint.Win.ComplexBorderSide(Color.Yellow);FarPoint.Win.Spread.TableBorder tborder = new FarPoint.Win.Spread.TableBorder(bside);FarPoint.Win.Spread.TableElementStyle testyle = newFarPoint.Win.Spread.TableElementStyle(tborder, Color.Red, Color.Blue,FarPoint.Win.Spread.RegularBoldItalicFontStyle.Bold);FarPoint.Win.Spread.TableStyle tstyle = fpSpread1.CreateTableStyle("Style1",FarPoint.Win.Spread.TableStyle.TableStyleLight2);tstyle.FirstColumn = testyle;fpSpread1.Sheets[0].Cells[1, 1].Text = "Last Name";fpSpread1.Sheets[0].Cells[1, 2].Text = "Value";fpSpread1.Sheets[0].Cells[2, 1].Text = "Smith";fpSpread1.Sheets[0].Cells[2, 2].Value = 50;fpSpread1.Sheets[0].Cells[3, 1].Text = "Vil";fpSpread1.Sheets[0].Cells[3, 2].Value = 10;fpSpread1.Sheets[0].Cells[4, 1].Text = "Press";fpSpread1.Sheets[0].Cells[4, 2].Value = 78;fpSpread1.TableStyleCollection.Add(tstyle);FarPoint.Win.Spread.TableView table = fpSpread1.Sheets[0].AddTable("table", 1, 1, 5, 2,"Style1");table.FirstColumn = true;
VBDim bside As New FarPoint.Win.ComplexBorderSide(Color.Yellow)Dim tborder As New FarPoint.Win.Spread.TableBorder(bside)Dim testyle As New FarPoint.Win.Spread.TableElementStyle(tborder, Color.Red,Color.Blue, FarPoint.Win.Spread.RegularBoldItalicFontStyle.Bold)Dim tstyle As FarPoint.Win.Spread.TableStyletstyle = FpSpread1.CreateTableStyle("Style1",FarPoint.Win.Spread.TableStyle.TableStyleLight2)tstyle.FirstColumn = testyleFpSpread1.Sheets(0).Cells(1, 1).Text = "Last Name"FpSpread1.Sheets(0).Cells(1, 2).Text = "Value"FpSpread1.Sheets(0).Cells(2, 1).Text = "Smith"FpSpread1.Sheets(0).Cells(2, 2).Value = 50FpSpread1.Sheets(0).Cells(3, 1).Text = "Vil"FpSpread1.Sheets(0).Cells(3, 2).Value = 10FpSpread1.Sheets(0).Cells(4, 1).Text = "Press"FpSpread1.Sheets(0).Cells(4, 2).Value = 78FpSpread1.TableStyleCollection.Add(tstyle)
Spread Windows Forms Developer’s Guide 235
Copyright © GrapeCity, Inc. All rights reserved.
Dim table As FarPoint.Win.Spread.TableView = FpSpread1.Sheets(0).AddTable("table", 1,1, 5, 2, "Style1")table.FirstColumn = True
Adding a Table Formula
YoucanaddformulastothetableinatotalrowatruntimewiththeFormulaEditororwithcode.
Addatotalrowandthenselectthedrop-downarrowatthebottomrightcornerofthetabletodisplayformulas.
YoucanselectMoreFunctionstodisplaytheFormulaEditorasshowninthefollowingfigure.
Spread Windows Forms Developer’s Guide 236
Copyright © GrapeCity, Inc. All rights reserved.
YoucanaddformulastothetablewiththeFormula('FormulaProperty'intheon-linedocumentation)property.Formoreinformationaboutusingstructuredreferencesintableformulas,seeUsingStructuredReferences.
UsingCode
UsetheTotalRowVisible('TotalRowVisibleProperty'intheon-linedocumentation)propertytodisplaythetotalrowforthetable.
Example
Thisexampleaddsatotalrow.
C#fpSpread1.Sheets[0].Cells[1, 1].Text = "Last Name";fpSpread1.Sheets[0].Cells[1, 2].Text = "Value";fpSpread1.Sheets[0].Cells[2, 1].Text = "Smith";fpSpread1.Sheets[0].Cells[2, 2].Value = 50;fpSpread1.Sheets[0].Cells[3, 1].Text = "Vil";fpSpread1.Sheets[0].Cells[3, 2].Value = 10;fpSpread1.Sheets[0].Cells[4, 1].Text = "Press";fpSpread1.Sheets[0].Cells[4, 2].Value = 78;FarPoint.Win.Spread.TableView table = fpSpread1.Sheets[0].AddTable("table", 1, 1, 5,2);table.TotalRowVisible = true;
VBFpSpread1.Sheets(0).Cells(1, 1).Text = "Last Name"FpSpread1.Sheets(0).Cells(1, 2).Text = "Value"FpSpread1.Sheets(0).Cells(2, 1).Text = "Smith"FpSpread1.Sheets(0).Cells(2, 2).Value = 50FpSpread1.Sheets(0).Cells(3, 1).Text = "Vil"FpSpread1.Sheets(0).Cells(3, 2).Value = 10FpSpread1.Sheets(0).Cells(4, 1).Text = "Press"FpSpread1.Sheets(0).Cells(4, 2).Value = 78Dim table As FarPoint.Win.Spread.TableView = FpSpread1.Sheets(0).AddTable("table", 1,1, 5, 2)table.TotalRowVisible = True
Understanding Structured References
Spreadsupportsstructuredreferenceformulasintables.Componentsofthestructuredreferenceincludethetablename,thecolumnspecifier,thespecialitemspecifier,andthetablespecifier.
Atablenameisthenameassignedtothetable.Thenamereferencesthetabledata,butnottheheaderandtotalsrows,ifany.
Acolumnspecifierisderivedfromthecolumnheaderandreferencesthecolumndata(excludingthecolumnheaderandtotal,ifany).Aspecialitemspecifierisawaytorefertospecificportionsofthetable,suchastheTotalsrow.
Thetablespecifieristheouterportionofthestructuredreference.Thespecifiersfollowthetablename,andareenclosedinsquarebrackets.Astructuredreferenceistheentirestringbeginningwiththetablenameandendingwiththecolumnspecifier.
Specifiersareenclosedinbrackets.
Spread Windows Forms Developer’s Guide 237
Copyright © GrapeCity, Inc. All rights reserved.
Thefollowingtopicsprovideadditionalinformationaboutstructuredreferencesintables.
UsingOperatorsandSpecialItems
UnderstandingStructuredReferenceSyntaxRules
UsingStructuredReferences
Using Operators and Special Items
Youcanuseoperatorsandspecialitemsinthestructuredreference.Thestructuredreferencecanbeunqualifiedorfullyqualified.
Foraddedflexibilityinspecifyingrangesofcells,youcanusethefollowingreferenceoperatorstocombinecolumnspecifiers.TheCellRangecolumnisageneralexample.
StructuredReference RefersTo
Operator CellRange
=DeptSales[[SalesPerson]:[Region]] Allofthecellsintwoormoreadjacentcolumns
:(colon)rangeoperator
A2:B7
=DeptSales[SaleAmt],DeptSales[ComAmt] Acombinationoftwoormorecolumns
,(comma)unionoperator
C2:C7,E2:E7
=DeptSales[[SalesPerson]:[SaleAmt]]DeptSales[[Region]:[ComPct]] Theintersectionoftwoormorecolumns
(space)intersectionoperator
B2:C7
Foraddedconvenience,youcanalsousespecialitemstorefertovariousportionsofatable,suchastheTotalsrow,tomakeiteasiertorefertotheseportionsinformulas.Thefollowingarethespecialitemspecifiersthatyoucanuseinastructuredreference:
SpecialItemSpecifier
RefersTo CellRange
=DeptSales[#All] Theentiretable,includingcolumnheaders,data,andtotals(ifany) A1:E8
=DeptSales[#Data] Justthedata A2:E7
=DeptSales[#Headers] Justtheheaderrow A1:E1
=DeptSales[#Totals] Justthetotalrow.Ifnoneexists,thenitreturnsnull A8:E8
Spread Windows Forms Developer’s Guide 238
Copyright © GrapeCity, Inc. All rights reserved.
=DeptSales[#ThisRow] Justtheportionofthecolumnsinthecurrentrow.#ThisRowcannotbecombinedwithanyotherspecialitemspecifiers.Useittoforceimplicitintersectionbehaviorforthereferenceortooverrideimplicitintersectionbehaviorandrefertosinglevaluesfromacolumn.
Whenyoucreateacalculatedcolumn,youoftenuseastructuredreferencetocreatetheformula.Thisstructuredreferencecanbeunqualifiedorfullyqualified.Forexample,tocreatethecalculatedcolumncalled,ComAmt,thatcalculatestheamountofcommissionindollars,youcanusethefollowingformulas:
StructuredReference
Example Comment
Unqualified =[SaleAmt]*[ComPct] Multipliesthecorrespondingvaluesfromthecurrentrow
Fullyqualified =DeptSales[SaleAmt]*DeptSales[ComPct] Multiplesthecorrespondingvaluesforeachrowforbothcolumns
Ifyouareusingstructuredreferenceswithinatable,suchaswhenyoucreateacalculatedcolumn,youcanuseanunqualifiedstructuredreference,butifyouusethestructuredreferenceoutsideofthetable,youneedtouseafullyqualifiedstructuredreference.
Understanding Structured Reference Syntax Rules
Structuredreferenceshaveadditionalsyntaxruleslistedasfollows:
Matchingbracketsarerequiredfortables,specifiers,andspecialcharacters.
Characterswithspecialmeaningrequireanescapecharacter.
Spacescanbeusedincertainareastomakethestructuredreferenceeasiertoread.
Alltable,column,andspecialitemspecifiersmustbeenclosedinmatchingbrackets([]).Aspecifierthatcontainsotherspecifiersrequiresoutermatchingbracketstoenclosetheinnermatchingbracketsoftheotherspecifiers,forexample:
=DeptSales[[SalesPerson]:[Region]]
Allcolumnheadersaretextstrings,butdonotrequirequoteswhentheyareusedinastructuredreference.Ifacolumnheadercontainsnumbersordates,suchas2004or1/1/2004,thesearestillconsideredtextstrings.Becausecolumnheadersaretextstrings,youcannotuseexpressionswithinbrackets,forexample:
=DeptSalesFYSummary[[2004]:[2002]]
Ifatablecolumnheadercontainsoneofthefollowingspecialcharacters,theentirecolumnheadermustbeenclosedinbrackets.Thismeansdoublebracketsarerequiredinacolumnspecifierwiththefollowingspecialcharacters:space,tab,linefeed,carriagereturn,comma(,),colon(:),period(.),leftbracket([),rightbracket(]),poundsign(#),singlequotationmark('),doublequotationmark("),leftbrace({),rightbrace(}),dollarsign($),caret(^),ampersand(&),asterisk(*),plussign(+),equalsign(=),minussign(-),greaterthansymbol(>),lessthansymbol(<),anddivisionsign(/).
Thefollowingstructuredreferenceincludesacolumnspecifierthatcontainsspecialcharacters:
=DeptSalesFYSummary[[Total$Amount]]
Theonlyexceptiontothisisiftheonlyspecialcharacterthatisusedisaspacecharacter,forexample:
=DeptSales[TotalAmount]
Thefollowingcharactershavespecialmeaningandrequiretheuseofasinglequotationmark(')asanescapecharacter:leftbracket([),rightbracket(]),poundsign(#),andsinglequotationmark(').
Thefollowingexampleillustratesastructuredreferencethatcontainsacharacterwithaspecialmeaning:
=DeptSalesFYSummary['#OfItems]
Spread Windows Forms Developer’s Guide 239
Copyright © GrapeCity, Inc. All rights reserved.
Youcanusespacecharacterstoimprovethereadabilityofastructuredreference.Youcanuseonespaceafterthefirstleftbracket([)andprecedingthelastrightbracket(]).Youcanalsouseonespaceafteracomma,asshowninthefollowingexamples:
=DeptSales[[SalesPerson]:[Region]]
=DeptSales[[#Headers],[#Data],[ComPct]]
Using Structured References
YoucanaddstructuredreferencestotablesusingtheFormula('FormulaProperty'intheon-linedocumentation)property.
Acelloutsideofthetablecanhaveaformulawithatablereference;however,thetablenamemustbeuniqueamongtablenamesandcustomnames.Thetablenamemustalsobevalid.
UsingCode
SettheFormula('FormulaProperty'intheon-linedocumentation)propertyforthecell.
Example
ThisexamplecodesumstheValuecolumninthetable.
C#fpSpread1.Sheets[0].Cells[1, 1].Text = "Last Name";fpSpread1.Sheets[0].Cells[1, 2].Text = "Value";fpSpread1.Sheets[0].Cells[2, 1].Text = "Smith";fpSpread1.Sheets[0].Cells[2, 2].Value = 50;fpSpread1.Sheets[0].Cells[3, 1].Text = "Vil";fpSpread1.Sheets[0].Cells[3, 2].Value = 10;fpSpread1.Sheets[0].Cells[4, 1].Text = "Press";fpSpread1.Sheets[0].Cells[4, 2].Value = 78;fpSpread1.Sheets[0].AddTable("table", 1, 1, 5, 2);fpSpread1.Sheets[0].Cells[5, 1].Formula = "SUM(table[Value])";
VBFpSpread1.Sheets(0).Cells(1, 1).Text = "Last Name"FpSpread1.Sheets(0).Cells(1, 2).Text = "Value"FpSpread1.Sheets(0).Cells(2, 1).Text = "Smith"FpSpread1.Sheets(0).Cells(2, 2).Value = 50FpSpread1.Sheets(0).Cells(3, 1).Text = "Vil"FpSpread1.Sheets(0).Cells(3, 2).Value = 10FpSpread1.Sheets(0).Cells(4, 1).Text = "Press"FpSpread1.Sheets(0).Cells(4, 2).Value = 78FpSpread1.Sheets(0).AddTable("table", 1, 1, 5, 2)FpSpread1.Sheets(0).Cells(5, 1).Formula = "SUM(table[Value])"
Customizing User Searching of Data
Youcansearchfordatainanyofthecellsintheworkbookbyspecifyingthesheetandthestringofdataforwhichtosearch.Youcanalsohavethecomponentdisplayasearchdialogandallowtheendusertosearchfordata.ThemethodsandpropertiesthatrelatetosearchingandsearchdialogsarepartoftheSpreadcomponent.
Spread Windows Forms Developer’s Guide 240
Copyright © GrapeCity, Inc. All rights reserved.
Thetasksforsearchinginclude:
AllowingtheUsertoPerformaStandardSearchAllowingtheUsertoPerformanAdvancedSearchSearchingforDatawithCode
Therearelimitationstothesearch.Rowandcolumnheadersarenotsearchedwiththesearchdialogs;onlycellsaresearched.UsetheSearchHeaders('SearchHeadersMethod'intheon-linedocumentation)methodtosearchtheheaders.Noneoftheinformationinthesheet,column,orrowobjectisincludedinthesearch.Notalltagsareincludedwhenyousearchand"includetags";onlycelltagsareincluded.
Mostsearches(exceptforthemethodthatspecifiesablockrangeofcells)startatthespecifiedstartcellandcontinuetotheendoftherowandthenstartthenextrowatthefirstcell.Thesearchcontinuesuntileithertheendcellortheendofthesheet.
Allowing the User to Perform a Standard Search
Youcanhavethecomponentdisplayasearch(find)dialogfortheend-usertoallowthemtosearchthetext(unformatteddata)ofcellsinasheetforaparticularstringoftext,asshowninthefollowingfigure.
Youcancustomizemanyfeaturesofthesearchdialogboxbysettingitsproperties.Inaddition,youcandisplayadefaultsearchstringintheFindwhatcombobox.Andyoucansetthecheckboxesfortheseoptions:
Matchcase-findingonlystringsthatmatchthecaseofthesearchstring(upperorlowercase).Matchexactly-findingonlystringsthatmatchthesearchstringexactly.Alternatesearch-searchingdownrowsthenacrosscolumnsratherthanviceversa.Usewildcards-allowtheuseofwildcardcharactersinthesearchstring.
Forinformationabouttheadvancedoptionsavailableonthesearchdialog,refertoAllowingtheUsertoPerformanAdvancedSearch.
Forinformationaboutperformingasearchwithoutadialog,refertoSearchingforDatawithCode.
UsingCode
UsetheSearchWithDialog('SearchWithDialogMethod'intheon-linedocumentation)methodsfortheFpSpread('FpSpreadClass'intheon-linedocumentation)componenttocustomizethesearchdialog.
Example
Thisexampleprovidesasearchdialogwithseveralsettingspreset.Inthiscase,itasanexact-matchsearchonthefourthsheet(Sheet3)forthephrase"NotAvailable"andstartatthefirstrowandcolumn.
C#fpSpread1.SearchWithDialog(3,"Not Available",true,true,false,false,0,0);
VBFpSpread1.SearchWithDialog(3,"Not Available",True,True,False,False,0,0)
Spread Windows Forms Developer’s Guide 241
Copyright © GrapeCity, Inc. All rights reserved.
Allowing the User to Perform an Advanced Search
Youcanprovideamoreadvancedsearchdialogfortheend-userstoallowthemtosearchotherareasofthespreadsheet,includingcellnotesandcelltags.
Thereareseveraladvancedoptionsyoucansetthatextendthescopeofthesearch.Foradescriptionofthestandardsearchoptions(showninthetophalfoftheadvanceddialog),refertoAllowingtheUsertoPerformaStandardSearch.Theadvancedoptionsinclude:
Includecelltext-searchestherowandcolumncells.Includecelltags-searchesthecelltagsinthedataarea.Includecellnotes-searchesthecellnotesinthedataarea.
Forinformationaboutperformingasearchwiththesearchdialogwiththestandardoptions,refertoAllowingtheUsertoPerformaStandardSearch.
Forinformationaboutperformingasearchwithoutadialog,refertoSearchingforDatawithCode.
UsingCode
UsetheSearchWithDialogAdvanced('SearchWithDialogAdvancedMethod'intheon-linedocumentation)methodsfortheFpSpread('FpSpreadClass'intheon-linedocumentation)componenttocustomizetheadvancedsearchdialog.
Example
ThisexampleusestheSearchWithDialogAdvanced('SearchWithDialogAdvancedMethod'intheon-linedocumentation)methodandprovidestheusersasearchdialogwithseveralsettingspreset.
C#fpSpread1.SearchWithDialogAdvanced(0,4,"This",true,true,false,false,0,0);
VBFpSpread1.SearchWithDialogAdvanced(0,4,"This",True,True,False,False,0,0)
Searching for Data with Code
Tosearchfordatainanyofthecellsofasheet,useanyofthesesetsofmethodsintheFpSpread('FpSpreadClass'intheon-linedocumentation)class:
Search('SearchMethod'intheon-linedocumentation)methodsSearchHeaders('SearchHeadersMethod'intheon-linedocumentation)methods
Spread Windows Forms Developer’s Guide 242
Copyright © GrapeCity, Inc. All rights reserved.
SearchWithDialog('SearchWithDialogMethod'intheon-linedocumentation)methodsSearchWithDialogAdvanced('SearchWithDialogAdvancedMethod'intheon-linedocumentation)methods
Theparametersofthevarioussearchmethodsallowyoutospecifythesheettosearch,thestringforwhichtosearch,andthematchingcriteria.Foralistofqualifications(restrictions)ofthesearch,refertothesetofmethodslistedaboveformoredetails.
Mostsearches(exceptforthemethodthatspecifiesablockrangeofcells)startatthespecifiedstartcellandcontinuetotheendoftherowandthenstartthenextrowatthefirstcell.Thesearchcontinuesuntileithertheendcellortheendofthesheet.
Forinformationaboutthesearchdialogs,refertoAllowingtheUsertoPerformaStandardSearchandAllowingtheUsertoPerformanAdvancedSearch.
UsingCode
UsetheSearch('SearchMethod'intheon-linedocumentation)methodfortheSpreadcomponenttoperformasearch.
Example
ThisexampleusestheSearch('SearchMethod'intheon-linedocumentation)methodfortheSpreadcomponenttoperformanexact-matchsearchonthethirdsheet(Sheet2)fortheword"Total"andreturnthevaluesoftherowindexandcolumnindexofthefoundcell.
C#int rowindx = 0;int colindx = 0;fpSpread1.Search(2,"Total",true,true,false,false,1,1,56,56, ref rowindx,ref colindx);
VBDim rowindx as IntegerDim colindx as IntegerFpSpread1.Search(2,"Total",True,True,False,False,1,1,56,56,rowindx,colindx)
Customizing User Selection of Data
Youcancustomizewhattheusercanselectandhowtheselectionappears.Tocustomizeaspectsofselections,youcanperformthefollowingtasks:
SpecifyingWhattheUserCanSelectCustomizingtheSelectionAppearanceWorkingwithSelectionsHidingtheSelectionWhenFocusisLost
Youcancustomizeseveralaspectsofuserselectionandwhethertohidetheselectionwhenfocusislost.Forexample,youcansetwhethertomovetheactivecellintheviewwiththeMoveActiveOnFocus('MoveActiveOnFocusProperty'intheon-linedocumentation)propertyoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class.Formoreactionswithselections,refertoWorkingwithSelections.
Tosettheselectionmodelforasheet,usetheSheetViewSelection('SelectionProperty'intheon-linedocumentation)property.
ForinformationregardingselectionsinSpreadDesigner,refertoSelectingaContiguousRangeofCells(on-linedocumentation)intheSpreadDesignerGuide(on-linedocumentation).
Spread Windows Forms Developer’s Guide 243
Copyright © GrapeCity, Inc. All rights reserved.
Specifying What the User Can Select
Bydefault,sheetsallowuserstoselectacell,acolumn,arow,arangeofcells,ortheentiresheet.Youcancustomizehowselectionoccursandwhatcanbeselectedbyworkingwiththeoperationmodeofthesheetandwiththeselectionpolicyandselectionunitofthesheet.
Thefollowingtablesummarizestheoptionsavailableforspecifyingwhatuserscanselect:
Whatusercanselect
Whensettingthisforthesheet
Cells FpSpread.SelectionBlockOptions('SelectionBlockOptionsProperty'intheon-linedocumentation).Cells
Rows FpSpread.SelectionBlockOptions('SelectionBlockOptionsProperty'intheon-linedocumentation).Rows
Columns FpSpread.SelectionBlockOptions('SelectionBlockOptionsProperty'intheon-linedocumentation).Columns
Sheet FpSpread.SelectionBlockOptions('SelectionBlockOptionsProperty'intheon-linedocumentation).Sheet
Combination FpSpread.SelectionBlockOptions('SelectionBlockOptionsProperty'intheon-linedocumentation).numberwherenumberissomeadditionofthenumbersfortheindividualsettings(suchas6=2+4,RowsandColumns)
Cells,rangesofcells,ormultiplerangesofcells
OperationMode('OperationModeProperty'intheon-linedocumentation).NormalwithSelectionPolicy('SelectionPolicyProperty'intheon-linedocumentation)property
Onlyrows,noediting
OperationMode('OperationModeProperty'intheon-linedocumentation).SingleSelect
Onlyrows,editing OperationMode('OperationModeProperty'intheon-linedocumentation).RowMode
Multiplecontiguousrows,noediting
OperationMode('OperationModeProperty'intheon-linedocumentation).MultiSelect
Multiplenoncontiguousrows,noediting
OperationMode('OperationModeProperty'intheon-linedocumentation).ExtendedSelect
NotethattheFpSpread.SelectionBlockOptions('SelectionBlockOptionsProperty'intheon-linedocumentation)aresettingsattheSpreadcomponentlevel,whiletheOperationMode('OperationModeProperty'intheon-linedocumentation)settingsareatthesheetlevel.
ThesettingsoftheOperationMode('OperationModeProperty'intheon-linedocumentation)andtheSelectionBlockOptions('SelectionBlockOptionsProperty'intheon-linedocumentation)propertiesaffectuserinteractionwiththesheet,thatis,whattheusercanselect,butnotnecessarilywhattheapplicationcanselect.Ifyouwanttocustomizewhattheuserandtheapplicationbothcanselect,settheSelectionUnit('SelectionUnitProperty'intheon-linedocumentation)property.
YoucanalsorestrictwhichcellscanbeeditedbyusingtheRestrictRows('RestrictRowsProperty'intheon-linedocumentation)andRestrictColumns('RestrictColumnsProperty'intheon-linedocumentation)methodsforthesheet.Thisrestrictsusersfromenteringdatabeyondthenextroworcolumn.Formoreinformation,refertotheSelectionPolicy('SelectionPolicyProperty'intheon-linedocumentation)propertyandtheSelectionUnit('SelectionUnitProperty'intheon-linedocumentation)propertyoftheSheetView('SheetViewClass'intheon-linedocumentation)class,andtheSelectionBlockOptions('SelectionBlockOptionsProperty'intheon-linedocumentation)propertyoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class.Formoredetails,seetheOperationMode('OperationMode
Spread Windows Forms Developer’s Guide 244
Copyright © GrapeCity, Inc. All rights reserved.
Enumeration'intheon-linedocumentation)andtheSelectionBlockOptions('SelectionBlockOptionsEnumeration'intheon-linedocumentation)enumerations.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetforwhichtosettheoperationmode.5. SelecttheOperationModeproperty,thenselectoneofthevaluesfromthedrop-downlistofvalues.6. IfyousettheOperationModepropertytoNormal,andyouwanttoallowuserstoselectonlyacellortoselect
multiplerangesofcells,settheSelectionPolicypropertytoSingleortoMultiRange.7. Tosettheoverallselectioninteractionforthesheet,includinghowusersandtheapplicationcanselectitems,settheSelectionUnitpropertytospecifytheunitofselectionallowed.
8. ClickOKtoclosetheeditor.9. IfyouwanttocustomizewhatuserscanselectinallsheetsintheSpreadcomponent,settheSelectionBlockOptionspropertytospecifywhethertheycanselectcells,columns,rows,thesheetoracombinationofthese.
UsingaShortcut
1. Tosettheoveralluserinteractionmodeofthesheet,settheSheetsOperationMode('OperationModeProperty'intheon-linedocumentation)property.
2. IfyousettheOperationMode('OperationModeProperty'intheon-linedocumentation)propertytoNormal,
a. IfyouwanttocustomizewhatuserscanselectinallsheetsintheSpreadcomponent,settheFpSpreadSelectionBlockOptions('SelectionBlockOptionsProperty'intheon-linedocumentation)propertytospecifywhethertheycanselectcells,columns,rows,thesheetoracombinationofthese.
b. Ifyouwanttoallowuserstoselectonlyacellortoselectmultiplerangesofcells,settheSheetsSelectionPolicy('SelectionPolicyProperty'intheon-linedocumentation)propertytoSingleortoMultiRange.
3. Tosettheoverallselectioninteractionforthesheet,includinghowusersandtheapplicationcanselectitems,settheSheetsSelectionUnit('SelectionUnitProperty'intheon-linedocumentation)propertytospecifytheunitofselectionallowed.
Example
Thisexamplecodesetsthesheettoallowuserstoselectonlycellsorrangesofcells,includingmultiplerangesofcells.Theycannotselectcolumns,rows,ortheentiresheetinthisexample.
C#// Set option so users can select only cells.fpSpread1.SelectionBlockOptions = FarPoint.Win.Spread.SelectionBlockOptions.Cells;// Set operation mode and let users select multiple blocks of cells.fpSpread1.Sheets[0].OperationMode = FarPoint.Win.Spread.OperationMode.Normal;fpSpread1.Sheets[0].SelectionPolicy = FarPoint.Win.Spread.Model.SelectionPolicy.MultiRange;
VB' Set option so users can select only cells.FpSpread1.SelectionBlockOptions = FarPoint.Win.Spread.SelectionBlockOptions.Cells' Set operation mode and let users select multiple blocks of cells.
Spread Windows Forms Developer’s Guide 245
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.Sheets(0).OperationMode = FarPoint.Win.Spread.OperationMode.NormalFpSpread1.Sheets(0).SelectionPolicy = FarPoint.Win.Spread.Model.SelectionPolicy.MultiRange
UsingCode
1. Tosettheoveralluserinteractionmodeofthesheet,settheOperationMode('OperationModeProperty'intheon-linedocumentation)propertyforaSheetViewobject.
2. IfyousettheOperationMode('OperationModeProperty'intheon-linedocumentation)propertytoNormal,
a. IfyouwanttocustomizewhatuserscanselectinallsheetsintheSpreadcomponent,settheFpSpreadSelectionBlockOptions('SelectionBlockOptionsProperty'intheon-linedocumentation)propertytospecifywhethertheycanselectcells,columns,rows,thesheetoracombinationofthese.
b. Ifyouwanttoallowuserstoselectonlyacellortoselectmultiplerangesofcells,settheSheetViewobjectSelectionPolicy('SelectionPolicyProperty'intheon-linedocumentation)propertytoSingleortoMultiRange.
3. Tosettheoverallselectioninteractionforthesheet,includinghowusersandtheapplicationcanselectitems,settheSheetViewobjectSelectionUnit('SelectionUnitProperty'intheon-linedocumentation)propertytospecifytheunitofselectionallowed.
4. AssigntheSheetViewobjectyouhavecreatedtooneofthesheetsintheSpreadcomponent.
Example
Thisexamplecodesetsthesheettoallowuserstoselectonlycellsorrangesofcells,includingmultiplerangesofcells.Theycannotselectcolumns,rows,ortheentiresheetinthisexample.
C#// Set option so users can select only cells.fpSpread1.SelectionBlockOptions = FarPoint.Win.Spread.SelectionBlockOptions.Cells;// Set operation mode and let users select multiple blocks of cells.FarPoint.Win.Spread.SheetView newsheet = new FarPoint.Win.Spread.SheetView();newsheet.OperationMode = FarPoint.Win.Spread.OperationMode.Normal;newsheet.SelectionPolicy = FarPoint.Win.Spread.Model.SelectionPolicy.MultiRange;// Assign the SheetView object to a sheet.fpSpread1.Sheets[0] = newsheet;
VB' Set option so users can select only cells.FpSpread1.SelectionBlockOptions = FarPoint.Win.Spread.SelectionBlockOptions.Cells' Set operation mode and let users select multiple blocks of cells.Dim newsheet As New FarPoint.Win.Spread.SheetView()newsheet.OperationMode = FarPoint.Win.Spread.OperationMode.Normalnewsheet.SelectionPolicy = FarPoint.Win.Spread.Model.SelectionPolicy.MultiRange' Assign the SheetView object to a sheet.FpSpread1.Sheets(0) = newsheet
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosettheselectionoperationmode.2. FromtheSettingsmenu,selectgeneral(SheetSettingssection).IntheSheetSettingsdialog,ontheGeneraltab,selectoneofthechoicesfromtheOperationModearea.
3. ClickOKtoclosetheSheetSettingsdialog.
Spread Windows Forms Developer’s Guide 246
Copyright © GrapeCity, Inc. All rights reserved.
4. IfyousettheOperationModepropertytoNormal,a. IfyouwanttocustomizewhatuserscanselectinallsheetsintheSpreadcomponent,settheSelectionBlockOptionsproperty(fortheselectedSpread)inthePropertieslisttospecifywhethertheycanselectcells,columns,rows,thesheetoracombinationofthese.
b. Ifyouwanttoallowuserstoselectonlyacellortoselectmultiplerangesofcells,settheSelectionPolicyproperty(fortheselectedSheet)inthePropertieslisttoSingleortoMultiRange.
5. Tosettheoverallselectioninteractionforthesheet,includinghowusersandtheapplicationcanselectitems,settheSelectionUnitproperty(fortheselectedSheet)inthePropertieslisttospecifytheunitofselectionallowed.
6. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing the Selection Appearance
SelectionshaveadefaultappearanceprovidedbytheSpreadcomponentandtheselectionrenderer.Youcanchangethatappearance,includingthebackgroundandforegroundcolorsandfont.YoucanalsospecifyarowselectoriconwiththeShowRowSelector('ShowRowSelectorProperty'intheon-linedocumentation)property.YoucanspecifyarowediticonwiththeShowEditingRowSelector('ShowEditingRowSelectorProperty'intheon-linedocumentation)propertyasillustratedinthefollowingimage.
Youcanspecifywhethertodisplaytheselectionheader,border,oractivecellwiththePaintSelectionHeader('PaintSelectionHeaderProperty'intheon-linedocumentation),PaintSelectionBorder('PaintSelectionBorderProperty'intheon-linedocumentation),orPaintActiveCellInSelection('PaintActiveCellInSelectionProperty'intheon-linedocumentation)property.
Bydefault,theSpreadcomponentusestheappearancesetbytheselectionrenderer.Whensomethingisselected,therendererchangesthecolorofthebackgroundoftheselection.Insteadofusingthisrendering,youcanspecifyspecificcolorstouseforthebackgroundandtextcolorsofselections.Alternatively,youcanuseboththerenderer’sappearanceandcolorsyouset.Finally,youcanspecifythatnoappearanceisusedtohighlightselections.
Thefollowingfigureshowscellsselectedusingthedefaultrendererstyle,thencellsselectedusingsetcolors,andfinally,cellsselectedusingboththerendererstyleandsetcolors.
Ifnocolorissetfortheselection,thenthecolorisColor.FromArgb(100,193,224,255).
PaintingofselectedcellsisdeterminedbythevariouspropertiesintheSheetView('SheetViewClass'intheon-linedocumentation)class:
SheetViewProperty DescriptionSelectionBackColor('SelectionBackColor Determinesthebackgroundcolorofselections
Spread Windows Forms Developer’s Guide 247
Copyright © GrapeCity, Inc. All rights reserved.
Property'intheon-linedocumentation)
SelectionForeColor('SelectionForeColorProperty'intheon-linedocumentation)
Determinesthetextcolorofselections
SelectionStyle('SelectionStyleProperty'intheon-linedocumentation)
Determineshowtheselectionsarestyledusingeitherthecolorsoracustomrendererorboth
SelectionFont('SelectionFontProperty'intheon-linedocumentation)
Determinesthefontoftheselectedtext
WhentheSelectionStyle('SelectionStyleProperty'intheon-linedocumentation)isSelectionColors,thecellispaintedusingtheSelectionBackColor('SelectionBackColorProperty'intheon-linedocumentation)andSelectionForeColor('SelectionForeColorProperty'intheon-linedocumentation)settingsinplaceofthecell'sForeColor('ForeColorProperty'intheon-linedocumentation)andBackColor('BackColorProperty'intheon-linedocumentation)propertysettings.WhentheSelectionStyle('SelectionStyleProperty'intheon-linedocumentation)isSelectionRenderer,thecellispaintedusingthecell'sForeColor('ForeColorProperty'intheon-linedocumentation)andBackColor('BackColorProperty'intheon-linedocumentation)propertysettings.Thenasemi-transparentlayerispaintedoverthecell.Thesemi-transparentlayerisaccomplishedusingthefollowing.
Brush selectionBrush = new SolidBrush(Color.FromArgb(100, 193, 224, 255));
g.FillRectangle(selectionBrush, x, y, width, height);
Formoreinformation,refertotheSelectionStyles('SelectionStylesEnumeration'intheon-linedocumentation)enumerationandtheISelectionRenderer('ISelectionRendererInterface'intheon-linedocumentation)interface.
Formoreinformationonselectionsettings,refertotheSelectionRenderer('SelectionRendererProperty'intheon-linedocumentation)propertyandtheRetainSelectionBlock('RetainSelectionBlockProperty'intheon-linedocumentation)propertyintheFpSpread('FpSpreadClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetforwhichtosettheselectionappearance.5. SelecttheSelectionStyleproperty,thenselectoneofthevaluesfromthedrop-downlistofvalues.6. IfyousettheSelectionStyletoSelectionColorsorBoth,settheSelectionBackColorandSelectionForeColorpropertiestospecifythebackgroundandtextcolorsfortheselectionhighlighting.
7. ClickOKtoclosetheeditor.
UsingaShortcut
1. Tospecifyhowtodrawtheselectionhighlighting,settheSheetsSelectionStyle('SelectionStyleProperty'intheon-linedocumentation)property.
2. IfyousettheSelectionStyle('SelectionStyleProperty'intheon-linedocumentation)toSelectionColorsorBoth,settheSheetsSelectionBackColor('SelectionBackColorProperty'intheon-linedocumentation)andSelectionForeColor('SelectionForeColorProperty'intheon-linedocumentation)tospecifythecolorstouseforthebackgroundandforthetext.
Example
Thisexamplecodesetstheselectionhighlightingtousetherenderersettingsandcolors.
C#
Spread Windows Forms Developer’s Guide 248
Copyright © GrapeCity, Inc. All rights reserved.
// Use the selection renderer and colors.fpSpread1.Sheets[0].SelectionStyle = FarPoint.Win.Spread.SelectionStyles.Both;// Set the background and text colors.fpSpread1.Sheets[0].SelectionBackColor = System.Drawing.Color.Pink;fpSpread1.Sheets[0].SelectionForeColor = System.Drawing.Color.Navy;
VB' Use the selection renderer and colors.FpSpread1.Sheets(0).SelectionStyle = FarPoint.Win.Spread.SelectionStyles.Both' Set the background and text colors.FpSpread1.Sheets(0).SelectionBackColor = System.Drawing.Color.PinkFpSpread1.Sheets(0).SelectionForeColor = System.Drawing.Color.Navy
UsingCode
1. Tospecifyhowtodrawtheselectionhighlighting,settheSelectionStyle('SelectionStyleProperty'intheon-linedocumentation)propertyforaSheetView('SheetViewClass'intheon-linedocumentation)object.
2. IfyousettheSelectionStyle('SelectionStyleProperty'intheon-linedocumentation)toSelectionColorsorBoth,settheSheetViewobjectSelectionBackColor('SelectionBackColorProperty'intheon-linedocumentation)andSelectionForeColor('SelectionForeColorProperty'intheon-linedocumentation)tospecifythecolorstouseforthebackgroundandforthetext.
3. AssigntheSheetView('SheetViewClass'intheon-linedocumentation)objectyouhavecreatedtooneofthesheetsinthecomponent.
Example
Thisexamplecodesetstheselectionhighlightingtousetherenderersettingsandcolors.
C#FarPoint.Win.Spread.SheetView newsheet=new FarPoint.Win.Spread.SheetView();// Use the selection renderer and colors.newsheet.SelectionStyle = FarPoint.Win.Spread.SelectionStyles.Both;newsheet.SelectionBackColor = System.Drawing.Color.AliceBlue;// Set the background and text colors.newsheet.SelectionForeColor = System.Drawing.Color.Navy;// Assign the SheetView to a sheet in the component.fpSpread1.Sheets[0] = newsheet;
VBDim newsheet As New FarPoint.Win.Spread.SheetView()' Use the selection renderer and colors.newsheet.SelectionStyle = FarPoint.Win.Spread.SelectionStyles.Both' Set the background and text colors.newsheet.SelectionBackColor = System.Drawing.Color.AliceBluenewsheet.SelectionForeColor = System.Drawing.Color.Navy' Assign the SheetView to a sheet in the component.FpSpread1.Sheets(0) = newsheet
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosettheselectionstyle.
Spread Windows Forms Developer’s Guide 249
Copyright © GrapeCity, Inc. All rights reserved.
2. Inthepropertylist,settheSelectionStyleproperty.3. IfyousettheSelectionStyletoSelectionColorsorBoth,settheSelectionBackColorandSelectionForeColorpropertiestospecifythebackgroundandtextcolorsfortheselectionhighlighting.
4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Working with Selections
Whenauserselectsarangeofcells,thatrangeofcellscanhaveaseparatebackgroundcolorandforegroundcolortodistinguishitfromtheothercellsinthespreadsheet.Therangeiscalledaselection.Therearemanyaspectsofselectionsthatyoucanmanageprogrammatically.Incodeyoucanaddandremoveselectionsandyoucanfindoutwhatisselected.Thistopicsummarizessomeofthetasksyoucanperformwithselectionsincode.
Toaddaselection(arangeofcellsthataredisplayedasselected),usetheSheetsAddSelection('AddSelectionMethod'intheon-linedocumentation)methodandspecifythestartingrowandcolumn,andthenumberofrowsandcolumnsintheselection.Togetalltherangesofcellsthatarepresentlyselected,usetheSheetsGetSelections('GetSelectionsMethod'intheon-linedocumentation)method.Toreturnaspecificselection,usetheSheetsGetSelection('GetSelectionMethod'intheon-linedocumentation)method.Toremovealloftheselections,usetheSheetsClearSelection('ClearSelectionMethod'intheon-linedocumentation)method.Toremoveaspecificselection,usetheSheetsRemoveSelection('RemoveSelectionMethod'intheon-linedocumentation)methodandspecifytherowandcolumn,andthenumberofrowsandcolumnstoremovefromtheselection.Toclearallselectionswhenanewactivecellissetprogrammatically,usingtheBooleanclearSelectionparameterintheSetActiveCell('SetActiveCellMethod'intheon-linedocumentation)method.Tokeepaselectionhighlighted,usetheRetainSelectionBlock('RetainSelectionBlockProperty'intheon-linedocumentation)propertyoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class.YoucanmoveaselectedcellintheviewusingtheMoveActiveOnFocus('MoveActiveOnFocusProperty'intheon-linedocumentation)propertyoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class.Toworkwitheventsregardingselections,refertotheSelectionChangedEventArgs('SelectionChangedEventArgsClass'intheon-linedocumentation)class.
ToselectallthecellsinasheetusetheRowCount('RowCountProperty'intheon-linedocumentation)andColumnCount('ColumnCountProperty'intheon-linedocumentation)propertiesforthatsheet,asinthislineofcode:
FpSpread1.ActiveSheet.Models.Selection.SetSelection(0, 0, FpSpread1.ActiveSheet.RowCount, FpSpread1.ActiveSheet.ColumnCount)
TheDefaultSheetSelectionModelclass(andIDisjointSelectioninterface)GetSelectionsmethodreturns-1foreithertheRowCountortheColumnCountifallthecellsinthatroworcolumnareselected,aswhentheenduserclicksonaheadertomakeaselection.
Forinformationontheunderlyingmodelforselections,refertoUnderstandingtheSelectionModel.
UsingaShortcut
Toaddaselection,usetheSheetView'sAddSelection('AddSelectionMethod'intheon-linedocumentation)methodfromtheSheetsshortcut,specifyingthenecessaryparameters.
Example
Thisexamplecodeselectstworangesofcells.
C#// Set the sheet to allow multiple range selections.fpSpread1.Sheets[0].SelectionPolicy = FarPoint.Win.Spread.Model.SelectionPolicy.MultiRange;// Select cells C3 through D4.fpSpread1.Sheets[0].AddSelection(2, 2, 2, 2);// Select cells F6 through H8.fpSpread1.Sheets[0].AddSelection(5, 5, 3, 3);
VB' Set the sheet to allow multiple range selections.FpSpread1.Sheets(0).SelectionPolicy = FarPoint.Win.Spread.Model.SelectionPolicy.MultiRange' Select cells C3 through D4.FpSpread1.Sheets(0).AddSelection(2, 2, 2, 2)' Select cells F6 through H8.FpSpread1.Sheets(0).AddSelection(5, 5, 3, 3)
UsingCode
Toaddaselection,usetheAddSelection('AddSelectionMethod'intheon-linedocumentation)methodfromtheSheetsshortcut,specifyingthenecessaryparameters.ThenassigntheSheetView('SheetViewClass'intheon-linedocumentation)objecttoasheetinthecomponent.
Example
Thisexamplecodeselectstworangesofcells.
C#FarPoint.Win.Spread.SheetView newsheet=new FarPoint.Win.Spread.SheetView();
Spread Windows Forms Developer’s Guide 250
Copyright © GrapeCity, Inc. All rights reserved.
// Add two selections.newsheet.SelectionPolicy = FarPoint.Win.Spread.Model.SelectionPolicy.MultiRange;newsheet.AddSelection(2, 2, 2, 2);newsheet.AddSelection(5, 5, 3, 3);// Assign the SheetView to a sheet in the component.fpSpread1.Sheets[0] = newsheet;
VBDim newsheet As New FarPoint.Win.Spread.SheetView()' Add two selections.newsheet.SelectionPolicy = FarPoint.Win.Spread.Model.SelectionPolicy.MultiRangenewsheet.AddSelection(2, 2, 2, 2)newsheet.AddSelection(5, 5, 3, 3)' Assign the SheetView to a sheet in the component.FpSpread1.Sheets(0) = newsheet
Hiding the Selection When Focus is Lost
Bydefault,theSpreadcomponentdisplaysthefocusrectangleandhighlightsselections,regardlessofwhetherthecomponenthasthefocus.Ifyouprefer,youcansetthecomponenttohidethefocusrectangleandselectionhighlightingwhenthecomponentdoesnothavethefocus.Inthiscase,thecomponentstilldisplaysthefocusandhighlightselectionswhenthecomponentregainsthefocus.(ThisdoesnotapplywhenEditModePermanent('EditModePermanentProperty'intheon-linedocumentation)issettoTrue,inwhichcasethefocusrectangleandselectionhighlightingarenotdisplayed.)FormoreinformationrefertotheRetainSelectionBlock('RetainSelectionBlockProperty'intheon-linedocumentation)propertyoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class.
Youcanspecifythateditmodeisalwaysoninthespreadsheet.Wheneditmodeisalwayson,thespreadsheetactslikeaform,wheretheusercanenterdatainanydatafieldandthefocusrectangleisnotdisplayed.OnlyablinkingI-barisdisplayedinacelltoshowthecursor.FormoreinformationrefertotheEditModePermanent('EditModePermanentProperty'intheon-linedocumentation)propertyoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class.
Formoreinformationaboutthefocusindicator,refertoCustomizingtheFocusIndicatorforaCell.
Using Application Tags
Youcanaddanapplicationtagtoasheet,toaroworcolumn,ortoacellinthespreadsheet.
AddingaTagtoaSheetAddingaTagtoaRoworColumnAddingaTagtoaCell
Adding a Tag to a Sheet
Youcanaddanapplicationtagtoasheet.Ifyouprefer,youcanassociatedatawithanycellinthespreadsheet,orthecellsinacolumn,arow,ortheentirespreadsheet.Thestringdatacanbeusedtointeractwithacellortoprovideinformationtotheapplicationyoucreate.Thesheetdata,orsheettag,issimilartoitemdatayoucanprovideforthespreadsheet,columns,orrows.
Becausethesheettagisdeclaredasanobject,itisveryflexible;itcanbeanumber,aboolean,astring,oraninstanceofaclass.
Formoreinformationontags,refertotheTag('TagProperty'intheon-linedocumentation)propertyintheSheetView('SheetViewClass'intheon-linedocumentation)classandtheGetCellFromTag('GetCellFromTagMethod'intheon-linedocumentation)methodintheSheetView('SheetViewClass'intheon-linedocumentation)class.
Spread Windows Forms Developer’s Guide 251
Copyright © GrapeCity, Inc. All rights reserved.
Adding a Tag to a Row or Column
Youcanaddanapplicationtagtoaroworcolumn.Ifyouprefer,youcanassociatedatawithanycellinthespreadsheet,orthecellsinacolumn,arow,ortheentirespreadsheet.Thestringdatacanbeusedtointeractwitharoworcolumn,ortoprovideinformationtotheapplicationyoucreate.Therowdata(columndata),orrowtag(columntag),issimilartoitemdatayoucanprovideforthespreadsheetorcells.
Sincetherowtag(columntag)isdeclaredasanobject,itisveryflexible;itcanbeanumber,aboolean,astring,oraninstanceofaclass.
Formoreinformationontags,refertotheTag('TagProperty'intheon-linedocumentation)propertyintheRow('RowProperty'intheon-linedocumentation)classorColumn('ColumnProperty'intheon-linedocumentation)classandtheGetCellFromTag('GetCellFromTagMethod'intheon-linedocumentation)methodintheSheetView('SheetViewClass'intheon-linedocumentation)class.
Adding a Tag to a Cell
Youcanaddanapplicationtagtoacellorrangeofcells.Ifyouprefer,youcanassociatedatawithanycellinthespreadsheet,orthecellsinacolumn,arow,ortheentirespreadsheet.Thestringdatacanbeusedtointeractwithacellortoprovideinformationtotheapplicationyoucreate.Thecelldata,orcelltag,issimilartoitemdatayoucanprovideforthespreadsheet,columns,orrows.
Thecelltagisfortheapplicationmuchlikethecellnoteisfortheenduser.Thecellnotecontainsanextrabitofhuman-readableinformationthatisusefultotheenduser.Thecelltagallowstheapplicationtoattachanextrabitofcomputer-readableinformationtoacell.Theinformationcanbewhateverisusefultotheapplication.Forexample,supposetheapplicationismanuallypopulatinganunboundsheetwithvaluesfromaDataTable.TheapplicationcouldusethecelltagtoindicatetheDataRowintheDataTablefromwhichthecellvaluewasobtained(celltag=DataRow).Asanotherexample,theapplicationcouldusethecelltagasadirtyflag(celltag=Trueindicatesthatthecellneedstobeprocessed).
Sincethecelltagisdeclaredasanobject,itisveryflexible;itcanbeanumber,aboolean,astring,oraninstanceofaclass.
Formoreinformationontags,refertotheTag('TagProperty'intheon-linedocumentation)propertyintheCell('CellClass'intheon-linedocumentation)classandtheGetCellFromTag('GetCellFromTagMethod'intheon-linedocumentation)methodintheSheetView('SheetViewClass'intheon-linedocumentation)class.
UsingaShortcut
SettheTag('TagProperty'intheon-linedocumentation)propertyforthecellsinthesheetoftheSpreadcomponent.
Example
ThisexamplecodesetstheTag('TagProperty'intheon-linedocumentation)propertyforarangeofCellobjects.
C#fpSpread1.Sheets[0].Cells[1, 1, 3, 3].Tag = "This is the tag that describes the value.";fpSpread1.Sheets[0].Cells[1, 1, 3, 3].Value = "Value Here";
VBFpSpread1.Sheets(0).Cells(1, 1, 3, 3).Tag = "This is the tag that describes the value."
Spread Windows Forms Developer’s Guide 252
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.Sheets(0).Cells(1, 1, 3, 3).Value = "Value Here"
UsingCode
SettheTag('TagProperty'intheon-linedocumentation)propertyfortheCell('CellClass'intheon-linedocumentation)objectforarangeofcells.
Example
ThisexamplecodesetstheTag('TagProperty'intheon-linedocumentation)propertyforarangeofCellobjects.
C#FarPoint.Win.Spread.Cell range1;range1 = fpSpread1.ActiveSheet.Cells[1, 1, 3, 3];range1.Value = "Value Here";range1.Tag = "This is the tag that describes the value.";
VBDim range1 As FarPoint.Win.Spread.Cellrange1 = FpSpread1.ActiveSheet.Cells(1, 1, 3, 3)range1.Value = "Value Here"range1.Tag = "This is the tag that describes the value."
Setting and Resetting User Interaction
Youcansetvariousaspectsofuserinteraction.Ifyoueverneedtoresetthecomponentbacktoitsdefaultvaluesorclearvaluesinordertostartover,followthetopicsinthissection.
AllowingUserFunctionalityResettingPartsoftheInterfaceClearingorRemovingPartsoftheInterface
Allowing User Functionality
ThereareseveralaspectsoftheSpreadcomponentthatcanbesettoalloworrestricthowtheusercaninteractwiththecomponent.
Hereisalistsummarizingthethingsyoucanallowtheusertodo(orpreventtheuserfromdoing)withthedataareaofthecomponent:
Userfunctionalitytoallow
Relatedpropertyormethod
Draganddropcelldata
FpSpread.AllowDragDrop('AllowDragDropProperty'intheon-linedocumentation)property
Dragandfillcelldata FpSpread.AllowDragFill('AllowDragFillProperty'intheon-linedocumentation)property
Editcellnotes SheetView.AllowNoteEdit('AllowNoteEditProperty'intheon-linedocumentation)property
Spread Windows Forms Developer’s Guide 253
Copyright © GrapeCity, Inc. All rights reserved.
Enterformulas FpSpread.AllowUserFormulas('AllowUserFormulasProperty'intheon-linedocumentation)property
Filterrows Column.AllowAutoFilter('AllowAutoFilterProperty'intheon-linedocumentation)property
Expandorcollapsehierarchy
GetRowExpandable('GetRowExpandableMethod'intheon-linedocumentation),SetRowExpandable('SetRowExpandableMethod'intheon-linedocumentation)methods
Moverowsandcolumns
FpSpread.AllowRowMove('AllowRowMoveProperty'intheon-linedocumentation)propertyandFpSpread.AllowColumnMove('AllowColumnMoveProperty'intheon-linedocumentation)property
Performastandardsearch
FpSpread.SearchWithDialog('SearchWithDialogMethod'intheon-linedocumentation)method)
Performanadvancedsearch
FpSpread.SearchWithDialogAdvanced('SearchWithDialogAdvancedMethod'intheon-linedocumentation)method
Resizerowsorcolumns
Column.Resizable('ResizableProperty'intheon-linedocumentation)propertyandRow.Resizable('ResizableProperty'intheon-linedocumentation)property
Sortbyclickingthesortindicatorinthecolumnheader
Column.AllowAutoSort('AllowAutoSortProperty'intheon-linedocumentation)property
Hereisalistsummarizingthethingsyoucanallowtheusertodo(orpreventtheuserfromdoing)withthecomponent:
Userfunctionalitytoallow
Relatedpropertyormethod
Restrictaccesstorowsorcolumns
SheetView.RestrictColumns('RestrictColumnsProperty'intheon-linedocumentation)property
SheetView.RestrictRows('RestrictRowsProperty'intheon-linedocumentation)property
Zoom,orscalethedisplayofthecomponent
FpSpread.AllowUserZoom('AllowUserZoomProperty'intheon-linedocumentation)property
UseofClipboardshortcuts(keys)
FarPoint.Win.SuperEditBase.AllowClipboardKeys('AllowClipboardKeysProperty'intheon-linedocumentation)property
Editthesheetnames FpSpread.TabStrip.Editable('EditableProperty'intheon-linedocumentation)property
Hereisalistofthingsyoucanallowtheusertodo(orpreventtheuserfromdoing)withtheshapes(onthedrawingspacelayer):
Userfunctionalitytoallow
Relatedpropertyormethod
Moveshapes PSObject.CanMove('CanMoveProperty'intheon-linedocumentation)property
Resizeshapes PSObject.CanSize('CanSizeProperty'intheon-linedocumentation)property
Rotateshapes PSObject.CanRotate('CanRotateProperty'intheon-linedocumentation)property
Youcancustomizehowtheuserinteractswiththekeyboard.Formoreinformation,refertoManagingKeyboard
Spread Windows Forms Developer’s Guide 254
Copyright © GrapeCity, Inc. All rights reserved.
Interaction.
Youcanalsocustomizehowtheuserinteractswithprinting.Formoreinformation,refertoManagingPrinting.
Formoreinformationonshapes,refertoCustomizingDrawing.
Resetting Parts of the Interface
YoucanresetvarioussettingsonvariouspartsoftheSpreadcomponentinterfacebacktodefaultororiginalvalues.Youcanalsoclearpartsofthedataareaofvariousitems,bothdataandformatting.
Thewaysinwhichpartsofthecomponentcanberesetinclude:
ResetthecomponenttoitsoriginalstateusingtheFpSpread('FpSpreadClass'intheon-linedocumentation)classReset('ResetMethod'intheon-linedocumentation)method.ResetthesizeofthecomponenttoitsoriginalsizeusingtheFpSpread('FpSpreadClass'intheon-linedocumentation)classDefaultSize('DefaultSizeProperty'intheon-linedocumentation)property.ResetthesheettoitsoriginalstateusingtheSheetView('SheetViewClass'intheon-linedocumentation)classReset('ResetMethod'intheon-linedocumentation)method.ResettheskinpropertiesforasheetorsheetsusingtheDefaultSkins('DefaultSkinsClass'intheon-linedocumentation)classReset('ResetMethod'intheon-linedocumentation)method.ResetthevalueofacellorthetextinacelltoemptyusingtheCell('CellClass'intheon-linedocumentation)class,ResetText('ResetTextMethod'intheon-linedocumentation)orResetValue('ResetValueMethod'intheon-linedocumentation)method.ResetallthenamedstylepropertiestotheirdefaultvaluesusingtheNamedStyle('NamedStyleClass'intheon-linedocumentation)classReset('ResetMethod'intheon-linedocumentation)method.Therearealsoindividualresetmethodsforeachofthesettingsinastyle:ResetallthestylesettingsintheStyleInfo('StyleInfoClass'intheon-linedocumentation)objecttothedefaultsettingsusingtheStyleInfo('StyleInfoClass'intheon-linedocumentation)classReset('ResetMethod'intheon-linedocumentation)method.
Resetthesettingsforcells,rows,orcolumnsusingtheindividualresetmethodsforeachsettingintheCell('CellClass'intheon-linedocumentation)orRow('RowClass'intheon-linedocumentation)orColumn('ColumnClass'intheon-linedocumentation)class:
ResettingDesired MethodNameBackgroundcolorforindividualcellsorforroworcolumnofcells
ResetBackColor('ResetBackColorMethod'intheon-linedocumentation)
Borderforindividualcellsorforroworcolumnofcells
ResetBorder('ResetBorderMethod'intheon-linedocumentation)
Celltypeforindividualcellsorforroworcolumnofcells
ResetCellType('ResetCellTypeMethod'intheon-linedocumentation)
Textfontforindividualcellsorforroworcolumnofcells
ResetFont('ResetFontMethod'intheon-linedocumentation)
Foregroundcolorforindividualcellsorforroworcolumnofcells
ResetForeColor('ResetForeColorMethod'intheon-linedocumentation)
Rowheight ResetHeight('ResetHeightMethod'intheon-linedocumentation)
Cellcontentshorizontalalignmentforindividualcellsorforroworcolumnofcells
ResetHorizontalAlignment('ResetHorizontalAlignmentMethod'intheon-linedocumentation)
Cellheaderlabel ResetLabel('ResetLabelMethod'intheon-line
Spread Windows Forms Developer’s Guide 255
Copyright © GrapeCity, Inc. All rights reserved.
documentation)
Lockedstatusforindividualcellsorforroworcolumnofcells
ResetLocked('ResetLockedMethod'intheon-linedocumentation)
Mergepolicyforaroworcolumnofcells ResetMergePolicy('ResetMergePolicyMethod'intheon-linedocumentation)
Cellnoteindicatorcolorforindividualcellsorforroworcolumnofcells
ResetNoteIndicatorColor('ResetNoteIndicatorColorMethod'intheon-linedocumentation)
Parentstylenameforindividualcellsorforroworcolumnofcells
ResetParentStyleName('ResetParentStyleNameMethod'intheon-linedocumentation)
Columnresizable ResetResizable('ResetResizableMethod'intheon-linedocumentation)
Columnsortindicator ResetSortIndicator('ResetSortIndicatorMethod'intheon-linedocumentation)
Cellcontentsverticalalignmentforindividualcellsorforroworcolumnofcells
ResetVerticalAlignment('ResetVerticalAlignmentMethod'intheon-linedocumentation)
Roworcolumnvisible ResetVisible('ResetVisibleMethod'intheon-linedocumentation)
Columnwidth ResetWidth('ResetWidthMethod'intheon-linedocumentation)
ResetallthenamedstylepropertiestotheirdefaultvaluesusingtheNamedStyle('NamedStyleClass'intheon-linedocumentation)classReset('ResetMethod'intheon-linedocumentation)method.Therearealsoindividualresetmethodsforeachofthesettingsinastyle:
MethodName ResettingDesiredReset('ResetMethod'intheon-linedocumentation) Allthepropertiesofthestyle
ResetBackColor('ResetBackColorMethod'intheon-linedocumentation)
Backgroundcolorofacell
ResetBorder('ResetBorderMethod'intheon-linedocumentation)
Borderaroundacell
ResetCanFocus('ResetCanFocusMethod'intheon-linedocumentation)
Whetherthecellcanreceivefocus
ResetCellType('ResetCellTypeMethod'intheon-linedocumentation)
Celltypeofthecell
ResetEditor('ResetEditorMethod'intheon-linedocumentation)
Editorusedforeditingthecell
ResetFont('ResetFontMethod'intheon-linedocumentation) Fontfaceusedinthetextofthecell
ResetForeColor('ResetForeColorMethod'intheon-linedocumentation)
Text(foreground)colorinacell
ResetFormatter('ResetFormatterMethod'intheon-linedocumentation)
Formatterforformattingthecontentsofthecell
ResetHorizontalAlignment('ResetHorizontalAlignmentMethod'intheon-linedocumentation)
horizontalalignmentoftextinacell
ResetLocked('ResetLockedMethod'intheon-linedocumentation)
Whetherthecellismarkedaslocked
ResetName('ResetNameMethod'intheon-linedocumentation) Defaultnameofthestyle
Spread Windows Forms Developer’s Guide 256
Copyright © GrapeCity, Inc. All rights reserved.
ResetNoteIndicatorColor('ResetNoteIndicatorColorMethod'intheon-linedocumentation)
Colorofthecellnoteindicator
ResetNoteStyle('ResetNoteStyleMethod'intheon-linedocumentation)
Cellnotestyle
ResetParent('ResetParentMethod'intheon-linedocumentation)(InheritedfromStyleInfo)
Parentstylename
ResetProperty('ResetPropertyMethod'intheon-linedocumentation)
Specifiedsettingproperty
ResetRenderer('ResetRendererMethod'intheon-linedocumentation)
Rendererforpaintingthecell
ResetTabStop('ResetTabStopMethod'intheon-linedocumentation)
WhethertheusercansetfocustothecellusingtheTabkey
ResetVerticalAlignment('ResetVerticalAlignmentMethod'intheon-linedocumentation)
Verticalalignmentoftextinacell
Ifyouaresettingthebackgroundcolorforanindividualcell,thenResetBackColorresetsthatcell'sbackgroundcolortoitsdefaultcolor.If,instead,yousetthebackgroundcolorusingtheBackColorpropertyforaRowobject,thenyoumustusetheResetBackColorforthatrow.IfyouwanttoloopallthecellssettingthecolortoWhite,youcanspeedthisupbyinvalidatingthepaintingintheSpreadwhileyouareloopingthecellsasshowninthefollowingcode.
VisualBasicFpSpread1.SuspendLayout()FpSpread1.Sheets(0).Cells(0, 0, 499, 499).BackColor = Color.WhiteFpSpread1.ResumeLayout(True)
C#fpSpread1.SuspendLayout();fpSpread1.Sheets[0].Cells(0, 0, 499, 499).BackColor = Color.White;fpSpread1.ResumeLayout(true);
Resettingthecomponentorasheettoitsdefaultsettingsreturnsthecomponentorthesheettoitsinitialstatepriortoanydesign-timeorrun-timechanges.Itclearsdata,resetscolors,andreturnscellstothedefaultcelltype.Resettingthecomponentresetseverythinginthecomponenttothestatewhenthecomponentisfirstdrawnontheform.
Note:Resettingthecomponentorasheetclearsthedatainthesheet(s)aswellastheformatting.Ifyouprovideawayforuserstoresettheirsheet(s),besuretohavethemconfirmtheactionbeforeresettingthesheet(s).
YoucanfindoutthedefaultsizeofthecomponentusingtheFpSpreadDefaultSize('DefaultSizeProperty'intheon-linedocumentation)property.
Formoreinformationaboutclearingdata,refertoRemovingDatafromaSheet.
ForinformationonresettingvaluescreatingduringthedesignusingSpreadDesigner,refertotheexplanationofthisprocedureintheSpreadDesignerGuide(on-linedocumentation).
Clearing or Removing Parts of the Interface
YoucanresetvarioussettingsonvariouspartsoftheSpreadcomponentinterfacebacktodefaultororiginalvalues.Youcanalsoclearpartsofthedataareaofvariousitems,bothdataandformatting.
Formoreinformationaboutclearingdata,refertoRemovingDatafromaSheet.
Spread Windows Forms Developer’s Guide 257
Copyright © GrapeCity, Inc. All rights reserved.
Customizing Drawing
Eachsheetcanhaveitsowndrawinglayerthatcancontainbuilt-inshapes,customshapes,andannotations(free-handdrawings).Shapesandannotationsareaformofgraphicsthataredrawnonaseparatelayerfromthatofthespreadsheet.Thisdrawinglayer,ordrawingspace,isinfrontofthespreadsheetinthedisplay.Shapescanbemadeallorpartiallytransparenttorevealthespreadsheetbehind.Anexampleofamultiple-sidedshapedrawninthespaceaboveaspreadsheetisshowninthisfiguretohelpyouunderstandtheconceptoflayers.Becausetheshapesappearonthisseparatelayerfromthesheetandcanbethoughttofloatabovethespreadsheet,theyaresometimescalledfloatingobjects.
Thesetopicscanhelpyoucustomizetheinteractionwiththedrawinglayer:
WorkingwithShapesinCodeWorkingwithAnnotationsAllowingtheUsertoDrawwithaTabletPCCreatingCameraShapes
Forinstance,inaspreadsheetyoucouldcreateashapelikea"star"orothergraphicthatcouldhighlightdataorpointtheusertosomeaspectofworkingwiththesheetandplacethisonalayerindependentofthecellsandtheirvalues.Youcouldthenproceedtocustomizeaspectsofthatstarorgraphicfromsizeandbackgroundcolortorotationangleorgradient.Theshapesareavailableincode(eachshapebeingaseparateclassintheDrawingSpacenamespace)orfromtheInsertmenuintheSpreadDesigner.Youcanuseshapesandannotationtodrawattentiontopartsofyourspreadsheetoremphasizesomeinformationorprocessinvolvingtheuseofthespreadsheet.Forexample,youcandisplayalogoonyoursheet,showaprocesswithflowchart-likegraphics,oruseshapestosimplyhighlightaparticularresult.
Formoreinformationonshapes,refertotheSpreadDesignerGuide(on-linedocumentation).
Working with Shapes in Code
Thereareseveralbuilt-inshapesforyoutouseonasheet.Eachshapecanberotatedandresized,andtheirabilitytoberotatedandresizedbytheendusercanbeconstrained.Whenselected,theshapehasresizehandleswithwhichyoucanadjustthesizeandarotatehandlewithwhichyoucanrotatetheshape.Colors,shadows,andtransparencycanbeadjusted.MostusersfinditeasytocreateandplacetheshapesusingSpreadDesigner.Youmayalsocreateandplaceshapesusingcode.
TheDynamicSize('DynamicSizeProperty'intheon-linedocumentation)andDynamicMove('DynamicMoveProperty'intheon-linedocumentation)propertiesspecifyhowshapesaremovedandresizedwhenhidingorshowing,resizing,ormovingrowsorcolumnsthatintersectwiththeshapeorthatappearbeforetheshape(forexample,resizingacolumntotheleftorarowabovetheshape).
Spread Windows Forms Developer’s Guide 258
Copyright © GrapeCity, Inc. All rights reserved.
Thefollowingoptionsareavailable:
Moveandsizewithcells(DynamicMove=TrueandDynamicSize=True)Move,butdonotsizewithcells(DynamicMove=TrueandDynamicSize=False)Donotmoveorsizewithcells(DynamicMove=FalseandDynamicSize=False)
Hidingcolumnsandrowsthatcontainashapehidestheshapeaswell.
TheFarPoint.Win.Spread.DrawingSpace.DrawingToolbarclassallowsyoutobringuptheshapetoolbaratrun-time.
BesidesworkingwithshapesfromSpreadDesigner,youcanalsoaddandremoveshapesprogrammatically.YoucanperformthefollowingworkwithshapesusingthecorrespondingmethodsintheSheetView('SheetViewClass'intheon-linedocumentation)class:
AddashapeincodeusingtheAddShape('AddShapeMethod'intheon-linedocumentation)methodRemoveashapeusingtheRemoveShape('RemoveShapeMethod'intheon-linedocumentation)methodRemovealltheshapesusingtheClearShapes('ClearShapesMethod'intheon-linedocumentation)methodGetashapeusingtheGetShape('GetShapeMethod'intheon-linedocumentation)method
Toaddashapeusingcode,refertotheDrawingSpacenamespaceandselecttheparticularshapeanddefineitspropertiesusingcode.Whilethereismuchflexibilityinsettingupshapes,therearesomelimitations.ThesearelistedintheAssemblyReference(on-linedocumentation)inthetopicsfortheshapemethodsandclasses.Forexample,fortheLineShape('LineShapeClass'intheon-linedocumentation)class,themaximumthicknessforalineis64pixels.
Thesimplestwaytoaddashapecanbeperformedinonelineofcode,asshowninthefollowingexample:
FpSpread1.ActiveSheet.AddShape(New FarPoint.Win.Spread.DrawingSpace.RectangleShape())
Thisconstructsabasicrectangleshapewithdefaultpropertiesandaddstheshapetheactivesheet.Thefollowingexamplecreatesashapewithcustomsettings.
Formoreinformationonshapes,refertotheSpreadDesignerGuide(on-linedocumentation).
Example
Thisexamplecreatesashape,changessomeofthemostusedproperties,andthenaddsittotheactivesheet.
C# // Create a new shape. FarPoint.Win.Spread.DrawingSpace.RectangleShape rShape = new FarPoint.Win.Spread.DrawingSpace.RectangleShape(); // Assign a name, overriding the unique default assigned name. // All shape names within a sheet must be unique. rShape.Name = "rShape1"; // Assign a location at which to start the display of the shape. rShape.Top = 20; rShape.Left = 60; // Alternatively, you could set the Location property // with a Point object as in: // rShape.Location = new Point(20, 60);
// Assign a custom fill color to the shape. rShape.BackColor = Color.Blue; // Assign a size to the shape. rShape.Width = 100; rShape.Height = 100; // Alternatively, you could set the Size property
Spread Windows Forms Developer’s Guide 259
Copyright © GrapeCity, Inc. All rights reserved.
// with a Size object as in: // rShape.Size = new Size(100, 100); // Add the shape to the sheet so that it appears on that sheet. fpSpread1.ActiveSheet.AddShape(rShape); // This code will display the shape property dialog //FarPoint.Win.Spread.DrawingSpace.ShapeProps f = new FarPoint.Win.Spread.DrawingSpace.ShapeProps(fpSpread1); //f.Shape = fpSpread1.Sheets[0].DrawingContainer.GetShape("rShape1"); //f.ShowDialog();
VB ' Create a shape. Dim rShape As New FarPoint.Win.Spread.DrawingSpace.RectangleShape() ' Assign a name, overriding the unique default assigned name. ' All shape names within a sheet must be unique. rShape.Name = "rShape1" ' Assign a location at which to start the display of the shape. rShape.Top = 20 rShape.Left = 60 ' Alternatively, you could set the Location property ' with a Point object as in: ' rShape.Location = new Point(20, 60)
' Assign a custom fill color to the shape. rShape.BackColor = Color.Blue ' Assign a size to the shape. rShape.Width = 100 rShape.Height = 100 ' Alternatively, you could set the Size property ' with a Size object as in: ' rShape.Size = new Size(100, 100) ' Add the shape to the sheet so that it appears on that sheet. FpSpread1.ActiveSheet.AddShape(rShape) ' This code will display the shape property dialog ' Dim f As New 'FarPoint.Win.Spread.DrawingSpace.ShapeProps(FpSpread1) 'f.Shape = 'FpSpread1.Sheets(0).DrawingContainer.GetShape("rShape1") 'f.ShowDialog()
Working with Annotations
Youcanaddfree-handdrawingtothedrawinglayerofthesheetusingannotationmode.Annotationmodeallowstheusertodrawinfree-handmodeontheshapeslayerandtosavetheannotationonthesheetasashape.
UseStartAnnotationMode('StartAnnotationModeMethod'intheon-linedocumentation)andStopAnnotationMode('StopAnnotationModeMethod'intheon-linedocumentation)toturnonandofftheabilityoftheusertodrawonthedrawinglayer.Therearecorrespondingevents,AnnotationModeStarting('AnnotationModeStartingEvent'intheon-linedocumentation)andAnnotationModeEnding('AnnotationModeEndingEvent'intheon-linedocumentation).YoucanalsocustomizewhatoccursusingtheOnAnnotationModeStarting('OnAnnotationModeStartingMethod'intheon-linedocumentation)andOnAnnotationModeEnding('OnAnnotationModeEndingMethod'intheon-linedocumentation)methods.
Bydefaultathinblacklineisdrawn.Youcanchangethisandyoucanhavethecomponentdisplayadialogfortheuser
Spread Windows Forms Developer’s Guide 260
Copyright © GrapeCity, Inc. All rights reserved.
toselectthedrawingpenorstencilorbitmappattern.
UsetheCloseFigureparameterifyouwanttoclosethedrawingbetweenthestartandendpointswithastraightline.
YoucanusetheCancelAnnotationMode('CancelAnnotationModeMethod'intheon-linedocumentation)tocancelannotationmodeandreturntonormalcelleditingmode.
Formoreinformationonbuilt-inandcustomshapesthatcanalsobeplacedonthedrawinglayer,refertoWorkingwithShapesinCode.
Allowing the User to Draw with a Tablet PC
Spreadprovidesalimitedsetoffunctionalityinsupportof"inking"onTabletPCsthatareenabledwithMicrosoft’sTabletPCSDK.MicrosoftWindowsXPTabletPCEditionisasupersetoftheWindowsXPProfessionaloperatingsystemthataddspen-basedcapabilitiestofullnotebookcomputers.ThisfeatureinSpreadiscalled"inknotation".Inthisversioninkingonagivenviewportofthespreadsheetisallowed.
Thedrawingfeatureallowstheuseofapen(stylus)ontheTabletPCfordrawingandwritingonthespreadsheet.Thisprocess,sometimescalledinking,allowsuserstowriteindigitalink,whichappearsasnatural-lookinghandwritingonthescreen.Thespreadsheetsavestheinknotation.
GettingSetUp
Beforeyoucanusethisfeature,youmustperformthesesteps:
1. GototheMicrosoftsiteanddownloadthelatestversionTabletPCSDK.2. MakesuretheInkassemblyisintheGACbeforerunningtheStartInkNotationmethodinSpread.
UsingInkNotation
Touseinknotation,useoneoftheFpSpread.StartInkNotation('StartInkNotationMethod'intheon-linedocumentation)methods.Therearevariousoverloadstoallowyoutospecifytheviewport,alpha-blending,andbackgroundcoloroftheinkviewport,asfollows:
Thedefaultsettingthatspecifiestheactiveviewportastheviewportthatcanbeinkedin.Youspecifytheviewportthatwillallowinking.Youcanspecifythebackgroundcolorandalpha-blending(transparency)toallowyoutohighlighttheinkingviewportandseethespreadsheetunderneath.
WhenyoucalltheStartInkNotationmethod,SpreadcheckstoseeiftheInkassemblyisintheGAC.Ifitcannotfindit,themethodreturnsFalseandgoesnofurther.Ifitisthere,itloadsitandthenitloadstheFarPoint.Inkassembly(whichisinstalledwithSpread,butisnotloadeduntilnow).SpreadattemptstoloadFpInkdynamicallyatruntime,anditwillsucceedifFpInkisintheGAC,alongwithMicrosoft.Ink(theMSInkassembly).Microsoft.Inkispartofthe
Spread Windows Forms Developer’s Guide 261
Copyright © GrapeCity, Inc. All rights reserved.
MicrosoftTabletPCSDK.
Wheninking,thecursorchangestoadrawingpoint;youcandrawwiththestylus.Youfinishdrawingbyclickingtherightmousebuttontocallupthecontextmenu.ClickSaveNotationtosavethenotation,theinkingthatyouhavedone,totheSpreadcomponent.Thenotationissavedasa"shape"residingoverapartofthespreadsheet.Inkingisdoneonthedrawing/presentationspacelayer,sosimilartoshapes,theinkingisdrawnontopofthespreadsheet.Itisdrawnonlyintheviewport,notovertheheadersorscrollbarsorotherpartsoftheSpreadcomponent.Itappearsasashape,soitcanbeselected,moved,rotated,andresized.Whenitissaved,itisgivenanamebeginningwith"inkShape"andauniquenumber.
Whenyouwanttoerasewhatyouhavedone,right-clicktogetthecontextmenuandselectEraseMode,andthestylusbecomesaneraser,ormoreaccuratelyaselectorofwhatgetserased.Ifyouclickonastrokeorpartofaninknotation,iterasesthatsegment.Ifyouwriteincursiveandallthenotationiscontinuous,thenifselected,theentirenotationiserased.Thecontextmenuchoice,ClearNotation,clearstheentirenotation,regardlessofthenumberofdiscontinuousstrokes.
Ininknotation,thecursorchangestoapenpointwiththethicknessandcolor(blackisthedefault)ofthepen.
Whentheuserright-clicksonthemouse,acontextmenuisdisplayedasshowninthefollowingfigure.
TheInkModeisdisplayedcheckedwhiletheuserisinking(orwritingordrawing).InEraseMode,theuseriserasingtheinkingpreviouslydone,whicherasesthesegmentorstrokethatisclickedwheninEraseMode.WithSaveNotation,theuseracceptstheinknotationanditispermanentlydisplayedonthesheet.TheClearNotationclearsalloftheinknotationdrawnsincethelastsave.
Creating Camera Shapes
YoucancreateasnapshotofarangeofcellsandusethatasashapeintheSpreadcontrol.Thecellrangecancontainothershapesincludingcharts.Thefollowingimagedisplaysacamerashapethatcontainsachart.
FormoreinformationaboutusingtheSpreadDesignertoaddcamerashapes,seetheInsertMenu(on-line
Spread Windows Forms Developer’s Guide 262
Copyright © GrapeCity, Inc. All rights reserved.
documentation)topic.Ingeneral,propertiesthatapplytotheinterioroftheshape,donotapplytothecamerashape.
Thecamerashapecannotuseanothercamerashape.
UsingCode
1. CreateacamerashapeobjectbyusingtheSpreadCameraShape('SpreadCameraShapeClass'intheon-linedocumentation)class.
2. SpecifytherangeofcellsthatwillbecometheshapewiththeFormulaproperty.3. Setanyothershapeproperties.4. Addthecamerashapetothesheet.
Example
Thisexamplecreatesabluetriangle,addstexttoacell,andcreatesacamerashapethatincludesboth.Thefollowingimagedisplaysacamerashapethatcontainsatriangleshapeandacellwithtext.
C#fpSpread1.Sheets[0].Cells[1, 3].Text = "Test";FarPoint.Win.Spread.DrawingSpace.TriangleShape a = new FarPoint.Win.Spread.DrawingSpace.TriangleShape();a.BackColor = Color.Blue;fpSpread1.ActiveSheet.AddShape(a, 1, 1);FarPoint.Win.Spread.DrawingSpace.SpreadCameraShape test = new FarPoint.Win.Spread.DrawingSpace.SpreadCameraShape();test.Formula = "B1:D6";test.Location = new System.Drawing.Point(20, 20);fpSpread1.Sheets[0].AddShape(test);
VBFpSpread1.Sheets(0).Cells(1, 3).Text = "Test"Dim a As New FarPoint.Win.Spread.DrawingSpace.TriangleShapea.BackColor = Color.BlueFpSpread1.ActiveSheet.AddShape(a, 1, 1)Dim test As New FarPoint.Win.Spread.DrawingSpace.SpreadCameraShape()test.Formula = "B1:D6"test.Location = New System.Drawing.Point(20, 20)FpSpread1.Sheets(0).AddShape(test)
UsingtheSpreadDesigner
Spread Windows Forms Developer’s Guide 263
Copyright © GrapeCity, Inc. All rights reserved.
1. Selectablockofcellsinthedesigner.2. SelecttheInsertmenu.3. Selectthecamerashapeicon.4. Clickontheshapetomoveit.5. TheDrawingToolsmenuwithadditionaloptionsisdisplayed.6. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Spread Windows Forms Developer’s Guide 264
Copyright © GrapeCity, Inc. All rights reserved.
Customizing Row or Column Interaction
YoucancustomizevariousaspectsofuserinteractionofthespreadsheetintheSpreadcomponent.Thetasksthatrelatetocustomizingtheuserinteractionwiththespreadsheetinclude:
AllowingUserInteractionwithRowsandColumnsManagingFilteringofRowsofUserDataManagingGroupingofRowsofUserDataManagingOutlines(RangeGroups)ofRowsandColumnsManagingSortingofRowsofUserData
Youcancustomizewhatyouallowtheusertodo.Thereareseveralfeaturesthatarecoveredinvarioustopicsinthissection,buttheyaresummarizedinonetopicforeasyreferenceinAllowingUserFunctionality.
Tocustomizethestaticappearanceofrowsandcolumns,refertoCustomizingtheRoworColumnAppearance.
Tocustomizeotheraspectsofinteractivityatthesheetlevel,refertoCustomizingSheetInteractionandwithindividualcells,refertoCustomizingInteractioninCells.
Fordetailsonthespreadsheetobjects,refertothesemembersintheAssemblyReference:
Row('RowClass'intheon-linedocumentation)Rows('RowsClass'intheon-linedocumentation)AlternatingRow('AlternatingRowClass'intheon-linedocumentation)AlternatingRows('AlternatingRowsClass'intheon-linedocumentation)Column('ColumnProperty'intheon-linedocumentation)Columns('ColumnsClass'intheon-linedocumentation)
Allowing User Interaction with Rows and Columns
Youcancustomizetheuserinteractionwithrowsandcolumns.Tocustomizethisaspectofuserinteraction,youmayperformthefollowingtasks:
AllowingtheUsertoEnterDatainRowsorColumnsAllowingtheUsertoMoveRowsorColumnsAllowingtheUsertoResizeRowsorColumnsSettingFixed(Frozen)RowsorColumnsSettingupPreviewRows
Formoreinformationaboutinteractingwithrowsandcolumns,referto:
ResizingtheRoworColumntoFittheDataAllowingtheUsertoFilterRowsCustomizingUserSelectionofDataAllowingtheUsertoAutomaticallySortRows
Forinformationontheunderlyingmodelresponsibleforrowsandcolumns,refertotheUnderstandingtheAxisModel.
Formoreinformation,refertotheRow('RowClass'intheon-linedocumentation),Rows('RowsClass'intheon-linedocumentation),AlternatingRow('AlternatingRowClass'intheon-linedocumentation),AlternatingRows('AlternatingRowsClass'intheon-linedocumentation),Column('ColumnClass'intheon-linedocumentation),andColumns('ColumnsClass'intheon-linedocumentation)objectsintheAssemblyReference.
Allowing the User to Enter Data in Rows or Columns
Spread Windows Forms Developer’s Guide 265
Copyright © GrapeCity, Inc. All rights reserved.
Youcanrestricttheportionofthesheetinwhichtheusercanenterdata.Youcansetthesizeofthesheetintermsofrowsandcolumns.Youcanhiderowsorcolumnssotheuserdoesnothaveaccesstothematall,orsetthemasfrozensothatuserscanseethembutcannotmovethemoutofviewbyscrolling.Formoreinformationonhiddenrowsandcolumns,refertoShowingorHidingaRoworColumn.Forinformationonfrozenrowsandcolumns,refertoSettingFixed(Frozen)RowsorColumns.Forinformationonsettingthenumberofrowsandcolumnsinasheet,refertoCustomizingtheNumberofRowsorColumns.
Youcanrestricttheuserfromenteringdatabeyondthedataalreadyinthesheet.SettheRestrictRows('RestrictRowsProperty'intheon-linedocumentation)propertyandRestrictColumns('RestrictColumnsProperty'intheon-linedocumentation)propertytorestrictorallowtheusertoenterdatainaroworcolumnonasheetthatismorethanoneroworcolumnbeyondthelastroworcolumnthatcontainsdata.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selectthesheet.2. IntheBehaviorcategory,selecttheRestrictRows('RestrictRowsProperty'intheon-linedocumentation)ortheRestrictColumns('RestrictColumnsProperty'intheon-linedocumentation)property.
3. Clickthedrop-downarrowtodisplaythechoicesandselectthevalue(TrueorFalse).Repeatthisforeachproperty.
UsingCode
SettheRestrictRows('RestrictRowsProperty'intheon-linedocumentation)orRestrictColumns('RestrictColumnsProperty'intheon-linedocumentation)propertyforthesheet.
Example
C#fpSpread1.ActiveSheet.RestrictColumns = true;fpSpread1.ActiveSheet.RestrictRows = true;
VBFpSpread1.ActiveSheet.RestrictColumns = TrueFpSpread1.ActiveSheet.RestrictRows = True
UsingtheSpreadDesigner
1. SelectSheetfromthedrop-downcombolistlocatedonthetoprightsideoftheDesigner.2. FromtheBehaviorsection,selectTrueorFalseforRestrictRowsorRestrictColumns.3. FromtheFilemenu,selectSaveandExittosavethechanges.
Allowing the User to Move Rows or Columns
Youcanallowtheusertodragandmoverowsorcolumns.SettheAllowRowMove('AllowRowMoveProperty'intheon-linedocumentation)propertytoallowtheusertomoverowsandtheAllowColumnMove('AllowColumnMoveProperty'intheon-linedocumentation)propertytoallowtheusertomovecolumns.Ifyouwishtoallowtheusertomovemultiplerowsorcolumns,alsosettheAllowRowMoveMultiple('AllowRowMoveMultipleProperty'intheon-linedocumentation)orAllowColumnMoveMultiple('AllowColumnMoveMultipleProperty'intheon-linedocumentation)property.
Spread Windows Forms Developer’s Guide 266
Copyright © GrapeCity, Inc. All rights reserved.
YoucanhidethedragbandwhilemovingtheroworcolumnwiththeShowDragBandOnMoving('ShowDragBandOnMovingProperty'intheon-linedocumentation)property.
Fortheusertomoverowsorcolumns,theyleftclickontheheaderoftheroworcolumntomoveanddragtheheaderbackorforthovertheheaderareaandreleasethemouseovertheheaderofthedesireddestination(formultiplerowsorcolumns,selectthemfirst).Theroworcolumnthatisbeingmovedisshowninatransparentcloneattachedtothepointer,asshowninthisfigure,wherethefourthcolumnisbeingmovedtotheleft.
MovingtheRoworColumninCode
Torelocatearow,usetheSheetView.MoveRowmethod;toremovemultiplerowsatatime,usetheSheetView.RemoveRowsmethod.Torelocateacolumn,usetheSheetView.MoveColumnmethod;toremovemultiplecolumnsatatime,usetheSheetView.RemoveColumnsmethod.Alternatively,youcanusetheDefaultSheetAxisModel.Movemethod.
YoucanusetheGetColumnFromTagmethodtofindcolumnsbasedontheirTagproperty,whichyoucansetprogrammaticallytowhateveryouwant.YoucandothesamewiththeGetRowFromTagmethodforrows.
YoucanremovemorethanonecolumnatatimeusingtheRemovemethodonarangeofcolumnsorrows.Forexample,
FpSpread1.Sheets(0).Columns(1,5).Remove()
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. IntheMisccategory,selecttheAllowRowMoveortheAllowColumnMoveproperty.3. Clickthedrop-downarrowtodisplaythechoicesandselectthevalue(TrueorFalse).Repeatthisforeach
property.
UsingCode
SettheAllowRowMove('AllowRowMoveProperty'intheon-linedocumentation)orAllowColumnMove('AllowColumnMoveProperty'intheon-linedocumentation)propertyfortheFpSpread('FpSpreadClass'intheon-linedocumentation)component.
Spread Windows Forms Developer’s Guide 267
Copyright © GrapeCity, Inc. All rights reserved.
Example
Thisexampleallowstheusertomovecolumnsorrows.
C#fpSpread1.AllowRowMove = true;fpSpread1.AllowColumnMove = true;
VBFpSpread1.AllowRowMove = TrueFpSpread1.AllowColumnMove = True
UsingtheSpreadDesigner
1. SelectSpreadfromthedrop-downcombolistlocatedonthetoprightsideoftheDesigner.2. FromtheMiscsection,selectTrueorFalseforAllowRowMoveorAllowColumnMove.3. FromtheFilemenu,selectSaveandExittosavethechanges.
Allowing the User to Resize Rows or Columns
Youcanallowtheusertoadjustthesizeofaroworcolumninthesheet.SettheResizable('ResizableProperty'intheon-linedocumentation)propertyfortherowtoallowtheusertoresizerowsandtheResizable('ResizableProperty'intheon-linedocumentation)propertyforthecolumntoallowtheusertoresizecolumns.Theusercanalsodouble-clickontheborderbetweenthecolumnheaderstoresizethecolumntomatchthewidthoftheheadertext.
Foruserstoresizerowsorcolumns,theyleftclickontheedgeoftheheaderoftheroworcolumntoresizeanddragthesideoftheheaderandreleasethemouseatthedesiredsize.Whiletheleftmousebuttonisdown,abarisdisplayedalongwiththeresizepointerasshowninthefollowingfigure.Besuretoclickontherightedgeofthecolumnandbottomedgeoftherow.
Double-clickingontheroworcolumnedgeresizestheroworcolumntofitthetallestorwidestcontentofthatroworcolumn(preferredheightorwidth).Wrappedtextinthecolumnisignoredwhendouble-clickingonacolumndivider.Unwrappedtextisignoredwhendouble-clickingonarowdivider.YoucanspecifytheautomaticfitbehaviorwiththeAutoFitColumnOptions('AutoFitColumnOptionsProperty'intheon-linedocumentation)orAutoFitRowOptions('AutoFitRowOptionsProperty'intheon-linedocumentation)property.
Bydefault,userresizingofrowsorcolumnsisallowedforrowsandcolumnsinthedataareaandnotallowedfortheheaderarea.Incode,youcanresizerowandcolumnheaders,notjustdataarearowsandcolumns.YoucanoverridethedefaultbehaviorusingtheResizable('ResizableProperty'intheon-linedocumentation)propertyandpreventtheuserfromresizing.
Spread Windows Forms Developer’s Guide 268
Copyright © GrapeCity, Inc. All rights reserved.
Thefollowingcodeturnsonresizingforasinglecolumnintherowheader:
spread.Sheets[0].RowHeader.Columns[0].Resizable = true;
Thefollowingcodeturnsonresizingforallcolumnsintherowheader:
spread.Sheets[0].RowHeader.Columns.Default.Resizable = true;
YoucandetermineifaroworcolumncanberesizedbytheuserwiththesemethodsintheSheetViewclass:
GetColumnSizeable('GetColumnSizeableMethod'intheon-linedocumentation)SetColumnSizeable('SetColumnSizeableMethod'intheon-linedocumentation)GetRowSizeable('GetRowSizeableMethod'intheon-linedocumentation)SetRowSizeable('SetRowSizeableMethod'intheon-linedocumentation)
Toresizetherowsorcolumnbasedonthesizeofthedata,refertoResizingtheRoworColumntoFittheData.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selectSheet.2. InthePropertieswindow,selectColumnorselectRow,andclickonthebuttonfortheCell,Column,andRowEditor.
3. IntheEditor,selectacolumnorarow.4. SelecttheResizableproperty.5. Clickthedrop-downarrowtodisplaythechoicesandselectthevalue(TrueorFalse).Repeatthisforeachproperty.
UsingCode
SettheResizable('ResizableProperty'intheon-linedocumentation)propertyfortheroworResizable('ResizableProperty'intheon-linedocumentation)propertyforthecolumn.
Example
Thefollowingexamplesetsthesheettoallowthefirstrowandfirstcolumntoberesizable.
C#fpSpread1.Sheets[0].Columns[0].Resizable = true;fpSpread1.Sheets[0].Rows[0].Resizable = true;
VBFpSpread1.Sheets(0).Columns(0).Resizable = TrueFpSpread1.Sheets(0).Rows(0).Resizable = True
UsingtheSpreadDesigner
1. SelectSheetfromthedrop-downcombolistlocatedonthetoprightsideoftheDesigner.2. FromtheAppearancecategory,selectColumnorselectRow,andclickonthebuttonfortheCell,Column,andRowEditor.
3. IntheEditor,selectacolumnorarow.4. SelecttheResizableproperty.5. Selectthevaluefromthedrop-downlist(eitherTrueorFalse).6. FromtheFilemenu,selectSaveandExittosavethechanges.
Spread Windows Forms Developer’s Guide 269
Copyright © GrapeCity, Inc. All rights reserved.
Setting Fixed (Frozen) Rows or Columns
Youcanfreeze(makeunscrollable)anumberofeitherrowsorcolumnsorbothinasheet.Youcanfreezeanynumberoftoprows,calledleadingrowsoranynumberofleft-mostcolumns,calledleadingcolumns.Youcanalsofreezeanynumberofthetrailingbottomrowsortrailingright-mostcolumns.Thefrozenleadingrowsandcolumnsstayatthetopandleftoftheviewregardlessofthescrolling.Thefrozentrailingrowsandcolumnsstayatthebottomandrightoftheviewregardlessofthescrolling.
Thefigurebelowdisplaysonefrozentrailingrowandcolumnthatstayinview:
Propertiesinvolvedwithfrozenrowsandcolumnsare:
FrozenRowCount('FrozenRowCountProperty'intheon-linedocumentation)FrozenColumnCount('FrozenColumnCountProperty'intheon-linedocumentation)FrozenTrailingColumnCount('FrozenTrailingColumnCountProperty'intheon-linedocumentation)FrozenTrailingRowCount('FrozenTrailingRowCountProperty'intheon-linedocumentation)
Frozenrowsorcolumnsarenonscrollableatruntime,butduringdesigntime,theyarestillscrollable.
Trailingfrozenrowsandcolumnsarenotprintedrepeatedlyatthebottomandrightofeverypage,butprintonlyonceasthelastrowandcolumn.Leadingfrozenrowsandcolumnscanberepeated.Formoreinformationaboutrepeatingrowsandcolumns,refertoRepeatingRowsorColumnsonPrintedPages.
Theleadingfrozenroworcolumnisaseparateviewportwhilethetrailingfrozenroworcolumnisalsoaseparateviewport.Indexesforthefrozenviewportsare:
Formoreinformationaboutviewports,refertoCustomizingViewports.
Spread Windows Forms Developer’s Guide 270
Copyright © GrapeCity, Inc. All rights reserved.
Inhierarchicaldisplays,frozenleadingrowsandcolumnsarepossibleinchildsheets.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSheet.2. IntheSheetViewCollectionEditor(Appearancesection),selecttheFrozenRowCount,FrozenColumnCount,FrozenTrailingRowCount,ortheFrozenTrailingColumnCountproperty.
3. Typeavalue.(Thedefaultis0.)Repeatthisforeachproperty.
UsingCode
SettheFrozenRowCount('FrozenRowCountProperty'intheon-linedocumentation),FrozenColumnCount('FrozenColumnCountProperty'intheon-linedocumentation),FrozenTrailingColumnCount('FrozenTrailingColumnCountProperty'intheon-linedocumentation),ortheFrozenTrailingRowCount('FrozenTrailingRowCountProperty'intheon-linedocumentation)propertyforthesheet.
Example
C#fpSpread1.Sheets[0].FrozenColumnCount = 2;fpSpread1.Sheets[0].FrozenRowCount = 2;fpSpread1.Sheets[0].FrozenTrailingColumnCount = 2;fpSpread1.Sheets[0].FrozenTrailingRowCount = 2;
VBFpSpread1.Sheets(0).FrozenColumnCount = 2FpSpread1.Sheets(0).FrozenRowCount = 2FpSpread1.Sheets(0).FrozenTrailingColumnCount = 2FpSpread1.Sheets(0).FrozenTrailingRowCount = 2
UsingtheSpreadDesigner
1. SelectSheetfromthedrop-downcombolistlocatedonthetoprightsideoftheDesigner.2. FromtheSheetViewCollectionEditor,typeanumberforFrozenColumnCount,FrozenRowCount,FrozenTrailingColumnCount,orFrozenTrailingRowCount.
3. FromtheFilemenu,selectSaveandExittosavethechanges.
Setting up Preview Rows
Youcandisplayapreviewrowtoprovidemoreinformationaboutarecord.Thepreviewrowisdisplayedbelowtherowforwhichitprovidesinformation.Youcanspecifycolorsandotherformattingforthepreviewrowaswell.Thefollowingfigureshowspreviewrowswithtext(therowswithoutrowheadernumbers):
Spread Windows Forms Developer’s Guide 271
Copyright © GrapeCity, Inc. All rights reserved.
SetthePreviewRowInfo('PreviewRowInfoClass'intheon-linedocumentation)Visible('VisibleProperty'intheon-linedocumentation)propertytotruetoseethepreviewrow.UsethePreviewRowInfo('PreviewRowInfoClass'intheon-linedocumentation)ColumnIndex('ColumnIndexProperty'intheon-linedocumentation)propertytospecifywhichcolumn’stextyouwanttoseeinthepreviewrow.Ifthecelltextisnull,thenthepreviewrowcontentisnull.YoucanalsousethePreviewRowFetch('PreviewRowFetchEvent'intheon-linedocumentation)eventtospecifythepreviewrowtext.YoucansetvariouspropertiesforthePreviewRowInfo('PreviewRowInfoClass'intheon-linedocumentation)classsuchasBackColor('BackColorProperty'intheon-linedocumentation),Border('BorderProperty'intheon-linedocumentation),Font('FontProperty'intheon-linedocumentation),andsoon.
Thecolumnheaderorfooterdoesnotdisplayapreviewrow.Achildsheetinahierarchydoesnotinheritthepreviewrowsettingsfromtheparentsheet.Ifthesheetwiththepreviewrowhaschildsheets,thepreviewrowisshownbelowtherowswithplussymbols.Ifarowthathasapreviewrowhasspannedrows,thespanisnotdisplayed.Thepreviewrowisread-only(nokeyboardormouseevents,focus,and/orselections).
ThepreviewrowisprintedandexportedtoPDFwhenprintingorprintingtoPDF.Theheightofthepreviewrowcanbeincreasedtoshowallthepreviewrowtext.Iftherearemultiplehorizontalpages,thepreviewrowcontentisdisplayedintheleft-mostpage.
TheAPImembersinvolvedinthisfeatureinclude(seethePreviewRowInfo('PreviewRowInfoClass'intheon-linedocumentation)classforacompletelist):
PreviewRowInfo('PreviewRowInfoClass'intheon-linedocumentation)classColumnIndex('ColumnIndexProperty'intheon-linedocumentation)propertyBackColor('BackColorProperty'intheon-linedocumentation)propertyVisible('VisibleProperty'intheon-linedocumentation)property
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSheet.2. IntheSheetViewCollectionEditor(Miscsection),selectthePreviewRowInfooptionandsetproperties.
UsingCode
SetthePreviewRowInfoclasspropertiesforthesheet.
Example
Thisexamplesetspreviewrowproperties.
C#private void Form1_Load(object sender, EventArgs e){FarPoint.Win.BevelBorder bord = new FarPoint.Win.BevelBorder(FarPoint.Win.BevelBorderType.Raised, Color.Red, Color.Blue);fpSpread1.Sheets[0].Cells[0, 1, 10, 1].Text = "Preview Row";fpSpread1.Sheets[0].PreviewRowInfo.Visible = true;fpSpread1.Sheets[0].PreviewRowInfo.BackColor = Color.BurlyWood;fpSpread1.Sheets[0].PreviewRowInfo.ForeColor = Color.Black;fpSpread1.Sheets[0].PreviewRowInfo.Border = bord;}
private void fpSpread1_PreviewRowFetch(object sender, FarPoint.Win.Spread.PreviewRowFetchEventArgs e){FarPoint.Win.Spread.SheetView sheetView = e.View.GetSheetView();
Spread Windows Forms Developer’s Guide 272
Copyright © GrapeCity, Inc. All rights reserved.
if (sheetView.SheetName == "Sheet1"){if (e.PreviewRowContent == string.Empty)e.PreviewRowContent = "The preview row content is empty";if ((e.Row + 1) % 2 == 0)e.PreviewRowContent = string.Format("Preview Row Content is: {0}", e.PreviewRowContent);}}
VBPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadDim bord As New FarPoint.Win.BevelBorder(FarPoint.Win.BevelBorderType.Raised, Color.DarkBlue, Color.Blue)FpSpread1.Sheets(0).Cells(0, 1, 10, 1).Text = "Preview Row"FpSpread1.Sheets(0).PreviewRowInfo.Visible = TrueFpSpread1.Sheets(0).PreviewRowInfo.BackColor = Color.BurlyWoodFpSpread1.Sheets(0).PreviewRowInfo.ForeColor = Color.BlackFpSpread1.Sheets(0).PreviewRowInfo.Border = bordEnd Sub
Private Sub FpSpread1_PreviewRowFetch(ByVal sender As Object, ByVal e As FarPoint.Win.Spread.PreviewRowFetchEventArgs) HandlesFpSpread1.PreviewRowFetchDim sheetView As FarPoint.Win.Spread.SheetViewsheetView = e.View.GetSheetView()If sheetView.SheetName = "Sheet1" ThenIf (e.PreviewRowContent = String.Empty) Thene.PreviewRowContent = "The preview row content is empty"End IfIf ((e.Row + 1) / 2 = 0) Thene.PreviewRowContent = String.Format("Preview Row Content is: {0}", e.PreviewRowContent)End IfEnd IfEnd Sub
UsingtheSpreadDesigner
1. SelectSheetfromthedrop-downcombolistlocatedonthetoprightsideoftheDesigner.2. FromtheMiscsection,selectthePreviewRowInfooptiontosetproperties.3. FromtheFilemenu,selectSaveandExittosavethechanges.
Managing Filtering of Rows of User Data
Spreadprovidestwotypesoffiltering,simpleandenhanced.ThesimplefilteringisthestyleoffilteringprovidedinthisandpreviousreleasesofSpread.TheenhancedfilteringissimilartoExcel'sfilterfeature.
Eachtypeoffilteringprovidesawayforuserstochangedata'sappearanceortemporarilyhidedatabasedonconditionsthattheyspecify,asshowninthefollowingfigures.Thisfigureillustratesthesimplefilter.
Spread Windows Forms Developer’s Guide 273
Copyright © GrapeCity, Inc. All rights reserved.
Thefollowingfigureillustratestheenhancedfilter.
Ifyouprovideenhancedfiltering,youcanchoosetoofferafilterlisttoassistusersinsettinguptheirfilter,asshownintheprecedingfigure,orafilterbar,asshowninthefollowingfigure.
Spread Windows Forms Developer’s Guide 274
Copyright © GrapeCity, Inc. All rights reserved.
SpecifythewayusersareallowedtofilterdatausingtheinstructionsinAllowingtheUsertoFilterRows.Youcancustomizemanyfeaturesforeachtypeoffiltering,aswellasthedisplayoffilteredrows,asdescribedinthefollowingsections.
CustomizingSimpleFilteringCustomizingEnhancedFiltering
UnderstandingSimpleRowFilteringandUnderstandingEnhancedRowFilteringdescribehowusersinteractwiththefilterfeaturesyoucreate.
Allowing the User to Filter Rows
Bydefault,thespreadsheetdoesnotallowtheusertofiltertherowsofaspreadsheet.Youcanturnonthisfeatureandallowrowfilteringforallorspecificcolumnsinasheet.Hiddenrowsarenotdisplayedeveniftheymatchthefiltercriteria.
UsetheHideRowFilter('HideRowFilterClass'intheon-linedocumentation)classorStyleRowFilter('StyleRowFilterClass'intheon-linedocumentation)classdependingonwhetheryouwanttohiderowsthatarefilteredorchangethestyleofthoserows.UsetheColumn.AllowAutoFilter('AllowAutoFilterProperty'intheon-linedocumentation)propertytoturnonfilteringforagivencolumn.
UsetheAutoFilterMode('AutoFilterModeProperty'intheon-linedocumentation)propertytospecifythetypeoffiltering.Youcanspecifythesimplefilterstyle(FilterGadget),theenhancedfilterstyle(EnhancedContextMenu),ortheenhancedfilterstylewithfilterbar(FilterBar).
Theusercanthenclicktheitemsinthedrop-downtofiltertherows.Tounderstandhowthefilteringworksfortheenduser,refertoUnderstandingSimpleRowFiltering.
Tounderstandtheotheraspectsoffilteringthatcanbecustomized,returntotheoverviewatManagingFilteringofRowsofUserData.
UsingCode
Spread Windows Forms Developer’s Guide 275
Copyright © GrapeCity, Inc. All rights reserved.
Allowrowfiltering(hidingrowsthatarefilteredout)basedonvaluesinonecolumn.Makesurethecolumnheadersarevisible.(RefertoShowingorHidingHeaders.)
Selectthetypeofrowfiltering,usingtheHideRowFilter('HideRowFilterClass'intheon-linedocumentation)class,thenallowthatfilteringforaspecifiedcolumn,usingtheAllowAutoFilter('AllowAutoFilterProperty'intheon-linedocumentation)property.
Example
Thefollowingexamplesetsupsimplefilteringandassumesthatyouhavesomedatainthecells,eitherbyassigningvaluesorbindingtoadatasource.
C#fpSpread1.ActiveSheet.ColumnHeaderVisible = true;FarPoint.Win.Spread.HideRowFilter hideRowFilter = new FarPoint.Win.Spread.HideRowFilter(fpSpread1.ActiveSheet);fpSpread1.ActiveSheet.Columns[1,3].AllowAutoFilter = true;fpSpread1.ActiveSheet.AutoFilterMode = FarPoint.Win.Spread.AutoFilterMode.FilterGadget;
VBFpSpread1.ActiveSheet.ColumnHeaderVisible = TrueDim hideRowFilter As New FarPoint.Win.Spread.HideRowFilter(FpSpread1.ActiveSheet)FpSpread1.ActiveSheet.Columns(1, 3).AllowAutoFilter = TrueFpSpread1.ActiveSheet.AutoFilterMode = FarPoint.Win.Spread.AutoFilterMode.FilterGadget
UsingtheSpreadDesigner
1. Selectacolumnbyclickingonthecolumnheader.2. SetAllowAutoFilterundertheMiscsectionofthePropertywindow.3. UsetheFilemenu,thenApplyandExittosavethechanges.
Customizing Simple Filtering
Youcancustomizemanythingsaboutsimplefiltering,includingthecontents,order,andappearanceofthefilterlist,andtheappearanceoffilterindicators.
Forinstructions,seethefollowingtopics.
UnderstandingSimpleRowFilteringSettingtheAppearanceofFilteredRowsCustomizingtheFilterListCreatingaCustomFilterSettingtheAppearanceofFilterIndicators
Understanding Simple Row Filtering
Thistopicsummarizeshowtheenduserinteractswiththesimplefilterfeature.
Onceyouhaverowfilteringappliedtoacolumn(asdescribedinAllowingtheUsertoFilterRows),anindicatorappearsinthecolumnheader.Thedifferentappearancesoftherowfilteringindicatoraresummarizedinthistable:
RowFilteringIndicator
Description
Spread Windows Forms Developer’s Guide 276
Copyright © GrapeCity, Inc. All rights reserved.
Appearanceofheadercellwithnorowfiltering;thisoccurswhenthereisnorowfiltering,orwhenrowfilteringisoff
Appearanceofheadercellwithrowfilteringallowedbutnorowsfiltered;thisoccurswhenrowfilteringissetto(All)thusnotrestrictingrowsbasedonthecontentsofthiscolumn
Appearanceofheadercellwithrowfilteringallowedandsomerowsfilter;thisoccurswhenrowfilteringsomeoftherowsbasedonthecontentsofthiscolumn
Thecolumnheaderdisplaystherowfilteringindicator,adrop-downarrowsymbol.Clickingonthisindicatorprovidesadrop-downlistofthefilterchoices.Pickinganitemfromthislistcausesthatfiltertobeappliedandalltherowsmeetingthatcondition(inthiscolumn)arefiltered.Thedefaultdrop-downlistcontainsalltheuniquetextvaluesincellsinthiscolumn.Thefigurebelowshowsanexampleofadrop-downlistoffilters.
Thetablebelowsummarizestheentriesinthedrop-downlist.
FilterListItem
Description
(All) Includeorallowalltherowsinthiscolumnregardlessofcontent
[contents] Includeorallowonlythoserowswiththisparticularcellcontentinthiscolumn
(Blanks) Includeorallowonlyrowsthathaveblanks(emptycells)inthiscolumn
(NonBlanks) Includeorallowonlyrowsthathavenon-blanks(non-emptycells)inthiscolumn,inotherwordsanycellthathasanycontent
Youcancustomizethewaythislistisdisplayed,asdescribedinCustomizingtheFilterList.Youcancreatecustomfilterstoaddtothedrop-downlist,asdescribedinCreatingaCustomFilter.
Foragivensheet,multiplecolumnsmayhavefilteringset.Thedifferentcolumnsmayhavedifferentfilters,dependingonthecontentsofcellsinthatcolumn.Theresultsoffilteringwouldbesimilartowhatonewouldexpectwithprimaryandsecondarykeyswhensortingdata.Thechoicefromthefilterlistfromtheinitialcolumnwouldfiltersomerows,leavingthechoicesinthesubsequentfilterlisttobeasubsetofthetotalpossible.Byselectingchoicesfrommorethanonefilter,theresultsincludeonlythoserowsthatsatisfyalltheselectedfilteringconditions.
Formoreinformationonsettinguprowfilters,refertoAllowingtheUsertoFilterRows.Formoreinformationonsettingtheappearanceoffilteredrows,refertoSettingtheAppearanceofFilteredRows.
Tounderstandtheaspectsoffilteringthatcanbecustomized,returntotheoverviewatManagingFilteringofRowsofUserData.
Setting the Appearance of Filtered Rows
Youcancustomizetheappearanceoffilteredrowstoallowyoutoseewhichrowsarefilteredinandwhichonesarefilteredout.Rowsthatmeetthecriteriafortherowfilteraresaidtobe"filteredin";rowsthatdonotmeetthecriteriaaresaidtobe"filteredout."Filteringmayeitherhidetherowsthatarefilteredout,orchangethestylesforbothfiltered-inandfiltered-outrows.Ifyouwantthestylestochange,sothatyoucancontinuetodisplayallthedatabuthighlightrowsthatmatchsomecriteria,thenyoumustdefineafiltered-instyleandafiltered-outstyle.
Spread Windows Forms Developer’s Guide 277
Copyright © GrapeCity, Inc. All rights reserved.
YoudefinestylesbycreatingNamedStyleobjectsthatcontainallthestylesettings.Thenwhentherowfilteringisappliedtoacolumn,youspecifythosedefinedstylesettingsbyreferringtotheNamedStyleobjectforthatfilteredstate.
Inthefigurebelow,fromtheexamplecodegivenhere,thechoiceofGibsoninthefilteritemsresultsintherowswiththatfilteritembeingformattedwithoneappearancestyleandalltheotherrowsbeingformattedwithanotherappearancestyle.
Formoreinformationabouttherowfilterthatusesstyles,refertotheStyleRowFilter('StyleRowFilterClass'intheon-linedocumentation)class.
UsingCode
1. DefinethestylesettingsinaNamedStyleobject.2. ApplytheNamedStyleobjecttothefilter.3. Allowfilteringforaspecifiedcolumnorcolumns.
Example
Thisexamplecreatesafilter.
C#// Define styles to apply to filtered rows.FarPoint.Win.Spread.NamedStyle inStyle = new FarPoint.Win.Spread.NamedStyle();FarPoint.Win.Spread.NamedStyle outStyle = new FarPoint.Win.Spread.NamedStyle();inStyle.BackColor = Color.LightCyan;inStyle.ForeColor = Color.DarkRed;
Spread Windows Forms Developer’s Guide 278
Copyright © GrapeCity, Inc. All rights reserved.
outStyle.BackColor = Color.LemonChiffon;outStyle.ForeColor = Color.Green;
// Create a new filter column definition for the first column (Definition of the default setting).FarPoint.Win.Spread.FilterColumnDefinition fcdef = new FarPoint.Win.Spread.FilterColumnDefinition(0);// Create a StyleRowFilter object (Style filter), and add the above filtering column definition.FarPoint.Win.Spread.StyleRowFilter styleFilter = new FarPoint.Win.Spread.StyleRowFilter(fpSpread1.ActiveSheet, inStyle, outStyle);styleFilter.AddColumn(fcdef);// Set the row filtering object you created to sheets.fpSpread1.ActiveSheet.RowFilter = styleFilter;fpSpread1.ActiveSheet.AutoFilterMode = FarPoint.Win.Spread.AutoFilterMode.FilterGadget;
// Fill the data area with text data.fpSpread1.ActiveSheet.DefaultStyle.CellType = new FarPoint.Win.Spread.CellType.TextCellType();fpSpread1.ActiveSheet.SetText(0, 0, "Fender");fpSpread1.ActiveSheet.SetText(1, 0, "Gibson");fpSpread1.ActiveSheet.SetText(2, 0, "Fender");fpSpread1.ActiveSheet.SetText(3, 0, "Ibanez");fpSpread1.ActiveSheet.SetText(4, 0, "Gibson");fpSpread1.ActiveSheet.SetText(5, 0, "Yamaha");fpSpread1.ActiveSheet.SetText(0, 1, "AST-100 DMC");fpSpread1.ActiveSheet.SetText(1, 1, "Les Paul Standard Double Cut Plus");fpSpread1.ActiveSheet.SetText(2, 1, "ST58-70TX");fpSpread1.ActiveSheet.SetText(3, 1, "AGS83B");fpSpread1.ActiveSheet.SetText(4, 1, "Les Paul Supreme");fpSpread1.ActiveSheet.SetText(5, 1, "ATTITUDE-Limited II");fpSpread1.ActiveSheet.SetColumnWidth(0, 90);fpSpread1.ActiveSheet.SetColumnWidth(1, 210);
VB' Create a named style object for Filter-In rows.Dim inStyle As New FarPoint.Win.Spread.NamedStyleDim outStyle As New FarPoint.Win.Spread.NamedStyleinStyle .BackColor = Color.LightCyaninStyle .ForeColor = Color.DarkRedoutStyle.BackColor = Color.LemonChiffonoutStyle.ForeColor = Color.Green
' Create a new filter column definition for the first column (definition of the default setting).Dim fcdef As New FarPoint.Win.Spread.FilterColumnDefinition(0)' Create a StyleRowFilter object (Style filter), and add the above filtering column definition.Dim styleFilter As New FarPoint.Win.Spread.StyleRowFilter(FpSpread1.ActiveSheet, inStyle, outStyle)styleFilter.AddColumn(fcdef)' Set the row filtering object you created to sheets.FpSpread1.ActiveSheet.RowFilter = styleFilterFpSpread1.ActiveSheet.AutoFilterMode = FarPoint.Win.Spread.AutoFilterMode.FilterGadget
' Fill the data area with text data.
Spread Windows Forms Developer’s Guide 279
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.ActiveSheet.DefaultStyle.CellType = New FarPoint.Win.Spread.CellType.TextCellTypeFpSpread1.ActiveSheet.SetText(0, 0, "Fender")FpSpread1.ActiveSheet.SetText(1, 0, "Gibson")FpSpread1.ActiveSheet.SetText(2, 0, "Fender")FpSpread1.ActiveSheet.SetText(3, 0, "Ibanez")FpSpread1.ActiveSheet.SetText(4, 0, "Gibson")FpSpread1.ActiveSheet.SetText(5, 0, "YAMAHA")FpSpread1.ActiveSheet.SetText(0, 1, "AST-100 DMC")FpSpread1.ActiveSheet.SetText(1, 1, "Les Paul Standard Double Cut Plus")FpSpread1.ActiveSheet.SetText(2, 1, "ST58-70TX")FpSpread1.ActiveSheet.SetText(3, 1, "AGS83B")FpSpread1.ActiveSheet.SetText(4, 1, "Les Paul Supreme")FpSpread1.ActiveSheet.SetText(5, 1, "ATTITUDE-Limited II")FpSpread1.ActiveSheet.SetColumnWidth(0, 90)FpSpread1.ActiveSheet.SetColumnWidth(1, 210)
Customizing the Filter List
Whentheuserclicksontherowfilterindicator,adrop-downlistoffilteritemsisdisplayed.Youcancustomizethatdrop-downlistintheseways:
DefiningtheContentsoftheFilterItemListDefiningtheOrderoftheItemsintheFilterItemListSettingtheAppearanceoftheDisplayoftheFilterItemList
Theusercanthenclicktheitemsinthedrop-downtofiltertherows.Formoreinformationonusingtherowfilters,refertoUnderstandingSimpleRowFiltering.
Defining the Contents of the Filter Item List
Youcanfilterallrowsinasheetbasedoncriteriaofthecontentsofaparticularcellinacolumn.Tosetuprowfilters,followthesebasicsteps:
1. Definefiltercriteria2. Definefilterresultbehavior(changestylesofrowsorhiderows)3. Defineanycustomfilters4. Applyfilter
Definethefiltercriteriaforeachcolumn,whicharecalledthecolumnfilterdefinitions.Thisisthecriteriathatisusedtofilterrowsbasedonthecontentsofthecolumnandisassignedtoanindividualcolumn.Combinetheseindividualcolumncriteriaorcolumnfilterdefinitionsintoacollection.
Definetheappearanceoftherowstobefiltered,eitherbydefiningafiltered-instyleandafiltered-outstyleorbydecidingtohidethefilteredoutrows.Formoreinformationaboutstylesandtheappearanceofrowsoffiltereddata,refertoSettingtheAppearanceofFilteredRows.
Youcancustomizethewordsthatappearinthefollowingchoicesinthedrop-downlist,usingthecorrespondingpropertiesintheDefaultRowFilter('DefaultRowFilterClass'intheon-linedocumentation)class.
All-AllString('AllStringProperty'intheon-linedocumentation)PropertyBlanks-BlanksString('BlanksStringProperty'intheon-linedocumentation)PropertyNonBlanks-NonBlanksString('NonBlanksStringProperty'intheon-linedocumentation)Property
Applytherowfilteringtoallorspecificcolumnsinasheet(whichappliesthecolumnfilterdefinitioncollectiontothe
Spread Windows Forms Developer’s Guide 280
Copyright © GrapeCity, Inc. All rights reserved.
columnsofthatsheet).
UsingCode
1. Definethecolumnfilterdefinitions.2. Groupthemintoacollection.3. Definethestyles.4. Applytherowfilter.
Example
Thefollowingexamplesetsupfilteredrows,includingfilteredrowstyles.
C#// Declare the row filter and column definitions.FarPoint.Win.Spread.FilterColumnDefinitionCollection fcdc = new FarPoint.Win.Spread.FilterColumnDefinitionCollection();FarPoint.Win.Spread.FilterColumnDefinition fcd1 = new FarPoint.Win.Spread.FilterColumnDefinition(2);FarPoint.Win.Spread.FilterColumnDefinition fcd2 = new FarPoint.Win.Spread.FilterColumnDefinition(3);FarPoint.Win.Spread.FilterColumnDefinition fcd3 = new FarPoint.Win.Spread.FilterColumnDefinition(1);// Add column filter definitions to a collection.fcdc.Add(fcd1);fcdc.Add(fcd2);fcdc.Add(fcd3);FarPoint.Win.Spread.NamedStyle inStyle = new FarPoint.Win.Spread.NamedStyle();FarPoint.Win.Spread.NamedStyle outStyle = new FarPoint.Win.Spread.NamedStyle();inStyle.BackColor = Color.Yellow;outStyle.BackColor = Color.Aquamarine;// Apply styles and column filter definitions to the row filter.FarPoint.Win.Spread.StyleRowFilter rowFilter = new FarPoint.Win.Spread.StyleRowFilter(fpSpread1.ActiveSheet,inStyle,outStyle);// Apply the column definition to the filter.rowFilter.ColumnDefinitions = fcdc;// Apply the row filter to the sheet.fpSpread1.ActiveSheet.RowFilter = rowFilter;fpSpread1.ActiveSheet.AutoFilterMode = FarPoint.Win.Spread.AutoFilterMode.FilterGadget;
VB' Declare the row filter and column definitionsDim fcdc As New FarPoint.Win.Spread.FilterColumnDefinitionCollection()Dim fcd1 As New FarPoint.Win.Spread.FilterColumnDefinition(2)Dim fcd2 As New FarPoint.Win.Spread.FilterColumnDefinition(3)Dim fcd3 As New FarPoint.Win.Spread.FilterColumnDefinition(1)' Add column filter definitions to a collection.fcdc.Add(fcd1)fcdc.Add(fcd2)fcdc.Add(fcd3)Dim inStyle As New FarPoint.Win.Spread.NamedStyle()Dim outStyle As New FarPoint.Win.Spread.NamedStyle()inStyle.BackColor = Color.YellowoutStyle.BackColor = Color.Aquamarine
Spread Windows Forms Developer’s Guide 281
Copyright © GrapeCity, Inc. All rights reserved.
' Apply styles and column filter definitions to the row filter.Dim rowFilter As New FarPoint.Win.Spread.StyleRowFilter(FpSpread1.ActiveSheet, inStyle, outStyle)' Apply the column definition to the filter.rowFilter.ColumnDefinitions = fcdc' Apply the row filter to the sheet.FpSpread1.ActiveSheet.RowFilter = rowFilterFpSpread1.ActiveSheet.AutoFilterMode = FarPoint.Win.Spread.AutoFilterMode.FilterGadget
Example
Thisexamplecodecreatesrowfiltersinadrop-downlistthatcanbeaccessedbyclickingonthedrop-downarrowiconinthecolumnheader.Twofiltersarecreated(hideandstyle).Commentoutthestylefiltertoseethehidefilter.
Thisexampledefinesfiltersbasedoncriteriafromthecontentsofcolumns1and2ofthespreadsheetusingthetextoftheitemsinthecolumnsasthefilterchoices.
C#// Set the rows to hide when they are filtered out.FarPoint.Win.Spread.HideRowFilter hideRowFilter = new FarPoint.Win.Spread.HideRowFilter(fpSpread1.ActiveSheet);hideRowFilter.AddColumn(1);hideRowFilter.AddColumn(2);fpSpread1.ActiveSheet.RowFilter = hideRowFilter;
// Set the styles for the filtered-in rows and filtered-out rows.FarPoint.Win.Spread.NamedStyle inStyle = new FarPoint.Win.Spread.NamedStyle();FarPoint.Win.Spread.NamedStyle outStyle = new FarPoint.Win.Spread.NamedStyle();FarPoint.Win.Spread.StyleRowFilter styleRowFilter = new FarPoint.Win.Spread.StyleRowFilter(fpSpread1.ActiveSheet, inStyle, outStyle);inStyle.BackColor = Color.Yellow;outStyle.BackColor = Color.Aquamarine;// Apply the row filter to the two columns.styleRowFilter.AddColumn(1);styleRowFilter.AddColumn(2);fpSpread1.ActiveSheet.RowFilter = styleRowFilter;
// Fill the cells with test data.fpSpread1.ActiveSheet.Cells[0,1].Value = "aaa";fpSpread1.ActiveSheet.Cells[1,1].Value = "aaa";fpSpread1.ActiveSheet.Cells[2,1].Value = "bbb";fpSpread1.ActiveSheet.Cells[3,1].Value = "ccc";fpSpread1.ActiveSheet.Cells[4,1].Value = "ddd";fpSpread1.ActiveSheet.Cells[5,1].Value = "bbb";fpSpread1.ActiveSheet.Cells[6,1].Value = "aaa";fpSpread1.ActiveSheet.Cells[7,1].Value = "eee";fpSpread1.ActiveSheet.Cells[8,1].Value = "jjj";fpSpread1.ActiveSheet.Cells[9,1].Value = "jjj";fpSpread1.ActiveSheet.Cells[10,1].Value = "fff";fpSpread1.ActiveSheet.Cells[11,1].Value = "fff";fpSpread1.ActiveSheet.Cells[12,1].Value = "eee";fpSpread1.ActiveSheet.Cells[13,1].Value = "jjj";fpSpread1.ActiveSheet.Cells[14,1].Value = "eee";fpSpread1.ActiveSheet.Cells[15,1].Value = "jjj";fpSpread1.ActiveSheet.Cells[16,1].Value = "fff";fpSpread1.ActiveSheet.Cells[0,2].Value = "111";
Spread Windows Forms Developer’s Guide 282
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.ActiveSheet.Cells[1,2].Value = "222";fpSpread1.ActiveSheet.Cells[2,2].Value = "333";fpSpread1.ActiveSheet.Cells[3,2].Value = "222";fpSpread1.ActiveSheet.Cells[4,2].Value = "555";fpSpread1.ActiveSheet.Cells[5,2].Value = "444";fpSpread1.ActiveSheet.Cells[6,2].Value = "444";fpSpread1.ActiveSheet.Cells[0,3].Value = "North";fpSpread1.ActiveSheet.Cells[1,3].Value = "South";fpSpread1.ActiveSheet.Cells[2,3].Value = "East";fpSpread1.ActiveSheet.Cells[3,3].Value = "South";fpSpread1.ActiveSheet.Cells[4,3].Value = "North";fpSpread1.ActiveSheet.Cells[5,3].Value = "North";fpSpread1.ActiveSheet.Cells[6,3].Value = "West";
VB' Set the rows to hide when they are filtered out.Dim hRowFilter As New FarPoint.Win.Spread.HideRowFilter(FpSpread1.ActiveSheet)hRowFilter.AddColumn(1)hRowFilter.AddColumn(2)FpSpread1.ActiveSheet.RowFilter = hRowFilter
' Set the styles for the filtered-in rows and filtered-out rows.Dim inStyle As New FarPoint.Win.Spread.NamedStyle()Dim outStyle As New FarPoint.Win.Spread.NamedStyle()Dim styleRowFilter As New FarPoint.Win.Spread.StyleRowFilter(FpSpread1.ActiveSheet, inStyle, outStyle)inStyle.BackColor = Color.YellowoutStyle.BackColor = Color.Aquamarine' Apply the row filter to the two columns.styleRowFilter.AddColumn(1)styleRowFilter.AddColumn(2)FpSpread1.ActiveSheet.RowFilter = styleRowFilter
' Fill the cells with test data.FpSpread1.ActiveSheet.Cells(0, 1).Value = "aaa"FpSpread1.ActiveSheet.Cells(1, 1).Value = "aaa"FpSpread1.ActiveSheet.Cells(2, 1).Value = "bbb"FpSpread1.ActiveSheet.Cells(3, 1).Value = "ccc"FpSpread1.ActiveSheet.Cells(4, 1).Value = "ddd"FpSpread1.ActiveSheet.Cells(5, 1).Value = "bbb"FpSpread1.ActiveSheet.Cells(6, 1).Value = "aaa"FpSpread1.ActiveSheet.Cells(7, 1).Value = "eee"FpSpread1.ActiveSheet.Cells(8, 1).Value = "jjj"FpSpread1.ActiveSheet.Cells(9, 1).Value = "jjj"FpSpread1.ActiveSheet.Cells(10, 1).Value = "fff"FpSpread1.ActiveSheet.Cells(11, 1).Value = "fff"FpSpread1.ActiveSheet.Cells(12, 1).Value = "eee"FpSpread1.ActiveSheet.Cells(13, 1).Value = "jjj"FpSpread1.ActiveSheet.Cells(14, 1).Value = "eee"FpSpread1.ActiveSheet.Cells(15, 1).Value = "jjj"FpSpread1.ActiveSheet.Cells(16, 1).Value = "fff"FpSpread1.ActiveSheet.Cells(0, 2).Value = "111"FpSpread1.ActiveSheet.Cells(1, 2).Value = "222"FpSpread1.ActiveSheet.Cells(2, 2).Value = "333"FpSpread1.ActiveSheet.Cells(3, 2).Value = "222"FpSpread1.ActiveSheet.Cells(4, 2).Value = "555"
Spread Windows Forms Developer’s Guide 283
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.ActiveSheet.Cells(5, 2).Value = "444"FpSpread1.ActiveSheet.Cells(6, 2).Value = "444"FpSpread1.ActiveSheet.Cells(0, 3).Value = "North"FpSpread1.ActiveSheet.Cells(1, 3).Value = "South"FpSpread1.ActiveSheet.Cells(2, 3).Value = "East"FpSpread1.ActiveSheet.Cells(3, 3).Value = "South"FpSpread1.ActiveSheet.Cells(4, 3).Value = "North"FpSpread1.ActiveSheet.Cells(5, 3).Value = "North"FpSpread1.ActiveSheet.Cells(6, 3).Value = "West"
Defining the Order of the Items in the Filter Item List
Youcancustomizehowthedrop-downlistoffilteritemsisdisplayed.Bydefault,thelistshowsthepossiblefilteritemsalphabeticallyandincludesalltheoptions.BychangingthevalueoftheFilterListBehavior('FilterListBehaviorEnumeration'intheon-linedocumentation)enumeration,youchangehowthefilterlistisdisplayed.Forexampleyoucansetthefilterlisttodisplayitemsinorderofnumberofoccurrencesinthatcolumn.
UsetheAddColumn('AddColumnMethod'intheon-linedocumentation)methodsandspecifythecolumnfilterdefinition.Thisalsodefinesthewaythefilteritemsappearinthedrop-down.
UsingCode
SettheFilterListBehavior('FilterListBehaviorEnumeration'intheon-linedocumentation)enumerationtochangehowthefilterlistisdisplayed.
Example
ThefollowingexampleillustratessettingtheFilterListBehavior('FilterListBehaviorEnumeration'intheon-linedocumentation)enumerationincode.
C#FarPoint.Win.Spread.NamedStyle instyle = new FarPoint.Win.Spread.NamedStyle();FarPoint.Win.Spread.NamedStyleim outstyle = new FarPoint.Win.Spread.NamedStyle();instyle.BackColor = Color.Yellow;outstyle.BackColor = Color.Aquamarine;FarPoint.Win.Spread.FilterColumnDefinition fcd = new FarPoint.Win.Spread.FilterColumnDefinition(1, FarPoint.Win.Spread.FilterListBehavior.SortByMostOccurrences | FarPoint.Win.Spread.FilterListBehavior.Default);FarPoint.Win.Spread.FilterColumnDefinition fcd1 = new FarPoint.Win.Spread.FilterColumnDefinition(2);FarPoint.Win.Spread.FilterColumnDefinition fcd2 = new FarPoint.Win.Spread.FilterColumnDefinition();FarPoint.Win.Spread.StyleRowFilter sf = new FarPoint.Win.Spread.StyleRowFilter(fpSpread1.ActiveSheet, instyle, outstyle);sf.AddColumn(fcd);sf.AddColumn(fcd1);sf.AddColumn(fcd2);fpSpread1.ActiveSheet.RowFilter = sf;fpSpread1.ActiveSheet.AutoFilterMode = FarPoint.Win.Spread.AutoFilterMode.FilterGadget;
VBDim instyle As New FarPoint.Win.Spread.NamedStyleDim outstyle As New FarPoint.Win.Spread.NamedStyle
Spread Windows Forms Developer’s Guide 284
Copyright © GrapeCity, Inc. All rights reserved.
instyle.BackColor = Color.Yellowoutstyle.BackColor = Color.AquamarineDim fcd As New FarPoint.Win.Spread.FilterColumnDefinition(1, FarPoint.Win.Spread.FilterListBehavior.SortByMostOccurrences Or FarPoint.Win.Spread.FilterListBehavior.Default)Dim fcd1 As New FarPoint.Win.Spread.FilterColumnDefinition(2)Dim fcd2 As New FarPoint.Win.Spread.FilterColumnDefinitionDim sf As New FarPoint.Win.Spread.StyleRowFilter(fpSpread1.ActiveSheet, instyle, outstyle)sf.AddColumn(fcd)sf.AddColumn(fcd1)sf.AddColumn(fcd2)fpSpread1.ActiveSheet.RowFilter = sfFpSpread1.ActiveSheet.AutoFilterMode = FarPoint.Win.Spread.AutoFilterMode.FilterGadget
Setting the Appearance of the Display of the Filter Item List
Youcansettheappearanceoftheoutlineofthedrop-downlist.Thefollowingfiguresshowthetypesofoutlines(orborder)styles.
Outline(Border)Style ExampleFixed,three-dimensional(default)
Fixed,single-line
None
Formoredetails,refertotheDefaultRowFilterclassDropDownBorderStyle('DropDownBorderStyleProperty'intheon-linedocumentation)propertyandthe.NETBorderStyleenumeration.
Spread Windows Forms Developer’s Guide 285
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
1. SettheAllowAutoFilter('AllowAutoFilterProperty'intheon-linedocumentation)property.2. SettheDropDownBorderStyle('DropDownBorderStyleProperty'intheon-linedocumentation)
property.
Example
Thisexamplecreatesafilterandsetstheborderstyle.
C#// Activate the automatic filtering features.fpSpread1.ActiveSheet.Columns[0].AllowAutoFilter = true;fpSpread1.ActiveSheet.AutoFilterMode = FarPoint.Win.Spread.AutoFilterMode.FilterGadget;// Change the drop-down list style to "Single Line".fpSpread1.ActiveSheet.RowFilter.DropDownBorderStyle = BorderStyle.FixedSingle;
fpSpread1.ActiveSheet.DefaultStyle.CellType = new FarPoint.Win.Spread.CellType.TextCellType();fpSpread1.ActiveSheet.SetText(0, 0, "Fender");fpSpread1.ActiveSheet.SetText(1, 0, "Gibson");fpSpread1.ActiveSheet.SetText(2, 0, "Fender");fpSpread1.ActiveSheet.SetText(3, 0, "Ibanez");fpSpread1.ActiveSheet.SetText(4, 0, "Gibson");fpSpread1.ActiveSheet.SetText(5, 0, "YAMAHA");fpSpread1.ActiveSheet.SetText(0, 1, "AST-100 DMC");fpSpread1.ActiveSheet.SetText(1, 1, "Les Paul Standard Double Cut Plus");fpSpread1.ActiveSheet.SetText(2, 1, "ST58-70TX");fpSpread1.ActiveSheet.SetText(3, 1, "AGS83B");fpSpread1.ActiveSheet.SetText(4, 1, "Les Paul Supreme");fpSpread1.ActiveSheet.SetText(5, 1, "ATTITUDE-Limited II");fpSpread1.ActiveSheet.SetColumnWidth(0, 90);fpSpread1.ActiveSheet.SetColumnWidth(1, 210);
VB' Activate the automatic filtering features.FpSpread1.ActiveSheet.Columns(0).AllowAutoFilter = True' Change the drop-down list style to "Single Line".FpSpread1.ActiveSheet.AutoFilterMode = FarPoint.Win.Spread.AutoFilterMode.FilterGadgetFpSpread1.ActiveSheet.RowFilter.DropDownBorderStyle = BorderStyle.FixedSingle
FpSpread1.ActiveSheet.DefaultStyle.CellType = New FarPoint.Win.Spread.CellType.TextCellTypeFpSpread1.ActiveSheet.SetText(0, 0, "Fender")FpSpread1.ActiveSheet.SetText(1, 0, "Gibson")FpSpread1.ActiveSheet.SetText(2, 0, "Fender")FpSpread1.ActiveSheet.SetText(3, 0, "Ibanez")FpSpread1.ActiveSheet.SetText(4, 0, "Gibson")FpSpread1.ActiveSheet.SetText(5, 0, "YAMAHA")FpSpread1.ActiveSheet.SetText(0, 1, "AST-100 DMC")FpSpread1.ActiveSheet.SetText(1, 1, "Les Paul Standard Double Cut Plus")FpSpread1.ActiveSheet.SetText(2, 1, "ST58-70TX")FpSpread1.ActiveSheet.SetText(3, 1, "AGS83B")FpSpread1.ActiveSheet.SetText(4, 1, "Les Paul Supreme")
Spread Windows Forms Developer’s Guide 286
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.ActiveSheet.SetText(5, 1, "ATTITUDE-Limited II")FpSpread1.ActiveSheet.SetColumnWidth(0, 90)FpSpread1.ActiveSheet.SetColumnWidth(1, 210)
Creating a Custom Filter
Youcancreateacustomfilterthatyoucanthenincludeinthecolumnfilterdefinitioncollection.Inordertocreateacustomfilter,followthesesteps:
1. CreateaclassthatinheritsfromFarPoint.Win.Spread.BaseFilterItem('BaseFilterItemClass'intheon-linedocumentation)orFarPoint.Win.Spread.DefaultFilterItem('DefaultFilterItemClass'intheon-linedocumentation).
2. OverridetheDisplayName('DisplayNameProperty'intheon-linedocumentation)propertytoreturnthenametobedisplayedinthedrop-downlistoffilteritems.
3. OverridetheShowInDropDown('ShowInDropDownMethod'intheon-linedocumentation)methodtospecifyifthisfilteritemshouldbedisplayedinthedrop-downlistgiventhecurrentfilteredinrows.
4. OverridetheFilter('FilterMethod'intheon-linedocumentation)methodtoperformthefilteractiononthespecifiedcolumn.
5. OverridetheSerialize('SerializeMethod'intheon-linedocumentation)andDeserialize('DeserializeMethod'intheon-linedocumentation)methods.Makecallstothebase.Serializeandbase.Deserializemethodsunlessyourmethodshandlepersistingthedefaultproperties.
6. CreateaHideRowFilter('HideRowFilterClass'intheon-linedocumentation)orStyleRowFilter('StyleRowFilterClass'intheon-linedocumentation)object.
7. Addthecustomfiltertothecustomfilter’slistofthecolumnfilterdefinitionintherowfilteringobjectfromthepreviousstep.
Formoredetails,refertothesemembers:
BaseFilterItem('BaseFilterItemClass'intheon-linedocumentation)IFilterItem('IFilterItemInterface'intheon-linedocumentation)DefaultFilterItem('DefaultFilterItemClass'intheon-linedocumentation)FilterItemCollection('FilterItemCollectionClass'intheon-linedocumentation)
Setting the Appearance of Filter Indicators
Thefilterindicatorsaredisplayedinthecolumnheaderwhenrowfilteringisavailabletotheuser.Youcancustomizevariousaspectsofthefilterindicators.Youcandoanyofthefollowing:
UsingCustomFilterIndicatorImagesShowingorHidingFilterIndicatorsDeterminingWhichHeaderRowDisplaystheIndicators
Using Custom Filter Indicator Images
Youcancustomizethefilterindicatorimagethatappearsinthecolumnheaderofcolumnsthathavefiltersassigned.Oneofthedefaultimagesisshownhereinthesecond(B)column.
OnewayistooverridethePaintFilterIndicator('PaintFilterIndicatorMethod'intheon-linedocumentation)methodintheCellTypeColumnHeaderRenderer('ColumnHeaderRendererClass'intheon-linedocumentation)classandcreateyourowncustomfilterindicator.
AnotherwayistousetheGetImage('GetImageMethod'intheon-linedocumentation)andSetImage
Spread Windows Forms Developer’s Guide 287
Copyright © GrapeCity, Inc. All rights reserved.
('SetImageMethod'intheon-linedocumentation)methodsintheSpreadViewclass,whichisdescribedinCustomizingtheUserInterfaceImages.
UsingCode
1. CreateanewcolumnheaderrendererwiththeColumnHeaderRenderer('ColumnHeaderRendererClass'intheon-linedocumentation)class.
2. OverridethePaintSortIndicator('PaintSortIndicatorMethod'intheon-linedocumentation)method.
3. OverridethePaintFilterIndicator('PaintFilterIndicatorMethod'intheon-linedocumentation)method.
Example
Thisexampleillustrateshowtosetcreateacustomfilterincode,byfirstcreatinganewcolumnheaderrenderer,andthencustomizingthefilterindicatorthatappearsinthecolumnheader.
C#// In the form load section, allow filtering (and sorting).private void Form1_Load(object sender, System.EventArgs e){ fpSpread1.ActiveSheet.ColumnHeader.DefaultStyle.Renderer = new myColumnHeaderRenderer(); fpSpread1.Sheets[0].Columns[0].AllowAutoSort =true; fpSpread1.Sheets[0].Columns[0].AllowAutoFilter =true;}// Define a new column header renderer.public class myColumnHeaderRenderer : FarPoint.Win.Spread.CellType.ColumnHeaderRenderer{ // Override the sorting indicator paint method. override public void PaintSortIndicator(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearance appearance, float zoomFactor) { g.FillRectangle(new SolidBrush(Color.Red), r); } // Override the filtering indicator paint method. override public void PaintFilterIndicator(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearance appearance, float zoomFactor) { g.FillRectangle(new SolidBrush(Color.Blue), r); }} //End Form1_Load
VB' Define a new column header renderer.Public Class myColumnHeaderRendererInherits FarPoint.Win.Spread.CellType.ColumnHeaderRenderer ' Override the sorting indicator paint method. Public Overrides Sub PaintSortIndicator(ByVal g As Graphics, ByVal r As Rectangle, ByVal appearance As FarPoint.Win.Spread.Appearance, ByVal zoomFactor As Single) g.FillRectangle(New SolidBrush(Color.Red), r) End Sub 'PaintSortIndicator ' Override the filtering indicator paint method. Public Overrides Sub PaintFilterIndicator(ByVal g As Graphics, ByVal r As Rectangle, ByVal appearance As FarPoint.Win.Spread.Appearance, ByVal zoomFactor As Single)
Spread Windows Forms Developer’s Guide 288
Copyright © GrapeCity, Inc. All rights reserved.
g.FillRectangle(New SolidBrush(Color.Blue), r) End Sub 'PaintFilterIndicatorEnd Class 'myColumnHeaderRenderer' In the form load section, allow sorting and filtering.Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load FpSpread1.ActiveSheet.ColumnHeader.DefaultStyle.Renderer = New myColumnHeaderRenderer FpSpread1.Sheets(0).Columns(0).AllowAutoSort = True FpSpread1.Sheets(0).Columns(0).AllowAutoFilter = TrueEnd Sub 'Form1_Load
Showing or Hiding Filter Indicators
Youcandisplayfortheuserorhidefromtheuserthefilterindicatorsthatappearinthecolumnheaders.
UsingCode
1. SettheAllowAutoFilter('AllowAutoFilterProperty'intheon-linedocumentation)property.2. SettheShowFilterIndicator('ShowFilterIndicatorProperty'intheon-linedocumentation)
property.
Example
Thisexampledisplaysthefilterindicatorandsetsthefilterstrings.
C#fpSpread1.ActiveSheet.Columns[1].AllowAutoFilter = true;fpSpread1.ActiveSheet.RowFilter.ShowFilterIndicator = true;fpSpread1.ActiveSheet.RowFilter.AllString = "Show All";fpSpread1.ActiveSheet.RowFilter.BlanksString = "Show The Blanks";fpSpread1.ActiveSheet.RowFilter.NonBlanksString = "Show The Non-Blanks";
VBFpSpread1.ActiveSheet.Columns(1).AllowAutoFilter = TrueFpSpread1.ActiveSheet.RowFilter.ShowFilterIndicator = TrueFpSpread1.ActiveSheet.RowFilter.AllString = "Show All"FpSpread1.ActiveSheet.RowFilter.BlanksString = "Show The Blanks"FpSpread1.ActiveSheet.RowFilter.NonBlanksString = "Show The Non-Blanks"
Determining Which Header Row Displays the Indicators
Ifyouhavemultiplecolumnheaderrowsthenyoucanspecifywhichrowdisplaysthefilterindicators.Bydefaulttheyappearinthebottomcolumnheaderrow.YoucanspecifywhichrowdisplaystheindicatorbysettingtheAutoFilterIndex('AutoFilterIndexProperty'intheon-linedocumentation)propertyoftheColumnHeader('ColumnHeaderClass'intheon-linedocumentation)class.
UsingCode
SettheColumnHeaderclassAutoFilterIndex('AutoFilterIndexProperty'intheon-linedocumentation)propertytotherowindextodisplaytheindicator.Therowindexiszerobased,sothefirstrowis0.
Spread Windows Forms Developer’s Guide 289
Copyright © GrapeCity, Inc. All rights reserved.
Example
Thefollowingexamplesetstheindicatortoappearinthenexttothebottomcolumnheaderrow.
C#fpSpread1.ActiveSheet.Columns[1].AllowAutoFilter = true;fpSpread1.ActiveSheet.ColumnHeaderRowCount = 3;fpSpread1.ActiveSheet.ColumnHeader.AutoFilterIndex = 1;
VBFpSpread1.ActiveSheet.Columns(1).AllowAutoFilter = TrueFpSpread1.ActiveSheet.ColumnHeaderRowCount = 3FpSpread1.ActiveSheet.ColumnHeader.AutoFilterIndex = 1
Customizing Enhanced Filtering
Youcancustomizeenhancedfilteringbyspecifyingtousethedefaultfiltermenuortodisplayafilterbar,asdescribedinAllowingtheUsertoFilterRows.Ifyoudecidetohavethecontroldisplayafilterbar,youcancustomizethefilterbar.Youcanalsouseanenhancedsortdialogwithenhancedfiltering.
UnderstandingEnhancedRowFilteringCustomizingtheFilterBarAddingaCustomSortDialog(on-linedocumentation)
Understanding Enhanced Row Filtering
Whenthecontrolhasenhancedfilteringturnedon,theusercandrop-downalistofavailablefilterstoapplytothedata,asshowninthefollowingfigure.
Spread Windows Forms Developer’s Guide 290
Copyright © GrapeCity, Inc. All rights reserved.
Thedefaultfilterthatisdisplayeddependsonthedatainthecolumn.Thefiltercanbeanumber,text,date,orcolorfilter.
Thefiltersaredescribedinthefollowingtable.
FilterType DescriptionNumberFilters
Equals Valuesinrowsareequaltocondition
DoesNotEqual Valuesinrowsdonotequalcondition
GreaterThan Valuesinrowsaregreaterthancondition
GreaterThanOrEqualTo Valuesinrowsaregreaterthanorequaltocondition
LessThan Valuesinrowsarelessthancondition
LessThanOrEqualTo Valuesinrowsarelessthanorequaltocondition
Between Valuesinrowsaregreaterthanoneconditionandlessthananothercondition
Top10 Valuesintherowswiththetenhighestvalues
AboveAverage Valuesintherowsthatareabovetheaverageofthevaluesinalltherows
BelowAverage Valuesintherowsthatarebelowtheaverageofthevaluesinalltherows
CustomFilter Valuesinrowsthatmeettheconditionsofacustomfilter
TextFilters
Equals Valuesinrowsequalthecondition
DoesNotEqual Valuesinrowsdonotequalthecondition
BeginsWith Valuesinrowsbeginwiththespecifiedcharacters
Spread Windows Forms Developer’s Guide 291
Copyright © GrapeCity, Inc. All rights reserved.
EndsWith Valuesinrowsendwiththespecifiedcharacters
Contains Valuesinrowscontainthespecifiedcharacters
DoesNotContain Valuesinrowsdonotcontainthespecifiedcharacters
CustomFilter Valuesinrowsthatmeettheconditionsofacustomfilter
DateFilters
Equals Valuesinrowsequalthecondition
Before Valuesinrowsaredatesbeforethecondition
After Valuesinrowsaredatesafterthecondition
Between Valuesinrowsaredatesbetweentwospecifieddatesforthecondition
Tomorrow Valuesinrowsaretomorrow'sdate
Today Valuesinrowsaretoday'sdate
Yesterday Valuesinrowsareyesterday'sdate
NextWeek Valuesinrowsareduringnextweek
ThisWeek Valuesinrowsareduringcurrentweek
LastWeek Valuesinrowsareduringlastweek
NextMonth Valuesinrowsareduringnextmonth
ThisMonth Valuesinrowsareduringcurrentmonth
LastMonth Valuesinrowsareduringlastmonth
NextQuarter Valuesinrowsareduringnextquarter
ThisQuarter Valuesinrowsareduringcurrentquarter
LastQuarter Valuesinrowsareduringlastquarter
NextYear Valuesinrowsareduringnextyear
ThisYear Valuesinrowsareduringcurrentyear
LastYear Valuesinrowsareduringlastyear
YeartoDate Valuesinrowsareduringcurrentyeartopresentdate
AllDatesinthePeriod Valuesinrowsarewithinaspecifiedperiod
CustomFilter Valuesinrowsthatmeettheconditionsofacustomfilter
Userscanspecifywildcardsinconditions.The"?"characterrepresentsanysinglecharacter.The"*"characterrepresentsanyseriesofcharacters.
Whentheuserchoosesafilter,thecontroleitherfiltersthedatatodisplayonlytheitemsthatmatchthefiltercriteria,orthecontroldisplaystherowsthatmeetthecriteriawithoneappearance,andtherowsthatdonotmeetthecriteriawithanotherappearance.Forinformationaboutsettingthestylesforrows,seeSettingtheAppearanceofFilteredRows.
Inthecontrol,columnswithfiltersdisplayfilterindicators,whichindicatewhetherafilterhasbeenapplied,asshowninthefollowingtable.
RowFilteringIndicator DescriptionAppearanceofheadercellwithnorowfiltering
Spread Windows Forms Developer’s Guide 292
Copyright © GrapeCity, Inc. All rights reserved.
Appearanceofheadercellwithrowfilteringallowedbutnorowsfiltered
Appearanceofheadercellwithrowfilteringallowedandsomerowsfiltered
Ifyouprefer,youcanhavethecontroldisplayafilterbarthatallowstheusertochoosethefiltertoapply.Thefilterbarisdisplayedinthecontrolatalltimes,andchoosingafilterfromthefilterbarmakesthefiltergointoeffectimmediately.Thefollowingfigureillustratesacontrolwithafilterbar.
UsingCode
1. SettheAllowAutoFilter('AllowAutoFilterProperty'intheon-linedocumentation)property.2. SettheAutoFilterMode('AutoFilterModeProperty'intheon-linedocumentation)property.
Example
Thefollowingexamplecreatesanenhancedfilterinthefirstthreecolumns.Adddifferenttypesofdatatoseethevariousfilteroptions.
C#fpSpread1.Sheets[0].Columns[0, 2].AllowAutoFilter = true;fpSpread1.Sheets[0].AutoFilterMode =FarPoint.Win.Spread.AutoFilterMode.EnhancedContextMenu;
VBFpSpread1.Sheets(0).Columns(0, 2).AllowAutoFilter = TrueFpSpread1.Sheets(0).AutoFilterMode =FarPoint.Win.Spread.AutoFilterMode.EnhancedContextMenu
Youcancustomizetheappearanceofthefilterbar,asdescribedinCustomizingtheFilterBar.
Spread Windows Forms Developer’s Guide 293
Copyright © GrapeCity, Inc. All rights reserved.
Customizing the Filter Bar
Youcancustomizetheappearanceofthefilterbar.Youcanchangethebackgroundandtextcolorsandthegridlinesandtheircolor.Thefollowingfigureillustratesafilterbarwithacustomappearance.
Thefilterbaralsoprovidesadatepickertopickadatetofilterby.Certainfiltermenuchoiceswilldisplaythedatepicker(beforeorafter,forexample).Youcanalsotypethevalueintheeditportionofthefilterafteryouselectafiltermenuoption.
SettingtheAutoFormat('AutoFormatProperty'intheon-linedocumentation)propertytotruespecifiestousetheDateTimeFormatInfo('DateTimeFormatInfoProperty'intheon-linedocumentation),FormatString('FormatStringProperty'intheon-linedocumentation),andNumberFormatInfo('NumberFormatInfoProperty'intheon-linedocumentation)propertiestoformatthevalueinthefilterbar.Setthesepropertiesiftheformatofthedatainthecellisdifferentfromtheformatinthefilterbar.TheEqualsfiltermenuoptionrequiresthatthecellformatandthefilterbarformatbethesame.
UsingCode
1. Tocustomizespecificcellsinthefilterbar,settheFilterBar('FilterBarClass'intheon-linedocumentation)class'sCells('CellsProperty'intheon-linedocumentation)properties.
2. Tocustomizethefilterbaroverall,settheFilterBar'sDefaultStyle('DefaultStyleProperty'intheon-linedocumentation),Height('HeightProperty'intheon-linedocumentation),HorizontalGridLine('HorizontalGridLineProperty'intheon-linedocumentation),andVerticalGridLine('VerticalGridLineProperty'intheon-linedocumentation)properties.
Example
Spread Windows Forms Developer’s Guide 294
Copyright © GrapeCity, Inc. All rights reserved.
Thefollowingexamplesetsonecellinthefilterbartodisplayacustomborderandbackgroundcolor,andtheentirefilterbartodisplayacustomborder.
C#FarPoint.Win.Spread.SheetView sheetView = fpSpread1.ActiveSheet;sheetView.AutoFilterMode = FarPoint.Win.Spread.AutoFilterMode.FilterBar;sheetView.FilterBar.Cells[0].Border = new FarPoint.Win.DoubleLineBorder(Color.Red);sheetView.FilterBar.Cells[0].BackColor = Color.GreenYellow;sheetView.FilterBar.DefaultStyle.Border = new FarPoint.Win.DoubleLineBorder(Color.Yellow);
VBDim sheetView As FarPoint.Win.Spread.SheetView = FpSpread1.ActiveSheetsheetView.AutoFilterMode = FarPoint.Win.Spread.AutoFilterMode.FilterBarsheetView.FilterBar.Cells(0).Border = New FarPoint.Win.DoubleLineBorder(Color.Red)sheetView.FilterBar.Cells(0).BackColor = Color.GreenYellowsheetView.FilterBar.DefaultStyle.Border = New FarPoint.Win.DoubleLineBorder(Color.Yellow)
Managing Grouping of Rows of User Data
Youcansetthedisplayofthespreadsheetcomponenttoallowrowstobegroupedaccordingtothecolumnheaders.Youcancustomizetheuserexperienceforgroupingdataonasheet.Withgrouping,youcanallowtheusertogrouprowsofdataaccordingtothecolumnheadersthataredraggedintothegroupbar.Specialgroupheadingsaredisplayedabovethegroupedrows.Groupingofrowsincludesthefollowingtasks.
AllowingtheUsertoGroupRowsUsingGroupingSettingtheAppearanceofGroupedRowsCustomizingtheGroupBarCreatingaCustomGroupInteroperabilityofGroupingwithOtherFeatures
Allowing the User to Group Rows
Bydefault,thespreadsheetdoesnotallowtheusertogrouptherowsofaspreadsheet.Youcanturnonthisfeatureandallowgroupingofrowsforanentiresheet.Besidesallowinggrouping,youalsoneedtoallowcolumnstomove,sincetheuserperformsgroupingbyclickinganddraggingacolumnheaderintothegroupbar,whichissimilartotheactofmovingacolumn.Also,thegroupbarmustbevisibleandthecolumnheaders(atleastonerow)shouldbevisible.
Thefollowingimagedisplaysthecomponentwithgroupingallowed.
UsetheAllowGroup('AllowGroupProperty'intheon-linedocumentation)propertyofthesheettoturnon
Spread Windows Forms Developer’s Guide 295
Copyright © GrapeCity, Inc. All rights reserved.
grouping.UsetheVisible('VisibleProperty'intheon-linedocumentation)propertyoftheGroupBarInfo('GroupBarInfoClass'intheon-linedocumentation)classtodisplaythegroupbar(theareaatthetopofthesheetintowhichtheusercandragcolumnheaders.RemembertosettheAllowColumnMove('AllowColumnMoveProperty'intheon-linedocumentation)propertyoftheSpreadtoTruetoallowtheusertoclickanddragcolumnheaders.Unlessyouareusingthedefaultvalue,settheColumnHeaderVisible('ColumnHeaderVisibleProperty'intheon-linedocumentation)propertyofthesheettoTruetoensurethatthecolumnheadersaredisplayed.
Youcanturnonorofftherowheaders;thesehavenoeffectonthedisplayofgrouping.
TheAllowDragDrop('AllowDragDropProperty'intheon-linedocumentation)propertyisnotsupportedwithgrouping.
Youcansetthemaximumnumberoflevelsofgroupingthattheendusercanset.Thislimitsthenumberofcolumnheadersthatcanbedraggedconsecutivelytothegroupbar.
Tounderstandhowgroupingworksfortheenduser,refertoUsingGrouping.
UsingCode
1. SettheAllowColumnMove('AllowColumnMoveProperty'intheon-linedocumentation)propertytoTrue.
2. SettheVisible('VisibleProperty'intheon-linedocumentation)propertytoTrue.3. SettheAllowGroup('AllowGroupProperty'intheon-linedocumentation)propertytoTruetoallow
theusertogroupthedata.
Example
Thisexampleallowsgrouping.
C#FpSpread1.AllowColumnMove = true;FpSpread1.ActiveSheet.GroupBarInfo.Visible = true;FpSpread1.ActiveSheet.AllowGroup = true;
VBFpSpread1.AllowColumnMove = TrueFpSpread1.ActiveSheet.GroupBarInfo.Visible = TrueFpSpread1.ActiveSheet.AllowGroup = True
Using Grouping
YoucansetupthedisplaytoallowOutlook-stylegroupingofrows.Forlargeamountsofdata,thisishelpfultodisplaythedataintheordertheuserneeds.Theuserselectscolumnsbywhichtosortandthecomponentthenorganizesanddisplaysthedatainahierarchywithrowsorganizedaccordingly.Toselectacolumnbywhichtogroupanddisplaythatdata,eitherdouble-clickontheheaderofthatcolumnorclickanddragthatcolumnintothegroupingbaratthetopofthepage.Seethefigurebelowforanexampleofthetermsusedwithgrouping.
Spread Windows Forms Developer’s Guide 296
Copyright © GrapeCity, Inc. All rights reserved.
Youcanexpandorcollapsegroupsbyclickingtheexpand(+)orcollapse(-)indicators.
Youcanprovidegroupingtoallowuserstosortthedatawithmultiplelevelsofgroupsbydraggingadditionalcolumnheadersintothegroupingarea.Anexampleoftheprocessofsettinguptwolevelsofgroupingisshowninthefollowingfigure.
Beforesecondarygrouping:draggingthecolumnheaderintothegroupingbar. Aftersecondarygrouping:nowasecondlevelofhierarchyisshown.
Whenmorethanonelevelischosen,thehigherleveliscalledtheparentgroupandthelowerleveliscalledthechildgroup.Intheproceedingfigurewithsecondarygrouping,theEmployeeIDistheparentgroupandtheFirstNameisthechildgroup.
Setting the Appearance of Grouped Rows
Youcancustomizetheappearanceofthegroupheadersandthegroupedrows.Foranintroductiontotheuserinterfaceforgrouping,refertoUsingGrouping.
Youcansetupthedisplaysothattheitemsareshowninitiallyallexpandedorallcollapsedwhengroupingisperformed.TheGroupingPolicy('GroupingPolicyProperty'intheon-linedocumentation)propertyonlyappliestonewgroups.
Youcansetthecolorsandotherformattingofboththehierarchynamesandthedataintherowswhengroupingisperformed.
Youcanhideordisplaythegroupingbaratthetopofthesheet.
Thefollowingtabledescribesthemembersusedforcustomizingtheappearanceofgroupedrows:
GroupingAPIMember Description
Spread Windows Forms Developer’s Guide 297
Copyright © GrapeCity, Inc. All rights reserved.
IGroupSupport('IGroupSupportInterface'intheon-linedocumentation)interface
Interfacethatsupportsgrouping
GroupDataModel('GroupDataModelClass'intheon-linedocumentation)class
Classofgroupingdataintheunderlyingmodels
Group('GroupClass'intheon-linedocumentation)class Classintheunderlyingmodelsthatsupportsgrouping
Grouped('GroupedEvent'intheon-linedocumentation)andGrouping('GroupingEvent'intheon-linedocumentation)events
EventsinFpSpreadclass
GroupInfo('GroupInfoClass'intheon-linedocumentation) Classthatrepresentsgroupinginformation
GroupInfoCollection('GroupInfoCollectionClass'intheon-linedocumentation)
Collectionofgroupinginformation
Formoreinformationonotherhierarchicaldisplaysofdata,refertoWorkingwithHierarchicalDataDisplay.
YoucanalsodefineasetofpropertiesinanarraylistcalledGroupInfo.Settheappearanceofgroupedrowsbyaddingstylestothearraylistofappearancepropertiesforgrouping.AcollectionofGroupInfoobjectsisintheGroupInfoCollection.TosettheappearancesettingsinaGroupInfotoaparticularsheet,settheGroupInfospropertyonthatsheet.Appearancesettingsforgroupinginclude:
BackgroundcolorBorderFontForeground(text)colorHorizontalalignmentIndentIndentcolorVerticalalignment
Onlycolumnandsheetappearancesettingsremainwhengroupingisturnedon.Sincerowsandcellsaremovedwhenthegroupingfeatureisturnedon,anystyleorspansettingsareignored.
Formoreinformationaboutthegroupdatamodelandtheeffectonthesheetdatamodel,refertoCreatingaCustomGroup.YoucanusetheIsGroup('IsGroupMethod'intheon-linedocumentation)method,whichdetermineswhetherarequestedrowisadataroworagroupheaderrow.
Formoreinformationaboutgroupfooters,refertoDisplayingaFooterforColumnsorGroups.
Customizing the Group Bar
Youcancustomizetheappearanceofthegroupbaratthetopofthegroupingdisplay.
Youcanhideordisplaythegroupingbaratthetopofthesheet.Thepropertiesonthesheet(GroupBarInfo('GroupBarInfoProperty'intheon-linedocumentation)object)include:
GroupBarInfoProperty DescriptionBackColor('BackColorProperty'intheon-linedocumentation)
Setthebackgroundcolorofthegroupingbar
Height('HeightProperty'intheon-linedocumentation)
Settheheightofthegroupingbar
Visible('VisibleProperty'intheon-linedocumentation)
Setwhethertodisplaythegroupingbar
Spread Windows Forms Developer’s Guide 298
Copyright © GrapeCity, Inc. All rights reserved.
GroupVerticalIndent('GroupVerticalIndentProperty'intheon-linedocumentation)
Settheverticaldistancebetweengroupnames(whenmorethanonegroupnameisused)inthegroupingbar
YoucansetthemaximumlevelsofgroupingallowedonthesheetbysettingtheSheetViewobject'sGroupMaximumLevel('GroupMaximumLevelProperty'intheon-linedocumentation)property.
Creating a Custom Group
Whengroupingisturnedonforasheet,aseparatetargetgroupdatamodelisavailabletothesheet(orspreadsheetcomponent)andthisgroupdatamodelisflat,completelywithoutahierarchy.Thiscontainsthegroupheadersandothergrouping-specificdisplaydata.Underneaththatmodelisatargetdatamodelwheretherowdataresides.
Youcancustomizegroupingbyspecifyingyourowncomparer.Forexample,youcancreateacustomgroupthatisbydecadeifthecolumnhasyearinformation.AstheGrouping('GroupingEvent'intheon-linedocumentation)eventisraised,youcanpassinyourownIComparer(callitMyComparer,forexample).YoucandeterminewhatisdisplayedinthegroupheaderbysettingtheTextpropertyforthatgroup.
Interoperability of Grouping with Other Features
ThegroupingfeatureaffectsthedisplayandisnotintendedtoworkwithsomeotherfeaturesofSpreadthatalsoworkwiththedisplayofthespreadsheet.Whengroupinghappens,thedatamodelischangedandanewmodel(theGroupDataModel('GroupDataModelClass'intheon-linedocumentation))isused.Manyfeaturesarenotaffectedbygroupingatall,butsomefeatures,listedbelow,arenotintendedtooperatewithgrouping.Ingeneral,ifthefeatureinvolvestheappearanceorinteractivityofthesheetorcolumn,checkthelisttoseeifitisaffectedbygrouping.
Someformattingfeaturescanworkwithgrouping,butneedtobeappliedaftergroupingoccurs.Ifyouneedtoformatcells(colors,locked,andsoon),youmustapplytheformattingaftergrouping.
Aftergroupingrows,youshouldnotchangethecolumncountandrowcount.TheGroupDataModeldoesnotsupportchangingthecolumnorrowcount.Toaddorremovecolumnsorrows,youneedtocalltheoriginaldatamodelmethods.YoucanaccesstheoriginaldatamodelusingtheTargetModel('TargetModelProperty'intheon-linedocumentation)propertyoftheGroupDataModel('GroupDataModelClass'intheon-linedocumentation)class.
Thefollowingfeaturescanworkwithgroupingorarenotaffectedbygrouping:
Groupingandhiddencolumnsworktogether.Thegroupingfeatureaffectsonlythevisualdisplay.Suchthingsasexportandprintingarenotaffected.Groupingandinputmapsoractionmapsworktogether.
FeaturesThatDoNotInteroperatewithGrouping
ThesefeaturesdonotinteroperatewithgroupinginSpread.
Feature DescriptionAlternatingRows
Groupingandalternatingrowsdonotworktogether.Groupingchangestheorderoftherows,sohavingadisplayofalternatingrowswouldnotmakesense.Thus,thesefeaturesdonotworktogether.
ClipboardPaste
Pastingdoesnotworkwithgrouping.
ConditionalFormatting
Groupingandconditionalformattingdonotworktogether.Conditionalformattingrequiresthedefaultdatamodel.Thus,thesefeaturesdonotworktogether.
Filtering Groupingandfilteringdonotworktogether.Ifyouwanttousegrouping,youshouldnotusefilteringandyoushouldclearthefilterundertheGrouping('GroupingEvent'intheon-linedocumentation)event.
Spread Windows Forms Developer’s Guide 299
Copyright © GrapeCity, Inc. All rights reserved.
Formulas Groupingandformulasdonotworktogether.Formulasrequiresthedefaultdatamodel.Thus,thesefeaturesdonotworkwithgrouping.
Outlines Grouping(Outlookstyle)andoutlines(rangegroups)arenotintendedtoworktogether.
Sorting Groupingandsortingdonotworktogether.Groupingisatypeofsorting.Whengroupingison,clickingoncolumnheaderswillcausegroupingnotsorting.Thus,thesefeaturesdonotworktogether.
Managing Outlines (Range Groups) of Rows and Columns
Youcansetthedisplayofthespreadsheetcomponenttoallowrowsorcolumnstobegroupedasanoutlineaccordingtotheheaders.Thisdisplaysaseparateareabeyondtheheadersthatcontainsoutlinestoallowexpandingorcollapsinglevelsofrowsorcolumns.Thefigurebelowshowsthreelevelsofoutlineforrowsandtwolevelsofoutlineforcolumns.
Collapsedrowsthatarevisiblearestillvisiblewhenexpandingtheoutlineagain.Thisbehavioroftheoutlineissimilartootherspreadsheetprogramswithsomesubtledifferences.Thisfeatureisalsocalled"rangegrouping"sinceitoperatesonarangeofrowsorcolumns.
Thefollowingoptionsareavailabletogrouprowsandcolumnsintooutlines.
UsinganOutline(RangeGroup)ofRowsorColumnsCustomizingtheAppearanceofanOutline(RangeGroup)
Sinceoutlinesaffecttheperformanceofotherfeatures,besuretoreadInteroperabilityofOutlineswithOtherFeatures.
Using an Outline (Range Group) of Rows or Columns
Youcanformoutlinesofoneormorerowsorcolumns.Thereareseveralmethodsthatcreateanoutline(rangegroup)suchastheAddRangeGroup('AddRangeGroupMethod'intheon-linedocumentation)methodfortheSheetView('SheetViewClass'intheon-linedocumentation)class.
Theoutlineappearsattheleft(forrows)andtop(forcolumns)ofthespreadsheetbeyondtheheaders.Outlinescanbenested,creatinglevelsofoutlines.Thenumberedboxesthatappearintheoutlineareaallowyoutoexpandorcollapsealltheoutlinesofthatlevel.Youcanexpandandcollapserowsandcolumnsbyclickingontheexpandandcollapseiconsoronthenumberedoutlineheaders.
Spread Windows Forms Developer’s Guide 300
Copyright © GrapeCity, Inc. All rights reserved.
Thefigurebelowshowsthreelevelsofoutlineforrowsandcolumns,andshowstheterminologyofthepartsoftheoutlinearea.
UsingCode
1. SettheInterfaceRenderer('InterfaceRendererProperty'intheon-linedocumentation)propertytochangethedefaultstyle.
2. SettheRangeGroupBackgroundColor('RangeGroupBackgroundColorProperty'intheon-linedocumentation)propertytospecifytheoutlinebackground.
3. SettheRangeGroupButtonStyle('RangeGroupButtonStyleProperty'intheon-linedocumentation)propertytospecifythebuttonstyle.
4. UseAddRangeGroup('AddRangeGroupMethod'intheon-linedocumentation)toaddoutlines.
Example
Thisexamplecreatestwocolumnoutlinegroups.
C#fpSpread1.ActiveSheet.Rows.Count = 11;fpSpread1.ActiveSheet.Columns.Count = 6;fpSpread1.InterfaceRenderer = null;fpSpread1.ActiveSheet.RangeGroupBackgroundColor = Color.LightGreen;fpSpread1.ActiveSheet.RangeGroupButtonStyle = FarPoint.Win.Spread.RangeGroupButtonStyle.Enhanced;fpSpread1.ActiveSheet.AddRangeGroup(0, 8, true);fpSpread1.ActiveSheet.AddRangeGroup(0, 5, true);fpSpread1.ActiveSheet.AddRangeGroup(1, 3, false);fpSpread1.ActiveSheet.AddRangeGroup(1, 2, false);
VB
Spread Windows Forms Developer’s Guide 301
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.ActiveSheet.Rows.Count = 11FpSpread1.ActiveSheet.Columns.Count = 6FpSpread1.InterfaceRenderer = NothingFpSpread1.ActiveSheet.RangeGroupBackgroundColor = Color.LightGreenFpSpread1.ActiveSheet.RangeGroupButtonStyle = FarPoint.Win.Spread.RangeGroupButtonStyle.EnhancedFpSpread1.ActiveSheet.AddRangeGroup(0, 8, True)FpSpread1.ActiveSheet.AddRangeGroup(0, 5, True)FpSpread1.ActiveSheet.AddRangeGroup(1, 3, False)FpSpread1.ActiveSheet.AddRangeGroup(1, 2, False)
Customizing the Appearance of an Outline (Range Group)
Youcancustomizetheappearanceoftheoutline(rangegroup)usingpropertiesontheSheetView('SheetViewClass'intheon-linedocumentation)classorinaninterfacerenderer.
ThetwopropertiesintheSheetViewclassthatcanbeusedtocustomizetheappearanceare:
RangeGroupBackgroundColor('RangeGroupBackgroundColorProperty'intheon-linedocumentation)RangeGroupButtonStyle('RangeGroupButtonStyleProperty'intheon-linedocumentation)
YoucanalsouseanEnhancedInterfaceRenderertocustomizetheappearance.Thepropertiesinclude:
RangeGroupBackgroundColor('RangeGroupBackgroundColorProperty'intheon-linedocumentation)RangeGroupButtonBorderColor('RangeGroupButtonBorderColorProperty'intheon-linedocumentation)RangeGroupLineColor('RangeGroupLineColorProperty'intheon-linedocumentation)
Thelinecoloralsosetsthecolorofthepointsintheoutline.Thefollowingfigureshowstheresultsoftheexamplecodebelowwhereseveralofthesepropertiesareset.
Noticethattheoutlinebackgroundisdifferentfromthegrayareaofthespreadsheet.
Spread Windows Forms Developer’s Guide 302
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
1. Createanewinterfacerenderertoprovideacustomlooktooutlines.2. SettheRangeGroupBackgroundColor('RangeGroupBackgroundColorProperty'intheon-linedocumentation)tospecifythecolor.
3. SettheRangeGroupButtonBorderColor('RangeGroupButtonBorderColorProperty'intheon-linedocumentation)tospecifythecolorforthebuttonborder.
4. SettheRangeGroupLineColor('RangeGroupLineColorProperty'intheon-linedocumentation)tospecifythegrouplinecolor.
5. AddtherangegroupswiththeAddRangeGroup('AddRangeGroupMethod'intheon-linedocumentation)method.
Example
Thisexamplecreatesanoutlineintherowsandinthecolumnsandchangesvariouscolors.Theresultisshownintheprecedingfigure.
C#fpSpread1.ActiveSheet.Rows.Count = 11;fpSpread1.ActiveSheet.Columns.Count = 6;FarPoint.Win.Spread.EnhancedInterfaceRenderer outlinelook = new FarPoint.Win.Spread.EnhancedInterfaceRenderer();outlinelook.RangeGroupBackgroundColor = Color.LightGreen;outlinelook.RangeGroupButtonBorderColor = Color.Red;outlinelook.RangeGroupLineColor = Color.Blue;fpSpread1.InterfaceRenderer = outlinelook;fpSpread1.ActiveSheet.AddRangeGroup(0, 8, true);fpSpread1.ActiveSheet.AddRangeGroup(0, 5, true);fpSpread1.ActiveSheet.AddRangeGroup(1, 3, false);fpSpread1.ActiveSheet.AddRangeGroup(1, 2, false);
VBFpSpread1.ActiveSheet.Rows.Count = 11FpSpread1.ActiveSheet.Columns.Count = 6Dim outlinelook As New FarPoint.Win.Spread.EnhancedInterfaceRendereroutlinelook.RangeGroupBackgroundColor = Color.LightGreenoutlinelook.RangeGroupButtonBorderColor = Color.Redoutlinelook.RangeGroupLineColor = Color.BluefpSpread1.InterfaceRenderer = outlinelookFpSpread1.ActiveSheet.AddRangeGroup(0, 8, True)FpSpread1.ActiveSheet.AddRangeGroup(0, 5, True)FpSpread1.ActiveSheet.AddRangeGroup(1, 3, False)FpSpread1.ActiveSheet.AddRangeGroup(1, 2, False)
Interoperability of Outlines with Other Features
Theoutline(rangegroup)featureaffectsthedisplayandisnotintendedtoworkwithsomeotherfeaturesofSpreadthatalsoworkwiththedisplayofthespreadsheet.Manyfeaturesarenotaffectedbyoutlinesatall,butsomefeatures,listedbelow,arenotintendedtooperatewiththisfeature.Ingeneral,ifthefeatureinvolvestheappearanceorinteractivityofthesheetorcolumn,checkthelisttoseeifitisaffectedbyoutlines.
Becarefulwhenaddingrowsorcolumnstoadisplaythathasanoutline.
Spread Windows Forms Developer’s Guide 303
Copyright © GrapeCity, Inc. All rights reserved.
Thefollowingfeaturescanworkwithgroupingorarenotaffectedbygrouping:
Outlinesandhiddencolumnsworktogether.Theoutlinefeatureaffectsonlythevisualdisplay.Suchthingsasexportandprintingarenotaffected.Outlinesandinputmapsoractionmapsworktogether.
FeaturesThatDoNotInteroperatewithOutlines
ThesefeaturesdonotinteroperatewithoutlinesinSpread.
Feature DescriptionAlternatingRows
Outlinesandalternatingrowsmaynotworktogether.Outlineschangestheorderoftherows,sohavingadisplayofalternatingrowswouldnotmakesense.Thus,thesefeaturesdonotworktogether.
HierarchicalDisplay
Outlinesandhierarchiesaretwodifferentanddissimilarwaysofgroupinganddisplayingdata.Thesefeaturesarenotintendedtoworktogether.
Outlook-styleGrouping
OutlinesandOutlook-stylegroupingaretwodifferentanddissimilarwaysofgroupinganddisplayingdata.Thesefeaturesarenotintendedtoworktogether.
Sorting Outlinesandsortingmightnotworktogether.
Managing Sorting of Rows of User Data
Youcansortthedatadisplayedinthesheeteitherbycolumnorbyrow.Typically,alltherowsofasheetaresortedbythevaluesinaparticularcolumn.ButSpreadallowsmanywaysofperformingasortwithvariouspropertiesandmethodsforeachtypeofsorting.Ingeneral,sortingdatacanbeperformedandcustomizedbyanyofthefollowingways:
AllowingtheUsertoAutomaticallySortRowsUsingAutomaticSortingSortingRows,Columns,orRangesSettingtheAppearanceofSortIndicators
Therearevariouspropertiesofsorting.Theorderofthesortcanbeinascendingorder(AtoZ,zeroto9)ordescendingorder(ZtoA,9tozero).Themethodofcomparisoncanbecustomized.Youcanselectwhichvaluestouseasakeywhencomparinginordertosortthevalues.Thesortindicator,anarrowtypically,canbedisplayedintheheaderforthecolumnbeingusedasasortkey.Formoreinformationoncustomizingthesorting,refertotheSortInfo('SortInfoClass'intheon-linedocumentation)object.Withthisobject,youcansettheparametersforsortingandthenspecifythisobjectintheparticularsortmethodyouchoose.
Thecelltypedoesnotmatterforsorting.Thesortingisdonedependingonthedatatypeofthevaluesinthecells.IfyousortcellswithdataoftheDateTimetype,thenitsortsthosecellsbydate,andifyousortcellswithdataofthestringtype,itsortsthosecellsalphabetically.
Beawareofhowsortingworkswiththedatainthemodels.IfyouusetheautomaticsortingbyclickingthecolumnheaderoryoucalltheSortRows('SortRowsMethod'intheon-linedocumentation)methodofthesheet,thenthedatamodelisnotsorted,justthedatathatisdisplayedtotheuser.Inthiscase,anydatathatishiddenbeforethesortishiddenafterthesort,sinceSpreadmovesanyhiddenrowsautomatically.IfyouusetheSortRange('SortRangeMethod'intheon-linedocumentation)method,thedataissortedinthedatamodelanddatathatishiddenmaybecomevisibleandviceversausingthismethod.Whenyousortdata,onlythedatamodelisgettingsorted.Theselectionmodeldoesnotgetsorted.Ifyouwanttheselectedrowtomove,youwouldneedtowritecodeintheAutoSortedColumn('AutoSortedColumnEvent'intheon-linedocumentation)andAutoSortingColumn('AutoSortingColumnEvent'intheon-linedocumentation)eventstomovetheselection.Formoreinformationonthemodels,refertoUnderstandingtheUnderlyingModels.
Sortingperformedbyclickingcolumnheaderssortsonlythedisplayeddataanddoesnotaffecttheorderofactualdata
Spread Windows Forms Developer’s Guide 304
Copyright © GrapeCity, Inc. All rights reserved.
inthedatamodel;therefore,youcanresetthesorteddatabeingdisplayedtotheorderofactualdatabycallingeithertheResetViewRowIndexes('ResetViewRowIndexesMethod'intheon-linedocumentation)methodortheResetViewColumnIndexes('ResetViewColumnIndexesMethod'intheon-linedocumentation)methodintheSheetView.DocumentModelsclass.YoucannotresettheresultwhentheactualdatainthedatamodelaresortedwiththeSortRange('SortRangeMethod'intheon-linedocumentation)methodintheSheetView('SheetViewClass'intheon-linedocumentation)class.
SortingisnotintendedtobeusedwhenOutlook-stylegroupingisturnedon.Formoreinformationaboutgrouping(whichisatypeofsorting),refertoManagingGroupingofRowsofUserData.
ForinformationonsortingwithintheSpreadDesigner,refertotheSpreadDesignerGuide(on-linedocumentation).
Note:CellspansbecomeinvisiblewhensortingasheetwithanymethodexceptSortRange.
Allowing the User to Automatically Sort Rows
Youcansetthespreadsheettoallowtheusertoautomaticallysortthedatawhenacolumnheaderisclicked.Thefirsttimethecolumnheaderisclicked(selected)theunsortediconisdisplayed.Thesecondclickdisplaysthesorticonandsortsthecolumn.Iftheuserclickssuccessivelyonthesamecolumn,thenthedirectionofthesortisreversed.Thisdoesnotaffectthedatamodel,onlyhowthedataisdisplayed.Thisfigureshowstheunsortedicon:
UsetheColumn('ColumnClass'intheon-linedocumentation)objectAllowAutoSort('AllowAutoSortProperty'intheon-linedocumentation)propertyortheSheetView('SheetViewClass'intheon-linedocumentation)SetColumnAllowAutoSort('SetColumnAllowAutoSortMethod'intheon-linedocumentation)methodtoallowtheusertoperformautomaticsortingwhentheheadercellofacolumnisclicked.SettheSortIndicator('SortIndicatorProperty'intheon-linedocumentation)propertyofthecolumnyouwanttoshowtheindicator.
TheSetColumShowSortIndicator('SetColumnShowSortIndicatorMethod'intheon-linedocumentation)methodorShowSortIndicator('ShowSortIndicatorProperty'intheon-linedocumentation)propertycanbesettodisplayorhidethesortindicator.Thesortindicatorappearsintheheadercolumnasshowninthefollowingfigure,illustratingtheascendinganddescendingsortindicators.
AscendingSortIndicator DescendingSortIndicator
Whenausersortsdata,theAutoSortingColumn('AutoSortingColumnEvent'intheon-linedocumentation)eventoccursbeforethesortandthentheAutoSortedColumn('AutoSortedColumnEvent'intheon-linedocumentation)eventoccursafterthesort.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetforwhichtosetupsorting.5. Inthepropertieslist,selecttheColumnspropertyandclickthebuttontoopentheCell,Column,andRow
Spread Windows Forms Developer’s Guide 305
Copyright © GrapeCity, Inc. All rights reserved.
Editor.6. Selectthecolumnsforwhichyouwanttoallowautomaticsorting.7. Inthepropertieslist,selecttheAllowAutoSortpropertyandsetthevaluetoTrue.8. ClickOKtocloseeachoftheeditors.
UsingaShortcut
UseeithertheAllowAutoSort('AllowAutoSortProperty'intheon-linedocumentation)propertyofthecolumnsortheSetColumnAllowAutoSort('SetColumnAllowAutoSortMethod'intheon-linedocumentation)methodoftheSheetsobjecttoallowautomaticsortingofthespecifiedcolumns.
Example
Thisexampleallowsautomaticsortingforthefirst30columnsinthesheet.
C#fpSpread1.Sheets[0].Columns[0,29].AllowAutoSort = true;//or//fpSpread1.Sheets[0].SetColumnAllowAutoSort(0,30,true);
VBFpSpread1.Sheets(0).Columns(0,29).AllowAutoSort = True'or'FpSpread1.Sheets(0).SetColumnAllowAutoSort(0,30,True)
UsingCode
UsetheAllowAutoSort('AllowAutoSortProperty'intheon-linedocumentation)propertytoallowautomaticsortingofthespecifiedcolumns.
Example
Thisexampleallowsautomaticsortingforthefirst30columnsinthesheet.
C#FarPoint.Win.Spread.Column mycols;mycols = fpSpread1.ActiveSheet.Columns[0,29];mycols.AllowAutoSort = true;
VBDim mycols As FarPoint.Win.Spread.Columnmycols = FpSpread1.ActiveSheet.Columns(0,29)mycols.AllowAutoSort = True
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttoallowautomaticsorting.2. Fromthepropertylistforthesheet,selectColumns.ClickonthebuttontoopentheCell,Column,andRow
editor.3. Selectthecolumnsforwhichyouwanttoallowautomaticsorting.4. Inthepropertieslist,selecttheAllowAutoSortpropertyandsetthevaluetoTrue.
Spread Windows Forms Developer’s Guide 306
Copyright © GrapeCity, Inc. All rights reserved.
5. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Using Automatic Sorting
Youcansortentirerowsorcolumnsautomaticallyinasheet.Thecomponentautomaticallysortstherowsinasheetaccordingtothespecifiedcolumninascendingorderunlessthesheetwaspreviouslyautomaticallysortedascending.Theautomaticsortingdisplaysthesortindicatorunlessthesortindicatorforthecolumnhasbeendisabled.Thisdoesnotaffectthedatamodel,onlyhowthedataisdisplayed.Differentoverloadsprovidedifferentwaystoperformthesorting.
UsetheAutoSortColumn('AutoSortColumnMethod'intheon-linedocumentation)methodtosortthedisplayinasheetautomaticallyaccordingtothespecifiedkeyandusetheSetColumShowSortIndicator('SetColumnShowSortIndicatorMethod'intheon-linedocumentation)tosetwhethertodisplaythesortindicator.TheAutoSortColumn('AutoSortColumnMethod'intheon-linedocumentation)methodperformsthesameactionasclickinginthecolumnheaderofthespecifiedcolumnthathasitsAllowAutoSort('AllowAutoSortProperty'intheon-linedocumentation)propertysettoTrue.TheAllowAutoSort('AllowAutoSortProperty'intheon-linedocumentation)propertydoesnotneedtobesettoTruetousethismethod.Ifthismethodiscalledsuccessivelywiththesamecolumnindex,thenthedirectionofthesortisreversed.Ifthemethodiscalledwithadifferentcolumnindex,thenthepreviouslysortedcolumn'ssortindicatorischangedbacktoSortIndicator.None(ifthereisone)andthespecifiedcolumnisusedasthekeycolumninacalltoSortRows('SortRowsMethod'intheon-linedocumentation)tosortalltherowsinthesheetbythatcolumn.Thisaffectsonlythearrangementofrowsorcolumnsonasheetanddoesnotchangethearrangementofthedata;thatis,thisdoesnotaffectthedatamodel,onlyhowthedataisdisplayed.
Note:TheSetColumShowSortIndicator('SetColumnShowSortIndicatorMethod'intheon-linedocumentation)methodmustbecalledbeforetheAutoSortColumn('AutoSortColumnMethod'intheon-linedocumentation)method;otherwise,thesortindicatorisshownandremainsdisplayed.
UsingCode
1. AllowtheautomaticsortingofacolumnorcolumnsbyusingtheSetColumnAllowAutoSort('SetColumnAllowAutoSortMethod'intheon-linedocumentation)method.
2. Ifyouwanttodisplayasortindicator,setthecolumntoshowthesortindicatorwiththeSetColumnShowSortIndicator('SetColumnShowSortIndicatorMethod'intheon-linedocumentation)method.
3. PerformtheautomaticsortbysettingtheAutoSortColumn('AutoSortColumnMethod'intheon-linedocumentation)method.
Example
Thisexampleautomaticallysortsthefirstcolumn.
C#fpSpread1.ActiveSheet.SetColumnAllowAutoSort(0, true);fpSpread1.ActiveSheet.SetColumnShowSortIndicator(0, false);fpSpread1.ActiveSheet.AutoSortColumn(0);
VBfpSpread1.ActiveSheet.SetColumnAllowAutoSort(0, True)fpSpread1.ActiveSheet.SetColumnShowSortIndicator(0, False)fpSpread1.ActiveSheet.AutoSortColumn(0)
Spread Windows Forms Developer’s Guide 307
Copyright © GrapeCity, Inc. All rights reserved.
Sorting Rows, Columns, or Ranges
YoucansortentirerowsorcolumnsinasheetusingcodeortheSpreadDesigner.Tosortalltherowsofanentiresheetbasedonthevaluesofagivencolumnisthemostcommoncase,butSpreadallowsyoutosorteitherrowsorcolumnsandtospecifywhichcolumnorrowtouseasakeyforsorting.Thissortappliestotheentiresheet.
UsetheSortColumns('SortColumnsMethod'intheon-linedocumentation)(orSortRows('SortRowsMethod'intheon-linedocumentation))methodtosortthearrangementofcolumns(orrows)inasheetusingoneormorerows(orcolumns)asthekey.Thisdoesnotaffectthedatamodel,onlyhowthedataisdisplayed.Severaloverloadsprovidedifferentwaystosortthecolumns(orrows).Tofurthercustomizethewaysortingisperformed,usetheSortInfo('SortInfoClass'intheon-linedocumentation)objectinconjunctionwiththesemethods.
Youcansortdatainarangeofcellswithoutre-arrangingtheentireroworcolumninasheet.Thismaybeusefulwhen,forexample,youwishtoarrangemanyrowsinorderofquantitybutnotincludeinthesortthefinalrowthatcontainsthetotalsofthosequantities.Inthiscase,youwouldsortthedatainarangeofcellsbutleavethefinalrow,thebottomline,unsorted.
Therearetwowaystosortdatainarange.Forbounddata,usetheSortRows('SortRowsMethod'intheon-linedocumentation)andSortColumns('SortColumnsMethod'intheon-linedocumentation)methodsusingthespecifiedparametersintheoverloadstospecifywhichrangeofrowsorcolumnstosort.Forunbounddata,usetheSortRange('SortRangeMethod'intheon-linedocumentation)method.FormoreinformationonsortingusingtheSpreadDesigneratdesigntime,refertotheUsingtheSpreadDesignerprocedurebelow.
TheSortRange('SortRangeMethod'intheon-linedocumentation)methodisforunbounddataonly.Thismethodsortsthedatainarangeofcellsbymovingthedataaroundinthedatamodelandmovingthecell-levelstylesalongwithit.Thismethodisnotintendedforbounddata,asitmovesdata(notnecessarilybyentireroworcolumn)andhastheeffectofmovingthedataaroundinthedatasource.
WiththesortInfoarrayoftheSortRange('SortRangeMethod'intheon-linedocumentation)method,youcanspecifymultiplecriteriaforsortingthedata.Thismethodgivesyoutheabilitytosort(orarrange)datainasmallersubsetthanentirerowsorcolumnsinasheet.Formoreinformation,refertotheSortInfo('SortInfoClass'intheon-linedocumentation)object.
UsingCode
Tosortrows,usetheSortRows('SortRowsMethod'intheon-linedocumentation)method;tosortcolumns,usetheSortColumns('SortColumnsMethod'intheon-linedocumentation)method.
Example
Thisexamplesortsalltherowsinthesheetaccordingtothevaluesinthesecondcolumn.Sincecolumnindexiszero-based,thesecondcolumnis1.Thesortindicatoristurnedon.
C#fpspread1.ActiveSheet.SortRows(1,true,true);
VBFpSpread1.ActiveSheet.SortRows(1,True,True)
Example
Thisexamplesortsrows12to230usingapredefinedarrayofsortinformation.
C#FarPoint.Win.Spread.SortInfo[] sorter = new FarPoint.Win.Spread.SortInfo[1];
Spread Windows Forms Developer’s Guide 308
Copyright © GrapeCity, Inc. All rights reserved.
sorter[0] = new FarPoint.Win.Spread.SortInfo(0, false, System.Collections.Comparer.Default);fpSpread1.ActiveSheet.SortColumns(12,230,sorter);
VBDim sorter(1) As FarPoint.Win.Spread.SortInfosorter(0) = New FarPoint.Win.Spread.SortInfo(0, False, System.Collections.Comparer.Default)FpSpread1.ActiveSheet.SortColumns(12,230,sorter)
UsingtheSpreadDesigner
1. AtdesigntimeyoucansortdatausingtheSpreadDesignerinaveryflexibleway.Selectthecellsyouwanttosort,eitherbydraggingoverthecellsorselectingtheroworcolumnheaders.
2. FromtheDatamenu,selectSort.TheSortdialogisdisplayed.3. IntheSortdialog,selecttheoptionsyouwouldlikeandclickOK.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting the Appearance of Sort Indicators
Youcancustomizethedisplayofsortingindicatorsintheseways:
UsingCustomSortIndicatorImagesShowingandHidingSortIndicatorsDeterminingWhichHeaderRowDisplaystheSortIndicators
UsingCustomSortIndicatorImages
Youcancustomizethesortingindicatorimagethatappearsinthecolumnheaderofcolumnsthatallowsorting.Oneofthedefaultsortindicatorsisshownintheheaderofthefirst(A)columninthefollowingfigure.
OnewayistooverridethePaintSortIndicator('PaintSortIndicatorMethod'intheon-linedocumentation)methodintheCellTypeColumnHeaderRenderer('ColumnHeaderRendererClass'intheon-linedocumentation)classanduseyourowncustomindicator.
AnotherwayistousetheGetImage('GetImageMethod'intheon-linedocumentation)andSetImage('SetImageMethod'intheon-linedocumentation)methodsintheSpreadView('SpreadViewClass'intheon-linedocumentation)class,whichisdescribedinCustomizingtheUserInterfaceImages.
ShowingandHidingSortIndicators
Youcandisplayfortheuserorhidefromtheuserthesortindicatorsthatmayappearinthecolumnheaders.TheColumn.ShowSortIndicator('ShowSortIndicatorProperty'intheon-linedocumentation)propertyandtheSheetView.SetColumnShowSortIndicator('SetColumnSortIndicatorMethod'intheon-linedocumentation)methodsetwhetherthecolumnshowsthesortindicatorthenexttimethattheSheetView.AutoSortColumn('AutoSortColumnMethod'intheon-linedocumentation)methodiscalledforthatcolumn.IthasnoeffectuntilAutoSortColumniscalledforthatcolumnindex.
Spread Windows Forms Developer’s Guide 309
Copyright © GrapeCity, Inc. All rights reserved.
DeterminingWhichHeaderRowDisplaystheSortIndicators
YoucanspecifyinwhichrowtodisplaythesortindicatorsthatmayappearinthecolumnheadersbysettingtheColumnHeaderAutoSortIndex('ColumnHeaderAutoSortIndexProperty'intheon-linedocumentation)property.Bydefaulttheyappearinthebottomofthecolumnheaderrows,butifyouhavemorethanoneheaderrow,youcanspecifywhichrow.YoucanspecifywhichrowdisplaystheautomatictextbysettingtheColumnHeaderAutoTextIndex('ColumnHeaderAutoTextIndexProperty'intheon-linedocumentation)property(ortheColumnHeader.AutoTextIndex('AutoTextIndexProperty'intheon-linedocumentation)property);however,changingtherowthatdisplaystheautomatictextdoesnotchangetherowthatdisplaysthesortindicator.
UsingCode
Tocreateacustomsortindicator:
Createanewcolumnheaderrendererclass.Customizethesortindicatorthatappearsinthecolumnheader.
Example
Thefollowingexamplecreatesacustomsortindicator.
C#// In the form load section, allow sorting (and filtering).private void Form1_Load(object sender, System.EventArgs e){ fpSpread1.ActiveSheet.ColumnHeader.DefaultStyle.Renderer = new myColumnHeaderRenderer(); fpSpread1.Sheets[0].Columns[0].AllowAutoSort =true; fpSpread1.Sheets[0].Columns[0].AllowAutoFilter =true;}// Define a new column header renderer.public class myColumnHeaderRenderer : FarPoint.Win.Spread.CellType.ColumnHeaderRenderer{ // Override the sorting indicator paint method. override public void PaintSortIndicator(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearance appearance, float zoomFactor) { g.FillRectangle(new SolidBrush(Color.Red), r); } // Override the filtering indicator paint method. override public void PaintFilterIndicator(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearance appearance, float zoomFactor) { g.FillRectangle(new SolidBrush(Color.Blue), r); }} //End Form1_Load
VB' Define a new column header renderer.Public Class myColumnHeaderRendererInherits FarPoint.Win.Spread.CellType.ColumnHeaderRenderer ' Override the sorting indicator paint method. Public Overrides Sub PaintSortIndicator(ByVal g As Graphics, ByVal r As Rectangle, ByVal appearance As FarPoint.Win.Spread.Appearance, ByVal zoomFactor As Single)
Spread Windows Forms Developer’s Guide 310
Copyright © GrapeCity, Inc. All rights reserved.
g.FillRectangle(New SolidBrush(Color.Red), r) End Sub 'PaintSortIndicator ' Override the filtering indicator paint method. Public Overrides Sub PaintFilterIndicator(ByVal g As Graphics, ByVal r As Rectangle, ByVal appearance As FarPoint.Win.Spread.Appearance, ByVal zoomFactor As Single) g.FillRectangle(New SolidBrush(Color.Blue), r) End Sub 'PaintFilterIndicatorEnd Class 'myColumnHeaderRenderer' In the form load section, allow sorting (and filtering).Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load FpSpread1.ActiveSheet.ColumnHeader.DefaultStyle.Renderer = New myColumnHeaderRenderer FpSpread1.Sheets(0).Columns(0).AllowAutoSort = True FpSpread1.Sheets(0).Columns(0).AllowAutoFilter = TrueEnd Sub 'Form1_Load
Spread Windows Forms Developer’s Guide 311
Copyright © GrapeCity, Inc. All rights reserved.
Customizing Interaction with Cell Types
Celltypesdefinethetypeofinformationthatappearsinacell,howthatinformationisdisplayed,andhowtheusercaninteractwithit.Therearetwodifferentgroupsofcelltypesthatcanbesetforcellsinasheet:onesthataresimplyrelatedtoformattingoftextinacellandonesthatdisplayacontrolorgraphic.Spreadincludesbuilt-incelltypesandallowsyoudefinecustomcelltypes.Celltypescanbeassignedtoindividualcellsorentirerowsorcolumns.
Thesetasksofworkingwithcelltypesareorganizedintothesebroadcategories:
UnderstandingHowCellTypesWorkWorkingwithEditableCellTypesWorkingwithGraphicalCellTypesUnderstandingAdditionalFeaturesofCellTypes
NotethatsomegraphicalelementsincertaincelltypesareaffectedbyXPthemes(visualstyles).SettingtheVisualStyles('VisualStylesProperty'intheon-linedocumentation)propertyoftheSpreadcomponentto"off"canallowvisualcustomizationsofthosegraphicalcelltypestoworkasexpected.Formoreinformation,refertoUsingXPThemeswiththeComponent.
Fordetailedinformationonclassesbehindthevariousbuilt-incelltypes,refertotheFarPoint.Win.Spread.CellType('FarPoint.Win.Spread.CellTypeNamespace'intheon-linedocumentation)namespace.
ForinformationonsettingcelltypesusingtheSpreadDesigner,refertotheSpreadDesignerGuide(on-linedocumentation).
Understanding How Cell Types Work
Thesetopicsdescribehowcelltypeswork:
UnderstandingCellTypeBasicsDeterminingtheCellTypeoftheActiveCellUnderstandingHowCellTypesDisplayandFormatDataUnderstandingHowCellTypeAffectsModelData
Understanding Cell Type Basics
Youcanspecifythewayauserinteractswithacell,includinghowdataisentered,displayed,andvalidated,byspecifyingthecelltype.Thecelltypedefinesaneditorcontrolforthecellthathandlesdataentry,aformattercontroltohandlehowthedataisinterpreted,andarenderercontrolthathandleshowthedataisdisplayedinthecell.Examplesofcelltypesarecheckboxcell,date-timecell,orasimpletextcell.
Celltypescanbesetforindividualcells,columns,rows,arangeofcells,oranentiresheet.Foranycelltypetherearepropertiesofacellthatcanbeset.Ingeneral,workingwithcelltypesincludesdefiningthecelltype,settingtheproperties,andapplyingthatcelltypetocells.
Payattentiontodatatypeswhenworkingwithcelltypes.Forseveralcelltypes,includingComboBoxCellType('ComboBoxCellTypeClass'intheon-linedocumentation),DateTimeCellType('DateTimeCellTypeClass'intheon-linedocumentation),andMultipleOptionCellType('MultiOptionCellTypeClass'intheon-linedocumentation),thereisanEditorValueproperty.MakesuretheValuepropertyyouaresettinginthecellmatchesthetypespecifiedbytheEditorValueproperty.
Editor,Formatter,andRenderer
Acelltypeconsistsofaneditor,arenderer,andaformatter.Theeditorisacontrolinstancethatiscreatedandplacedinthelocationofthecellwhenthecellgoesintoeditmode.Theeditorisresponsibleforcreatingandmanagingthecell's
Spread Windows Forms Developer’s Guide 312
Copyright © GrapeCity, Inc. All rights reserved.
editcontrolwhenineditmode.Theformatterisresponsibleforconvertingthecell'svaluetoandfromtext(forexamplewhengettingorsettingacell'sText('TextProperty'intheon-linedocumentation)property).Therendererpaintsthecontrolinsidethecellrectanglewhentheeditorisnotthereorwhenthecellisnotineditmode.
Inmostcases,youwantthecelltolookthesamewhetheryouareineditmodeornotineditmode.Inthesecases,youwouldcreateasinglecelltypeandassignittothecell'sCellType('CellTypeProperty'intheon-linedocumentation)property.Thissinglecelltypeisusedasthecell'seditor,renderer,andformatter.Ifyouwantthecelltoappeardifferentlydependingonwhetheryouareineditmodeornotineditmode,thenyoucancreatetwodifferentcelltypesandassignonecelltypeasthecell'seditorandtheothercelltypeasthecell'srenderer.Inthiscase,youprobablyalsowanttoassignoneofthecelltypesasthecell'sformatter.Formoreinformation,refertotheICellType('ICellTypeInterface'intheon-linedocumentation)interface.
EditBaseCellType
Thedesignofcelleditingrequiresthatthecelltypereturnaneditorcontrolthatisthenplacedoverthecell.Theeditorcontrolcanbetextbased(forexample,textbox)orgraphicsbased(forexample,checkbox).Theeditorcontrolcandropdownlists(forexample,combobox)orpopupdialogs(forexample,datepicker).TheEditBaseCellType('EditBaseCellTypeClass'intheon-linedocumentation)classisaclassfromwhichthebuilt-intextbasedcelltypes(forexample,general,text,number,data-time,andsoon)arederived.Theclasscanalsobeusedtoderivecustomcelltypesthataretextbased.TheISubEditor('ISubEditorInterface'intheon-linedocumentation)interfaceisusedtocombineatext-basededitorwithadrop-downlist(forexample,combobox)orpop-updialog(forexampledatepicker).Thedatamodelcanholdanyvalue,includingcolors.Thecelltypeisalwayspassedtherawvaluefromthedatamodel.
HeaderCells
Whileyoucanassignacelltypetothecellsintherowheaderorcolumnheader,thecelltypeisonlyusedforpaintingpurposes;thecomponentrendersheadercellsbutdoesnotallowediting.In‑celleditingislimitedtocellsinthedataarea.Ifyouwanttohavesomethingeditablethatactslikeaheader,youcanhide(turnoff)thecolumnheader,freezethefirstrowofthespreadsheet,thenusethefrozenrowtoappearasheadercells.
Determining the Cell Type of the Active Cell
Youcandeterminethecelltypeoftheactivecell.YoucanusetheGetCellType('GetCellTypeMethod'intheon-linedocumentation)methodoftheSheetView('SheetViewClass'intheon-linedocumentation)class.
Understanding How Cell Types Display and Format Data
ThevalueoftheTextpropertycontainstheformatteddataasdisplayedinthecell;thevalueoftheValuepropertycontainstheunformatteddataassavedinthemodel.YoucanusetheSheetView('SheetViewClass'intheon-linedocumentation)GetText('GetTextMethod'intheon-linedocumentation)andGetValue('GetValueMethod'intheon-linedocumentation)methodstoobtainthecontentsofthecell,regardlessofcelltype.
Thefollowingtableliststheeditablecelltypes,andhoweachcelltypeworkswiththedata,whetherformatted(Text)orunformatted(Value).
EditableCellType SampleInput
FormattedData
UnformattedData
CurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation)
"$10,000.00" "$10,000.00" 10000.00
DateTimeCellType('DateTimeCellTypeClass'intheon-linedocumentation)
"10/29/2002" "10/29/2002" DateTimeobjectofTuesday,October29,200212:00:00AM
GcCharMaskCellType "123-45- "123-45-6789" "123456789"
Spread Windows Forms Developer’s Guide 313
Copyright © GrapeCity, Inc. All rights reserved.
('GcCharMaskCellTypeClass'intheon-linedocumentation)
6789"
GcDateTimeCellType('GcDateTimeCellTypeClass'intheon-linedocumentation)
"10/29/2002" "10/29/2002" DateTimeobjectofTuesday,October29,200212:00:00AM
GcMaskCellType('GcMaskCellTypeClass'intheon-linedocumentation)
"123-45-6789"
"123-45-6789" "123456789"
GcNumberCellType('GcNumberCellTypeClass'intheon-linedocumentation)
"10000.00" "10000.00" 10000.00
GcTextBoxCellType('GcTextBoxCellTypeClass'intheon-linedocumentation)
Anytext Stringofthattext
Stringofthattext
GcTimeSpanCellType('GcTimeSpanCellTypeClass'intheon-linedocumentation)
"1.22:50:40" "1.22:50:40" TimeSpanobject{1.22:50:40}
GeneralCellType('GeneralCellTypeClass'intheon-linedocumentation)
Anydata Stringofthatdata
DependsonwhetherDateTime,Boolean,orTextreturnstheDateTimeobject,theBooleanvalue,ortheTextvalue
MaskCellType('MaskCellTypeClass'intheon-linedocumentation)
"123-45-6789"
"123-45-6789" "123456789"
NumberCellType('NumberCellTypeClass'intheon-linedocumentation)
"10000.00" "10000.00" 10000.00
PercentCellType('PercentCellTypeClass'intheon-linedocumentation)
"15%" "15%" 0.15
RegularExpressionCellType('RegularExpressionCellTypeClass'intheon-linedocumentation)
"99-999-9999"
"99-999-9999" "99-999-9999"
TextCellType('TextCellTypeClass'intheon-linedocumentation)
Anytext Stringofthattext
Stringofthattext
Thefollowingtableliststhegraphicalcelltypes,andhoweachcelltypeworkswiththeTextandValueproperties.
GraphicalCellType SampleInput
TextData ValueData
BarCodeCellType('BarCodeCellTypeClass'intheon-linedocumentation)
Pictureasdata
N/A N/A
ButtonCellType('ButtonCellTypeClass'intheon-linedocumentation)two-state
True "1" True
False "0" False
Notsetlooksfalse
Emptystring False
CheckBoxCellType('CheckBoxCellTypeClass'intheon-linedocumentation)two-state
True(checked)
"True" 1
False(unchecked)
"False" 0
Spread Windows Forms Developer’s Guide 314
Copyright © GrapeCity, Inc. All rights reserved.
Notsetlooksfalse
Emptystring False
CheckBoxCellType('CheckBoxCellTypeClass'intheon-linedocumentation)three-state
True(checked)
"1" 1
False(unchecked)
"0" 0
Indeterminate(gray)
"2" 2
Notsetlooksfalse
Emptystring 0
ColorPickerCellType('BarCodeCellTypeClass'intheon-linedocumentation)
Selectedcolor Colorname Colorname
ComboBoxCellType('ComboBoxCellTypeClass'intheon-linedocumentation)andMultiColumnComboBoxCellType('MultiColumnComboBoxCellTypeClass'intheon-linedocumentation)
Anyitem Textofselecteditem
Textofselecteditemorindexofselecteditem(seetheEditorValue('EditorValueProperty'intheon-linedocumentation)property)
Nothingselected
Emptystring Null
GcComboBoxCellType('GcComboBoxCellTypeClass'intheon-linedocumentation)
Anyitem Textofselecteditem
Textofselecteditemorindexofselecteditem(seetheEditorValue('EditorValueProperty'intheon-linedocumentation)property)
Nothingselected
Emptystring Null
HyperLinkCellType('HyperLinkCellTypeClass'intheon-linedocumentation)
anytext ArrayofBooleanvalues:"True"(forvisitedlink)or"False"(fornotvisited)
ArrayofBooleanvalues:"True"(forvisitedlink)or"False"(fornotvisited)
ImageCellType('ImageCellTypeClass'intheon-linedocumentation)
Pictureasdata
N/A N/A
ListBoxCellType('ListBoxCellTypeClass'intheon-linedocumentation)
Array Array Array
MultiOptionCellType('MultiOptionCellTypeClass'intheon-linedocumentation)
Anyitemselected
Textofselecteditem
Indexofselecteditem(numeric)
Nothingselected
Emptystring Null
ProgressCellType('ProgressCellTypeClass'intheon-linedocumentation)
15,between10and20
"50%"(stringrepresentationofnumericvalue)
15(actualvalue)
Spread Windows Forms Developer’s Guide 315
Copyright © GrapeCity, Inc. All rights reserved.
RichTextCellType('RichTextCellTypeClass'intheon-linedocumentation)
Stringinrichtextformat
Stringinrichtextformat
Stringinrichtextformat
SliderCellType('SliderCellTypeClass'intheon-linedocumentation)
4,between0and10
"4"(stringrepresentationofnumericvalue)
4
Forinformationonotheraspectsofcelldisplay,refertoResizingaCelltoFittheData.
Understanding How Cell Type Affects Model Data
Thecelltypeaffectshowthevaluesarestoredinthemodel.
Thefollowingtableliststheeditablecelltypesandthedatatypeofthevalueinthecellthatiswrittentothedatamodel.
EditableCellType DataTypeWrittentoModel
CurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation)
Decimal
DateTimeCellType('DateTimeCellTypeClass'intheon-linedocumentation)
Date-TimeObject
GcCharMaskCellType('GcCharMaskCellTypeClass'intheon-linedocumentation)
String
GcDateTimeCellType('GcDateTimeCellTypeClass'intheon-linedocumentation)
Date-TimeObject
GcMaskCellType('GcMaskCellTypeClass'intheon-linedocumentation)
String
GcNumberCellType('GcNumberCellTypeClass'intheon-linedocumentation)
Double
GcTextBoxCellType('GcTextBoxCellTypeClass'intheon-linedocumentation)
String
GcTimeSpanCellType('GcTimeSpanCellTypeClass'intheon-linedocumentation)
TimeSpanObject
GeneralCellType('GeneralCellTypeClass'intheon-linedocumentation)
DependswhetherDate-Time,Boolean,orString
MaskCellType('MaskCellTypeClass'intheon-linedocumentation) String
NumberCellType('NumberCellTypeClass'intheon-linedocumentation)
Double
PercentCellType('PercentCellTypeClass'intheon-linedocumentation)
Double
RegularExpressionCellType('RegularExpressionCellTypeClass'intheon-linedocumentation)
String
TextCellType('TextCellTypeClass'intheon-linedocumentation) String
Thefollowingtableliststhegraphicalcelltypesandthedatatypeofthevalueinthecellthatiswrittentothedatamodel.
GraphicalCellType DataTypeWrittentoModel
Spread Windows Forms Developer’s Guide 316
Copyright © GrapeCity, Inc. All rights reserved.
BarCodeCellType('BarCodeCellTypeClass'intheon-linedocumentation)
Valueofbarcode
ButtonCellType('ButtonCellTypeClass'intheon-linedocumentation)two-state
Integer
ButtonCellType('ButtonCellTypeClass'intheon-linedocumentation)one-state
Null
CheckBoxCellType('CheckBoxCellTypeClass'intheon-linedocumentation)three-state
Integer(0=false,1=true,2=indeterminate)
CheckBoxCellType('CheckBoxCellTypeClass'intheon-linedocumentation)two-state
Boolean
ColorPickerCellType('BarCodeCellTypeClass'intheon-linedocumentation)
Null
ComboBoxCellType('ComboBoxCellTypeClass'intheon-linedocumentation)andMultiColumnComboBoxCellType('MultiColumnComboBoxCellTypeClass'intheon-linedocumentation)
DependsonvalueofEditorValueproperty.String,ifEditorValue=Stringoritemdata.Integer,ifEditorValue=index
GcComboBoxCellType('GcComboBoxCellTypeClass'intheon-linedocumentation)
DependsonvalueofEditorValueproperty.String,ifEditorValue=Stringoritemdata.Integer,ifEditorValue=index
HyperLinkCellType('HyperLinkCellTypeClass'intheon-linedocumentation)
ArrayofBooleanvalues(whethereachlinkisclickedorunclicked)
ImageCellType('ImageCellTypeClass'intheon-linedocumentation)
System.Drawing.ColororNull
ListBoxCellType('ListBoxCellTypeClass'intheon-linedocumentation)
Array
MultiOptionCellType('MultiOptionCellTypeClass'intheon-linedocumentation)
DependsonvalueofEditorValueproperty.String,ifEditorValue=Stringoritemdata,Integer,ifEditorValue=index
ProgressCellType('ProgressCellTypeClass'intheon-linedocumentation)
Double
RichTextCellType('RichTextCellTypeClass'intheon-linedocumentation)
String
SliderCellType('SliderCellTypeClass'intheon-linedocumentation)
Integer
Working with Editable Cell Types
Youcanworkwiththeeditablecelltypesasdescribedinthefollowingtopics:
SettingaCurrencyCellSettingaDate-TimeCellSettingaGcCharMaskCell(on-linedocumentation)SettingaGcDateTimeCellSettingaGcMaskCell(on-linedocumentation)SettingaGcNumberCell
Spread Windows Forms Developer’s Guide 317
Copyright © GrapeCity, Inc. All rights reserved.
SettingaGcTextBoxCellSettingaGcTimeSpanCell(on-linedocumentation)SettingaGeneralCellSettingaMaskCellSettingaNumberCellSettingaPercentCellSettingaRegularExpressionCellSettingaTextCell
Forothercelltypes,refertoWorkingwithGraphicalCellTypes.
Setting a Currency Cell
Youcansetacelltodisplaycurrencyvaluesusingthecurrencycell.Acurrencycelldisplaysthenumericcurrencyvalueswithformattingthatyoucancustomizeincludingacurrencysymbol,aseparatorcharacter,andotherformatting.
YouusetheCurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation)classtosetthecurrencycellanditsproperties.
Bydefault,SpreadusestheregionalWindowssettings(oroptions)ofthemachineonwhichitrunsfortheformattingofcurrency.Youcancustomizeanyofthesecurrencyformattingproperties:
currencysymbol(andwhethertodisplayit)separatorcharacter(andwhethertodisplayit)decimalsymbolwhethertodisplayaleadingzeropositivevalueindicator(andwhethertodisplayit)negativevalueindicator(andwhethertodisplayit)
Bydefault,inacurrencycell,ifyoudouble-clickonthecellineditmodeatrun-time,apop-upcalculatorappears.Youcandeterminewhethertoallowthis,andyoucanspecifythetextthatdisplaysontheOKandCancelbuttons.Formoreinformation,refertoCustomizingthePop-UpCalculatorControl.
Youcanalsosettheminimumandmaximumvaluesthatcanbeenteredtoprovidevalidationoftheuserentry.Todefinethelimitsforvalues,refertoLimitingValuesforaNumericCell.
UsingSpinButtons
Bydefault,nospinbuttonsareshown,butyoucandisplayspinbuttonsonthesideofthecellwhenthecellisineditmode.YoucansetvariousspinfunctionsusingthepropertiesoftheCurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation)thatbeginwiththewordSpin.Formoreinformation,refertoDisplayingSpinButtons.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheCurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.
Spread Windows Forms Developer’s Guide 318
Copyright © GrapeCity, Inc. All rights reserved.
3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheCurrencycelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefineacurrencycellbycreatinganinstanceoftheCurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation)class.
2. SpecifytheformattingofacurrencycellbysettingtheCurrencySymbol('CurrencySymbolProperty'intheon-linedocumentation)andotherpropertiesfortheCurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation)object.
3. AssignthecurrencycelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,orstyletotheCurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplecreatesacurrencycell.
C#FarPoint.Win.Spread.CellType.CurrencyCellType currcell = new FarPoint.Win.Spread.CellType.CurrencyCellType();currcell.CurrencySymbol = "US$";currcell.DecimalSeparator = ":";currcell.DecimalPlaces = 8;fpSpread1.ActiveSheet.Cells[1,1].CellType = currcell;
VBDim currcell As New FarPoint.Win.Spread.CellType.CurrencyCellType()currcell.CurrencySymbol = "US$"currcell.DecimalSeparator = ":"currcell.DecimalPlaces = 8FpSpread1.ActiveSheet.Cells(1,1).CellType = currcell
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheCurrencycell
type.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectCurrency.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Date-Time Cell
Spread Windows Forms Developer’s Guide 319
Copyright © GrapeCity, Inc. All rights reserved.
Youcansetacelltodisplaydateandtimeandonlyallowuserinputsofdateandtimeusingthedate-timecell.Youdeterminetheformatofthedateandtimetodisplay.
YouusetheDateTimeCellType('DateTimeCellTypeClass'intheon-linedocumentation)classtosetthedate-timecellanditsproperties.
ThedefaultvaluesusetheRegionalSettingsorRegionalOptionsintheWindowsenvironment.Youcanspecifytheformatusingseveralproperties.Foracompletelistofdateandtimeformats,refertotheDateTimeFormat('DateTimeFormatEnumeration'intheon-linedocumentation)enumerationandtheDateTimeFormat('DateTimeFormatProperty'intheon-linedocumentation)property.Ifadatetimecelldisplaysdatesandtimesinlongdateandtimeformat,andthecurrentdateandtimeis"10/29/200211:10:01",theTextpropertyreturns"Tuesday,October29,200211:10:01AM"astheformatteddataofthecell.TheValuepropertyreturnsthedate-timeobjectofthatdateandtime.
Thedate-timecellalsohasanEditorValue('EditorValueProperty'intheon-linedocumentation)propertythatallowsyoutodeterminewhatiswrittentothedatamodel.
Bydefault,inadate-timecell,ifyoudouble-clickonthecellineditmodeatrun-time,apop-upcalendar(orclock)appears.Youcandeterminewhethertoallowthis,andyoucanspecifythetextthatdisplaysontheOKandCancelbuttons.Formoreinformation,refertoCustomizingthePop-UpDate-TimeControl.
SpreadusestheTimeDefault('TimeDefaultProperty'intheon-linedocumentation)propertytofillinthetimeportionthatisnotsetintothecell.Whenyouusethepopupcalendartosetthedateforthecell,thetimeissettomidnight.Ifyouwantadifferenttime,youwouldneedtousetheSubEditorClosedeventandchangethevalueinthecell.(Youcanalsocreateyourownsub-editortocreateaclockandcalendarformtopopupforthecell.)YoucanlookinISubEditorinterfaceformoreinformationonhowtoimplementthis.Asforthevalue,theValue('ValueProperty'intheon-linedocumentation)propertyreturnsisaDateTimeobjectthatencapsulatesboththedateandtime.QuerytheTimeOfDaypropertyfromthereturnedDateTimeobjecttogetthetimeofday.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheDateTimeCellType('DateTimeCellTypeClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheDateTimecelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. Definethedate-timecellbycreatinganinstanceoftheDateTimeCellType('DateTimeCellTypeClass'in
Spread Windows Forms Developer’s Guide 320
Copyright © GrapeCity, Inc. All rights reserved.
theon-linedocumentation)class.2. Specifythemessagetodisplayifinvalid.3. Specifytheformatofthedatetodisplay.4. Assignthedate-timecelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,
orstyletotheDateTimeCellType('DateTimeCellTypeClass'intheon-linedocumentation)object.
Example
DisplaythedateasTuesday,March04(dayofweek,monthandnumberofday)inthesecondrow,secondcolumncell.
C#FarPoint.Win.Spread.CellType.DateTimeCellType datecell = new FarPoint.Win.Spread.CellType.DateTimeCellType();datecell.DateSeparator = " | ";datecell.TimeSeparator = ".";datecell.DateTimeFormat = FarPoint.Win.Spread.CellType.DateTimeFormat.ShortDateWithTime;datecell.MaximumDate = new System.DateTime(2100, 1, 1);datecell.MinimumDate = new System.DateTime(1990, 12, 31);datecell.MaximumTime = new System.TimeSpan(15, 59, 59);datecell.MinimumTime = new System.TimeSpan(11, 0, 0);fpSpread1.ActiveSheet.Columns[1].Width = 175;fpSpread1.ActiveSheet.Cells[1, 1].CellType = datecell;fpSpread1.ActiveSheet.Cells[1, 1].Value = System.DateTime.Now;
VBDim datecell As New FarPoint.Win.Spread.CellType.DateTimeCellType()datecell.DateSeparator = " | "datecell.TimeSeparator = "."datecell.DateTimeFormat = FarPoint.Win.Spread.CellType.DateTimeFormat.ShortDateWithTimedatecell.MaximumDate = new System.DateTime(2100, 1, 1)datecell.MinimumDate = new System.DateTime(1990, 12, 31)datecell.MaximumTime = new System.TimeSpan(15, 59, 59)datecell.MinimumTime = new System.TimeSpan(11, 0, 0)fpSpread1.ActiveSheet.Columns(1).Width = 175FpSpread1.ActiveSheet.Cells(1, 1).CellType = datecellFpSpread1.ActiveSheet.Cells(1, 1).Value = System.DateTime.Now
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheDateTimecell
type.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectDateTime.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a GcDateTime Cell
YoucanusetheGcDateTimecelltodisplaydateandtimevalues.TheGcDateTimecellallowstheusertopickadatefromacalendardrop-downortypeinthecell.ThiscellispartoftheGrapeCity.Win.PluginInputManassembly.
Spread Windows Forms Developer’s Guide 321
Copyright © GrapeCity, Inc. All rights reserved.
TheGcDateTimecellsupportsdifferentcalendarstylesfromtheDateTimecell.YoucanspecifywhichfieldstodisplaywiththeDisplayFields('DisplayFieldsProperty'intheon-linedocumentation)property.
YoucanspecifythefocuspositionwhenthecellgetsfocuswiththeFocusPosition('FocusPositionProperty'intheon-linedocumentation)propertyandyoucanspecifywhetherfocusleavesthecellaftertypingthelastcharacterinthedatevaluewiththeExitOnLastChar('ExitOnLastCharProperty'intheon-linedocumentation)property.
YoucanusetheShortcutKeys('ShortcutKeysProperty'intheon-linedocumentation)propertytomapkeystoactionsfortheGcDateTimeandGcTextBoxcells.Ineditmode,theseshortcutkeyshaveprecedenceovertheSpreadinputmaps.ThecellusestheSpreadinputmapswhennotineditmode.
Youcanspecifythetypeofdrop-downtodisplaywiththeDropDownType('DropDownTypeProperty'intheon-linedocumentation)property.Thedrop-downpickertypeiseasiertouseinatouchenvironment.
Foracompletelistofproperties,seetheGcDateTimeCellType('GcDateTimeCellTypeClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheGcDateTimecelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinethetextcellbycreatinganinstanceoftheGcDateTimeCellType('GcDateTimeCellTypeClass'intheon-linedocumentation)class.
2. Setpropertiesfortheclass.3. AssignthecelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,orstyleto
theGcDateTimeCellTypeobject.
Spread Windows Forms Developer’s Guide 322
Copyright © GrapeCity, Inc. All rights reserved.
Example
ThisexamplecreatesaGcDateTimecell.
C#GrapeCity.Win.Spread.InputMan.CellType.GcDateTimeCellType inputcell = newGrapeCity.Win.Spread.InputMan.CellType.GcDateTimeCellType();inputcell.EditMode = GrapeCity.Win.Spread.InputMan.CellType.EditMode.Overwrite;fpSpread1.Sheets[0].Cells[0, 0].CellType = inputcell;
VBDim inputcell As New GrapeCity.Win.Spread.InputMan.CellType.GcDateTimeCellTypeinputcell.EditMode = GrapeCity.Win.Spread.InputMan.CellType.EditMode.OverwriteFpSpread1.Sheets(0).Cells(0, 0).CellType = inputcell
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheTextcelltype.
NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectGcDateTime.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a GcNumber Cell
Youcancreateanumbercellthatdisplaysasidebuttonandcalculator.TheGcNumberCellType('GcNumberCellTypeClass'intheon-linedocumentation)cellispartoftheGrapeCity.Win.PluginInputManassembly.
Selectthesidebuttontodisplaythedrop-downcalculatorasshowninthefollowingimage.SelectOKtoclosethecalculator.
Youcanspecifywhethertodisplay0ifthecellvalueisnullwiththeAllowDeleteToNull('AllowDeleteToNullProperty'intheon-linedocumentation)property.
Youcandisplaythepop-upcalculatorusingtheCtrlkeyandtheadd,subtract,multiply,ordividekeyonthenumber
Spread Windows Forms Developer’s Guide 323
Copyright © GrapeCity, Inc. All rights reserved.
padwhilethecellisineditmode.PressEntertofinishthecalculationandacceptthevalue.Thefollowingimagedisplaysthepop-upcalculator.
Foracompletelistofproperties,seetheGcNumberCellType('GcNumberCellTypeClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheGcNumbercelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinethecellbycreatinganinstanceoftheGcNumberCellType('GcNumberCellTypeClass'intheon-linedocumentation)class.
2. Setpropertiesfortheclass.3. AssignthecelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,orstyleto
theGcNumberCellTypeobject.
Example
ThisexamplecreatesaGcNumbercell.
C#GrapeCity.Win.Spread.InputMan.CellType.GcNumberCellType ncell = newGrapeCity.Win.Spread.InputMan.CellType.GcNumberCellType();fpSpread1.Sheets[0].Cells[0, 0].CellType = ncell;
VBDim ncell As New GrapeCity.Win.Spread.InputMan.CellType.GcNumberCellType()FpSpread1.Sheets(0).Cells(0, 0).CellType = ncell
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheGcNumbercell
Spread Windows Forms Developer’s Guide 324
Copyright © GrapeCity, Inc. All rights reserved.
type.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectGcNumber.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a GcTextBox Cell
Youcancreateatextcellthatdisplaystextandallowsyoutospecifypatternsofallowedcharacters.TheGcTextBoxCellType('GcTextBoxCellTypeClass'intheon-linedocumentation)cellispartoftheGrapeCity.Win.PluginInputManassembly.
YoucanspecifyanautomaticcompletemodeandacustomsourcewiththeAutoCompleteMode('AutoCompleteModeProperty'intheon-linedocumentation)andAutoCompleteCustomSource('AutoCompleteCustomSourceProperty'intheon-linedocumentation)properties.YoucanalsospecifymaximumlimitsforthecellwiththeMaxLength('MaxLengthProperty'intheon-linedocumentation)property.
YoucanusetheShortcutKeys('ShortcutKeysProperty'intheon-linedocumentation)propertytomapkeystoactionsfortheGcDateTimeandGcTextBoxcells.Ineditmode,theseshortcutkeyshaveprecedenceovertheSpreadinputmaps.ThecellusestheSpreadinputmapswhennotineditmode.
TheFormatString('FormatStringProperty'intheon-linedocumentation)propertyallowsyoutospecifyspecificcharactersthatareallowedinthecell.ThefollowingSpreadDesignertabledisplaystheavailablecharacters.
Spread Windows Forms Developer’s Guide 325
Copyright © GrapeCity, Inc. All rights reserved.
Foracompletelistofproperties,seetheGcTextBoxCellType('GcTextBoxCellTypeClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheGcTextBoxcelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
Spread Windows Forms Developer’s Guide 326
Copyright © GrapeCity, Inc. All rights reserved.
1. DefinethetextcellbycreatinganinstanceoftheGcTextBoxCellType('GcTextBoxCellTypeClass'intheon-linedocumentation)class.
2. Setpropertiesfortheclass.3. AssignthecelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,orstyleto
theGcTextBoxCellTypeobject.
Example
ThisexamplecreatesaGcTextBoxcellandcutsCrLfcharactersincopied,cut,orpastedstrings.
C#GrapeCity.Win.Spread.InputMan.CellType.GcTextBoxCellType inputcell1 = newGrapeCity.Win.Spread.InputMan.CellType.GcTextBoxCellType();inputcell1.Multiline = true;inputcell1.AcceptsCrLf = GrapeCity.Win.Spread.InputMan.CellType.CrLfMode.Cut;fpSpread1.Sheets[0].Cells[1, 1].CellType = inputcell1;
VBDim inputcell1 As New GrapeCity.Win.Spread.InputMan.CellType.GcTextBoxCellTypeinputcell1.Multiline = Trueinputcell1.AcceptsCrLf = GrapeCity.Win.Spread.InputMan.CellType.CrLfMode.CutFpSpread1.Sheets(0).Cells(1, 1).CellType = inputcell1
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheTextcelltype.
NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectGcTextBox.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a General Cell
Thegeneralcellisthedefaultcelltypeforthecellsinthesheets.Unlessyouspecifyanothercelltype,thecomponentassignsthegeneralcelltypetothecells.Thegeneralcellcanbeusedasisforenteringtextornumberswhereformattingisnotcriticalorthetypeofdataisnottiedtoaspecificdatatype.Forspecificcelltypeswhereformattingisimportant,seetheCurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation),DateTimeCellType('DateTimeCellTypeClass'intheon-linedocumentation),NumberCellType('NumberCellTypeClass'intheon-linedocumentation),andPercentCellType('PercentCellTypeClass'intheon-linedocumentation)cells.
YouusetheGeneralCellType('GeneralCellTypeClass'intheon-linedocumentation)classtosetthegeneralcellanditsproperties.
Withthegeneralcellyoucanformatthedisplayedvaluesregardlessoftheuserinput.Thegeneralcelltypeincludesaformatterthattakesthedataenteredbytheuserandassignsitoneoftheknownformatsanddatatypes.Therefore,youneednotworryaboutsettingcelltypesbecausethegeneralcelltypehandlesinputsofmanykinds.
Theopennessofthegeneralcellcanberestrictedifyouwanttoallowtheusertoenterdatainanyacceptableformat,butwantittobeformattedanddisplayedinaspecificway.Toallowtheusertoenterdatainanyacceptableformatandformatanddisplaythedatainaspecificway,adjusttheformatterforthegeneralcelltype.Todothis,specifyaformat
Spread Windows Forms Developer’s Guide 327
Copyright © GrapeCity, Inc. All rights reserved.
stringforthegeneralcellandthegeneralformatterparsestheuser-entereddata,butwhenthedataisdisplayed,yourcustomformatisusedratherthantheformatusedbytheenduser.YoucanusetheFormatStringproperty.Hereisanexample:
VisualBasicDim gnrlcell As New FarPoint.Win.Spread.GeneralCellTypegnrlcell.FormatString = "#,###.00"FpSpread1.Sheets(0).Cells(1, 1).CellType = gnrlcell
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheGeneralCellType('GeneralCellTypeClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheGeneralcelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinethegeneralcellbycreatinganinstanceoftheGeneralCellType('GeneralCellTypeClass'intheon-linedocumentation)class.
2. Setpropertiesfortheclass.3. AssignthegeneralcelltypetoacellorrangeofcellsbysettingtheCellType('CellTypeProperty'intheon-linedocumentation)propertyforacell,column,row,orstyletotheGeneralCellType('GeneralCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplesetsacelltobeageneralcell.
C#FarPoint.Win.Spread.CellType.GeneralCellType gnrlcell = new FarPoint.Win.Spread.CellType.GeneralCellType();fpSpread1.ActiveSheet.Cells[1, 1].CellType = gnrlcell;
VBDim gnrlcell As New FarPoint.Win.Spread.CellType.GeneralCellType()FpSpread1.ActiveSheet.Cells(1, 1).CellType = gnrlcell
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.
Spread Windows Forms Developer’s Guide 328
Copyright © GrapeCity, Inc. All rights reserved.
2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheGeneralcelltype.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectGeneral.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Mask Cell
Youcanuseamaskcellformaskingcharacterstolimituserentry.Youspecifywhichsubsetsofcharactersareallowedforeachiteminthemask.Youcandefinehowthemaskappears,withliteralsdisplayedexactlyastypedandplaceholdersshowingtheplacesforuserentry.Tocreateamask,settheMask('MaskProperty'intheon-linedocumentation)propertytoastringofmaskcharacters.Eachmaskcharacterrepresentsapositioninwhichtheusercantypeacharacter.
YouusetheMaskCellType('MaskCellTypeClass'intheon-linedocumentation)classtosetthemaskcellanditsproperties.
Foradetailedlistofthemaskcharacters,refertotheMask('MaskProperty'intheon-linedocumentation)propertyintheMaskCellType('MaskCellTypeClass'intheon-linedocumentation)class.Foradescriptionofhowtosettheplaceholdercharacter,refertotheMaskChar('MaskCharProperty'intheon-linedocumentation)property.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheMaskcelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinethemaskcellbycreatinganinstanceoftheMaskCellType('MaskCellTypeClass'intheon-linedocumentation)class.
2. Definethemask,includingliteralsandplaceholdersbysettingtheMask('MaskProperty'intheon-linedocumentation)property.
3. AssignthemaskcelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,orstyletotheMaskCellType('MaskCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplesetsacelltobeamaskcellandrestrictstheusertoenteringtwoalphabeticnamesandpromptsthemwith
Spread Windows Forms Developer’s Guide 329
Copyright © GrapeCity, Inc. All rights reserved.
X’s.Thedisplaylookslikethis:
->XXXXXXXX:XXXXXXXX<-
C#FarPoint.Win.Spread.CellType.MaskCellType maskcell = new FarPoint.Win.Spread.CellType.MaskCellType();maskcell.Mask = "-> ULLLLLLL : ULLLLLLL <-";maskcell.MaskChar = Convert.ToChar("X");fpSpread1.ActiveSheet.Cells[1, 1].CellType = maskcell;
VBDim maskcell As New FarPoint.Win.Spread.CellType.MaskCellType()maskcell.Mask = "-> ULLLLLLL : ULLLLLLL <-"maskcell.MaskChar = "X"FpSpread1.ActiveSheet.Cells(1, 1).CellType = maskcell
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheMaskcelltype.
NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectMask.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Number Cell
Youcanuseanumbercellforenteringdouble-precisionfloatingpointnumbersaswellasfractions.Youcandisplaydecimalnumbers,integers,orfractions.Thetopicsbelowdiscussthevariousaspectsofnumbercellformattingandcalculation.
YouusetheNumberCellType('NumberCellTypeClass'intheon-linedocumentation)classtosetthenumbercellanditsproperties.UsetheCurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation)classtosetthecurrencycellanditsproperties.
SettingPrecision
NumbersaretypicallycalculatedandstoredusingtheDoubledatatypewhichprovidesanaccuracyofabout15digits.Thecellcanbeformattedtodisplayasmanyorasfewdigitsasyouwant.Forexample,thefollowingcodewouldsumthevaluesinthecellrangeA1:A5andplacetheresultincellA6.ThevaluestoredincellA6wouldhavefullaccuracy(uptothelimitsoftheDoubledatatype),butthetextdisplayedincellA6wouldshowthevalueroundedtothenearesttenthsplace(onedecimalplace).
C#NumberCellType ct = new NumberCellType();ct.DecimalPlaces = 1;spread.Sheets[0].Cells[5,0].CellType = ct;spread.Sheets[0].Cells[5,0].Formula = "SUM(A1:A5)";
Numbercellssupports15significantdigitsofprecision.Thisisatotalofalldigits,integralandfractional.Forexample,whenyouhave10fractionaldigits,youlimitthenumberofintegerdigitstotheleftofthedecimalto5digits.Also,there
Spread Windows Forms Developer’s Guide 330
Copyright © GrapeCity, Inc. All rights reserved.
isthepossibilityoffloatingpointerrorswiththeDoubledatatype.Formoreaccurateprecisionoflargenumbersornumberswithlargefractionalportions,considerusingacurrencycellwhichusestheDecimaldatatypeandisnotpronetofloatingpointerrors.
FormattingNumbers
Youcancustomizethenumbercelltodisplaythenumberasanintegerordecimalwithseveralformattingfeaturesassummarizedinthistableofproperties.Anexampleoftheuseofthesepropertiesisprovidedafterthetable.
Property DescriptionDecimalPlaces('DecimalPlacesProperty'intheon-linedocumentation)
Setsthenumberofdecimalplacesinthedisplayofthenumber,foradecimalnumber.
DecimalSeparator('DecimalSeparatorProperty'intheon-linedocumentation)
Setsthedecimalcharacterforthedisplayofadecimalnumber.
FixedPoint('FixedPointProperty'intheon-linedocumentation)
Setswhethertodisplayzerosasplaceholdersinthedecimalportionofthenumberforafixed-pointnumericdisplay.
LeadingZero('LeadingZeroProperty'intheon-linedocumentation)
Setswhetherleadingzerosaredisplayed.
MaximumValue('MaximumValueProperty'intheon-linedocumentation)
Setsthemaximumvalueallowedforuserinput.
MinimumValue('MinimumValueProperty'intheon-linedocumentation)
Setstheminimumvalueallowedforuserinput.
NegativeFormat('NegativeFormatProperty'intheon-linedocumentation)
Setshowthevalueisformattedfornegativevalues.
NegativeRed('NegativeRedProperty'intheon-linedocumentation)
Setswhethernegativenumericvaluesaredisplayedinred.
OverflowCharacter('OverflowCharacterProperty'intheon-linedocumentation)
Setsthecharactertousetoreplacethevalueifitdoesnotfitthewidthofthedisplay.
Separator('SeparatorProperty'intheon-linedocumentation)
Setsthestringusedtoseparatethousandsinanumericvalue.
ShowSeparator('ShowSeparatorProperty'intheon-linedocumentation)
Setswhethertodisplaythethousandsseparatorstring.
AcompletelistofformattingpropertiescanbefoundintheNumberCellType('NumberCellTypeClass'intheon-linedocumentation)class.Youcanusecode,thePropertiesWindow,ortheSpreadDesignertosettheseproperties.
DisplayingFractions
Thenumbercellcandisplayvaluesinafractionformat,so0.01canbedisplayedas1/100.SettheFractionMode('FractionModeProperty'intheon-linedocumentation)propertyofthenumbercelltodisplayvaluesinthefractionformat.Youcantypevaluesinthecellas0.01oryoucantype1/100inthecell;bothdisplayas1/100.TheprecisionofthefractioncanbesetusingtheFractionDenominatorPrecision('FractionDenominatorPrecisionEnumeration'intheon-linedocumentation)enumeration(suchastodisplayfractionsasquarters,1/4,etc.)ortheFractionDenominatorDigits('FractionDenominatorDigitsProperty'intheon-linedocumentation)tosetthenumberofdigitsinthedenominator,for10s,100sor1000sormore.Thistableliststhefraction-relatedpropertiesofthenumbercell.
Property DescriptionFractionMode('FractionModeProperty'intheon-line
Setswhethervaluesarerepresentedasfractions.
Spread Windows Forms Developer’s Guide 331
Copyright © GrapeCity, Inc. All rights reserved.
documentation)
FractionConvertWholeNumbers('FractionConvertWholeNumbersProperty'intheon-linedocumentation)
Setswhethertoconvertwholenumberstofractionswhenvaluesaredisplayedasfractions.
FractionCustomFormat('FractionCustomFormatProperty'intheon-linedocumentation)
Setshowvaluesaredisplayedasfractionswithcustomformatting.Tousethecustomformat,settheFractionDenominatorPrecision('FractionDenominatorPrecisionProperty'intheon-linedocumentation)propertytoCustom.
FractionDenominatorDigits('FractionDenominatorDigitsProperty'intheon-linedocumentation)
Setsthenumberofdigitswhenvaluesaredisplayedasfractions.
FractionDenominatorPrecision('FractionDenominatorPrecisionProperty'intheon-linedocumentation)
Setstheprecisionwhenvaluesaredisplayedasfractions.
FractionRenderOnly('FractionRenderOnlyProperty'intheon-linedocumentation)
Setswhethertoallowfractionsineditmodewhenvaluesaredisplayedasfractions.
Anotherwaytosetthefractiondisplayistosetavalueforthefractioncustomformat(usingtheFractionCustomFormat('FractionCustomFormatProperty'intheon-linedocumentation)property).Thedefaultvalueis"#???/???"whichformatsthenumberasaninteger(#)followedbyathree-digitfraction(???/???).Thequestionmarksaftertheslashdeterminethenumberofdigitsofdenominatorprecisionofwhichtherecanbefromonetofifteen(because15-digitprecisionisthemaximum).Withthecustomformat,youcanalsospecifythedenominator,suchas"#???/100"or"#??/64".IfFractionConvertWholeNumbers('FractionConvertWholeNumbersProperty'intheon-linedocumentation)issettotrue,thenthereisnointegertodisplayandtheentirenumberisdisplayedasafraction.
Thealignmentofthedisplayisdeterminedbythealignmentpropertiesthataresetforthecell.Thenumberisnotalignedbasedonthefractiondisplay.(Intheexamplebelow,thenumbersarerightalignedregardlessofwhetherthereisafractionalpartornot.)
AcompletelistoffractionpropertiescanbefoundintheNumberCellType('NumberCellTypeClass'intheon-linedocumentation)class.Youcanusecode,thePropertiesWindow,ortheSpreadDesignertosettheseproperties.
UsingSpinButtons
Bydefault,nospinbuttonsareshown,butyoucandisplayspinbuttonsonthesideofthecellwhenthecellisineditmode.YoucansetvariousspinfunctionsusingthepropertiesoftheNumberCellType('NumberCellTypeClass'intheon-linedocumentation)classthatbeginwiththewordSpin.RefertoDisplayingSpinButtons.
UsingthePop-UpCalculator
Bydefault,inanumbercell,ifyoudouble-clickonthecellineditmodeatrun-time,apop-upcalculatorappears.YoucanspecifythetextthatdisplaysintheOKandCancelbuttons.Formoreinformation,refertoCustomizingthePop-UpCalculatorControl.Toprohibitthepoppingupofthecalculator,canceltheFpSpreadSubEditorOpening('SubEditorOpeningEvent'intheon-linedocumentation)event.HandlethiseventandsettheCancelargumentoftheSubEditorOpeningEventArgs('SubEditorOpeningEventArgsClass'intheon-linedocumentation)toTrue.
Formoreinformationonthepropertiesandmethodsofthenumbercelltype,refertotheNumberCellType('NumberCellTypeClass'intheon-linedocumentation)class.
Formoreinformationonthecurrencycelltype,refertotheSettingaCurrencyCell.
Spread Windows Forms Developer’s Guide 332
Copyright © GrapeCity, Inc. All rights reserved.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheNumbercelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCodeforFormattingNumbers
1. DefinethenumbercellbycreatinganinstanceoftheNumberCellType('NumberCellTypeClass'intheon-linedocumentation)class.
2. Setpropertiesfortheclass.3. AssignthenumbercelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,or
styletotheNumberCellType('NumberCellTypeClass'intheon-linedocumentation)object.
Example
ThisexamplesetsacelltobeanumericcellwithcertainformattingbyassigningtheNumberCellType('NumberCellTypeClass'intheon-linedocumentation)objectwithdefinedformattingproperties.
C#FarPoint.Win.Spread.CellType.NumberCellType nmbrcell = new FarPoint.Win.Spread.CellType.NumberCellType();nmbrcell.DecimalSeparator = ",";nmbrcell.DecimalPlaces = 5;nmbrcell.LeadingZero = FarPoint.Win.Spread.CellType.LeadingZero.UseRegional;nmbrcell.MaximumValue = 500.000;nmbrcell.MinimumValue = -10.000;fpSpread1.ActiveSheet.Cells[1, 1].CellType = nmbrcell;
VBDim nmbrcell As New FarPoint.Win.Spread.CellType.NumberCellType()nmbrcell.DecimalSeparator = ","nmbrcell.DecimalPlaces = 5nmbrcell.LeadingZero = FarPoint.Win.Spread.CellType.LeadingZero.UseRegionalnmbrcell.MaximumValue = 500.000nmbrcell.MinimumValue = -10.000FpSpread1.ActiveSheet.Cells(1, 1).CellType = nmbrcell
UsingCodeforFormattingFractions
1. DefinethenumbercellbycreatinganinstanceoftheNumberCellType('NumberCellTypeClass'intheon-linedocumentation)class.
2. SettheFractionModepropertytotrueandotherfractionpropertiesasneeded.
Spread Windows Forms Developer’s Guide 333
Copyright © GrapeCity, Inc. All rights reserved.
3. AssignthenumbercelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,orstyletotheNumberCellType('NumberCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplesetsacelltodisplaynumbersasfractions.
C#fpSpread1.ActiveSheet.Columns[0, 9].Width = 120;FarPoint.Win.Spread.CellType.NumberCellType frac = new FarPoint.Win.Spread.CellType.NumberCellType();frac.FractionMode = true;frac.FractionConvertWholeNumbers = false;frac.FractionDenominatorPrecision = FarPoint.Win.Spread.CellType.FractionDenominatorPrecision.Custom;frac.FractionCustomFormat = "## ???/???";frac.FractionDenominatorDigits = 3;fpSpread1.ActiveSheet.Columns[0].CellType = frac;fpSpread1.ActiveSheet.Columns[1].CellType = frac;fpSpread1.ActiveSheet.Cells[0, 0].Value = 5.00;fpSpread1.ActiveSheet.Cells[1, 0].Value = 5.01;fpSpread1.ActiveSheet.Cells[2, 0].Value = 5.02;fpSpread1.ActiveSheet.Cells[3, 0].Value = 5.03;fpSpread1.ActiveSheet.Cells[4, 0].Value = 5.04;fpSpread1.ActiveSheet.Cells[5, 0].Value = 5.05;fpSpread1.ActiveSheet.Cells[6, 0].Value = 5.06;fpSpread1.ActiveSheet.Cells[7, 0].Value = 5.07;fpSpread1.ActiveSheet.Cells[8, 0].Value = 5.08;fpSpread1.ActiveSheet.Cells[9, 0].Value = 5.09;fpSpread1.ActiveSheet.Cells[0, 1].Value = 25.000;fpSpread1.ActiveSheet.Cells[1, 1].Value = 25.011;fpSpread1.ActiveSheet.Cells[2, 1].Value = 25.021;fpSpread1.ActiveSheet.Cells[3, 1].Value = 25.031;fpSpread1.ActiveSheet.Cells[4, 1].Value = 25.041;fpSpread1.ActiveSheet.Cells[5, 1].Value = 25.051;fpSpread1.ActiveSheet.Cells[6, 1].Value = 25.061;fpSpread1.ActiveSheet.Cells[7, 1].Value = 25.071;fpSpread1.ActiveSheet.Cells[8, 1].Value = 25.081;fpSpread1.ActiveSheet.Cells[9, 1].Value = 25.091;
VBFpSpread1.ActiveSheet.Columns(0, 9).Width = 120Dim frac As New FarPoint.Win.Spread.CellType.NumberCellTypefrac.FractionMode = Truefrac.FractionConvertWholeNumbers = Falsefrac.FractionDenominatorPrecision = FarPoint.Win.Spread.CellType.FractionDenominatorPrecision.Customfrac.FractionCustomFormat = "# ???/???"frac.FractionDenominatorDigits = 3FpSpread1.ActiveSheet.Columns(0).CellType = fracFpSpread1.ActiveSheet.Columns(1).CellType = fracFpSpread1.ActiveSheet.Cells(0, 0).CellType = fracFpSpread1.ActiveSheet.Cells(0, 0).Value = 5.00FpSpread1.ActiveSheet.Cells(1, 0).Value = 5.01FpSpread1.ActiveSheet.Cells(2, 0).Value = 5.02
Spread Windows Forms Developer’s Guide 334
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.ActiveSheet.Cells(3, 0).Value = 5.03FpSpread1.ActiveSheet.Cells(4, 0).Value = 5.04FpSpread1.ActiveSheet.Cells(5, 0).Value = 5.05FpSpread1.ActiveSheet.Cells(6, 0).Value = 5.06FpSpread1.ActiveSheet.Cells(7, 0).Value = 5.07FpSpread1.ActiveSheet.Cells(8, 0).Value = 5.08FpSpread1.ActiveSheet.Cells(9, 0).Value = 5.09FpSpread1.ActiveSheet.Cells(0, 1).Value = 25.000FpSpread1.ActiveSheet.Cells(1, 1).Value = 25.011FpSpread1.ActiveSheet.Cells(2, 1).Value = 25.021FpSpread1.ActiveSheet.Cells(3, 1).Value = 25.031FpSpread1.ActiveSheet.Cells(4, 1).Value = 25.041FpSpread1.ActiveSheet.Cells(5, 1).Value = 25.051FpSpread1.ActiveSheet.Cells(6, 1).Value = 25.061FpSpread1.ActiveSheet.Cells(7, 1).Value = 25.071FpSpread1.ActiveSheet.Cells(8, 1).Value = 25.081FpSpread1.ActiveSheet.Cells(9, 1).Value = 25.091
ThisiswhattheresultlookslikeinSpread.
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheNumbercell
type.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Thefractionpropertiesareunderthefractiontab.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectNumber.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Percent Cell
Youcanuseapercentcellfordisplayingvaluesaspercentagesandrestrictinginputstopercentagenumericvalues.
YouusethePercentCellType('PercentCellTypeClass'intheon-linedocumentation)classtosetthepercentcellanditsproperties.
Spread Windows Forms Developer’s Guide 335
Copyright © GrapeCity, Inc. All rights reserved.
UsingSpinButtons
Bydefault,nospinbuttonsareshown,butyoucandisplayspinbuttonsonthesideofthecellwhenthecellisineditmode.YoucansetvariousspinfunctionsusingthepropertiesofthePercentCellType('PercentCellTypeClass'intheon-linedocumentation)classthatbeginwiththewordSpin.RefertoDisplayingSpinButtons.
UsingtheCalculator
Bydefault,inapercentcell,ifyoudouble-clickonthecellineditmodeatrun-time,apop-upcalculatorappears.Youcandeterminewhethertoallowthis,andyoucanspecifythetextthatdisplaysintheOKandCancelbuttons.Formoreinformation,refertoCustomizingthePop-UpCalculatorControl.Toprohibitthepoppingupofthecalculator,canceltheFpSpreadSubEditorOpening('SubEditorOpeningEvent'intheon-linedocumentation)event.HandlethiseventandsettheCancelargumentoftheSubEditorOpeningEventArgs('SubEditorOpeningEventArgsClass'intheon-linedocumentation)toTrue.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertothePercentCellType('PercentCellTypeClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosethePercentcelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinethepercentcellbycreatinganinstanceofthePercentCellType('PercentCellTypeClass'intheon-linedocumentation)class.
2. Setpropertiesfortheclass.3. AssignthepercentcelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,or
styletothePercentCellType('PercentCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplesetsacelltobeapercentcellanddisplaysanabbreviation(PRCNT)insteadofthepercentsign(%).
C#FarPoint.Win.Spread.CellType.PercentCellType prctcell = new FarPoint.Win.Spread.CellType.PercentCellType();prctcell.PercentSign = "PRCNT";prctcell.PositiveFormat = FarPoint.Win.Spread.CellType.PercentPositiveFormat.PercentBefore;fpSpread1.ActiveSheet.Cells[1, 1].CellType = prctcell;
VB
Spread Windows Forms Developer’s Guide 336
Copyright © GrapeCity, Inc. All rights reserved.
Dim prctcell As New FarPoint.Win.Spread.CellType.PercentCellType()prctcell.PercentSign = "PRCNT"prctcell.PositiveFormat = FarPoint.Win.Spread.CellType.PercentPositiveFormat.PercentBeforeFpSpread1.ActiveSheet.Cells(1, 1).CellType = prctcell
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosethePercentcell
type.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectPercent.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Regular Expression Cell
Youcancreatearegularexpressioncellthatrestrictsthedataenteredinthecelltovalidentriesdefinedinaregularexpression.Thedataisevaluatedwhenexitingthecell.InvaliddataisremovedandtheEditError('EditErrorEvent'intheon-linedocumentation)eventisraised.
YouusetheRegularExpressionCellType('RegularExpressionCellTypeClass'intheon-linedocumentation)classtosettheregularexpressioncellanditsproperties.
Forasummaryofregularexpressionsyntax,refertotheRegularExpressionSyntaxtopicintheMicrosoftNETFrameworkReference.Foranintroductiontoregularexpressions,refertotheIntroductiontoRegularExpressionstopicintheMicrosoft.NETFrameworkReference.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheRegularExpressioncelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinetheregularexpressioncellbycreatinganinstanceoftheRegularExpressionCellType('RegularExpressionCellTypeClass'intheon-linedocumentation)class.
2. Createaregularexpression.3. Createamessagetodisplaytotheuserwhentheexpressionisnotvalid.4. AssigntheregularexpressioncelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,
column,row,orstyletotheRegularExpressionCellType('RegularExpressionCellTypeClass'intheon-linedocumentation)object.
Spread Windows Forms Developer’s Guide 337
Copyright © GrapeCity, Inc. All rights reserved.
Example
Thisexamplecreatesaregularexpressioncell.
C#FarPoint.Win.Spread.CellType.RegularExpressionCellType regexcell = new FarPoint.Win.Spread.CellType.RegularExpressionCellType()regexcell.RegularExpression = "[0-9]{3}-[0-9]{2}-[0-9]{4}";fpSpread1.ActiveSheet.Cells[0, 0].CellType = regexcell;
VBDim regexcell As New FarPoint.Win.Spread.CellType.RegularExpressionCellType()regexcell.RegularExpression = "[0-9]{3}-[0-9]{2}-[0-9]{4}"FpSpread1.ActiveSheet.Cells(0, 0).CellType = regexcell
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheRegularExpressioncelltype.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectRegularExpression.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Text Cell
Youcancreateatextcellthatallowsonlytexttobedisplayedortreatsthecontentsofacellasonlytext.
Youcanalsospecifyifthetextshowsupasalllowercase,uppercase,ornormalwiththeCharacterCasing('CharacterCasingProperty'intheon-linedocumentation)property.TheCharacterSet('CharacterSetProperty'intheon-linedocumentation)propertyallowsyoutospecifynumbersonly,lettersonly,numbersandletters,oranyASCIIcharacters.
YouusetheTextCellType('TextCellTypeClass'intheon-linedocumentation)classtosetthetextcellanditsproperties.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheTextcelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
Spread Windows Forms Developer’s Guide 338
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
1. DefinethetextcellbycreatinganinstanceoftheTextCellType('TextCellTypeClass'intheon-linedocumentation)class.
2. Setpropertiesfortheclass.3. AssignthetextcelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,orstyle
totheTextCellType('TextCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplecreatesatextcellwithamaximumlength.
C#FarPoint.Win.Spread.CellType.TextCellType tcell = new FarPoint.Win.Spread.CellType.TextCellType();tcell.CharacterCasing = CharacterCasing.Upper;tcell.CharacterSet = FarPoint.Win.Spread.CellType.CharacterSet.Ascii;tcell.MaxLength = 30;tcell.Multiline = true;fpSpread1.ActiveSheet.Cells[0, 0].Text = "This is a text cell.";fpSpread1.ActiveSheet.Cells[0, 0].CellType = tcell;
VBDim tcell As New FarPoint.Win.Spread.CellType.TextCellType()tcell.CharacterCasing = CharacterCasing.Uppertcell.CharacterSet = FarPoint.Win.Spread.CellType.CharacterSet.Asciitcell.MaxLength = 40tcell.Multiline = TrueFpSpread1.ActiveSheet.Cells(0, 0).Text = "This is a text cell."FpSpread1.ActiveSheet.Cells(0, 0).CellType = tcell
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheTextcelltype.
NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectText.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Working with Graphical Cell Types
Youcanworkwiththegraphicalcelltypesasdescribedinthefollowingtopics:
SettingaBarcodeCellSettingaButtonCellSettingaCheckBoxCellSettingaColorPickerCellSettingaComboBoxCellSettingaGcComboBoxCell(on-linedocumentation)
Spread Windows Forms Developer’s Guide 339
Copyright © GrapeCity, Inc. All rights reserved.
SettingaHyperlinkCellSettinganImageCellSettingaListBoxCellSettingaMultiple-ColumnComboBoxCellSettingaMultipleOptionCellSettingaProgressIndicatorCellSettingaRichTextCellSettingaSliderCell
Thegraphicalcelltypesuseagraphicoracontrolorform.TheyarebasedontheBaseCellType('BaseCellTypeClass'intheon-linedocumentation)classandyoucandefineasubeditorforthem.
Forothercelltypes,refertoWorkingwithEditableCellTypes.
NotethatsomegraphicalelementsincertaincelltypesareaffectedbyXPthemes(visualstyles).SettingtheVisualStylespropertyoftheSpreadcomponentto"off"canallowvisualcustomizationsofthosegraphicalcelltypestoworkasexpected.Formoreinformation,refertoUsingXPThemeswiththeComponent.
Setting a Barcode Cell
Youcandisplayabarcodegraphicinabarcodecell.Variousbarcodetypesareavailablesuchasbarcodesthatareusedinretail,forshipping,andsoon.Youcansetheightandwidthpropertiesforthebarcodedisplay.
YouusetheBarCodeCellType('BarCodeCellTypeClass'intheon-linedocumentation)classtosetthebarcodecellanditsproperties.
CustomizingtheAppearance
Youcancustomizethebarcodecellbyusingtheseproperties:
Property DescriptionAcceptsCheckDigit('AcceptsCheckDigitProperty'intheon-linedocumentation)
Setswhethertoacceptthecheckdigitintheinput.
AdjustSize('AdjustSizeProperty'intheon-linedocumentation)
Setswhetherthebarcodeadjustsitssizebasedonthebarcodesize.
AutoStretch('AutoStretchProperty'intheon-linedocumentation)
Setswhetherthesizeisbasedonthecellsize.
BarAdjust('BarAdjustProperty'intheon-linedocumentation)
Setswhethertofinetunethewidthofthebarcode.
BarCodePadding('BarCodePaddingProperty'intheon-linedocumentation)
Setstheleftsideandrightsidepaddingofthebarcode.
BarSize('BarSizeProperty'intheon-line Setstheheightandwidthofthebarcode.
Spread Windows Forms Developer’s Guide 340
Copyright © GrapeCity, Inc. All rights reserved.
documentation)
DisplayCheckDigit('DisplayCheckDigitProperty'intheon-linedocumentation)
Setswhetherthecheckdigitisavailableforthebarcode.
DisplayMode('DisplayModeProperty'intheon-linedocumentation)
Setswhetherthebarcodedrawsabarcodeimage.
FixedLength('FixedLengthProperty'intheon-linedocumentation)
Setsthenumberofthefixeddigitsofthevalueofthebarcode.
IsFormulaValue('IsFormulaValueProperty'intheon-linedocumentation)
Determineswhethertheeditorcontainsaformula.
Message('MessageProperty'intheon-linedocumentation)
Setswhethertodisplaythecustommessagestringbelowthebarcodeimage(ifthebarcodetypeallowsit).
MessagePosition('MessagePositionProperty'intheon-linedocumentation)
Setsthealignmentofthecustommessagebelowthebarcodeimage.
MessageValue('MessageValueProperty'intheon-linedocumentation)
Setsacustommessagetodisplaybelowthebarcodeimage.
MinimumHeight('MinimumHeightProperty'intheon-linedocumentation)
Setstheminimumheightofentirebarcode.
ModuleSize('ModuleSizeProperty'intheon-linedocumentation)
Setsthesizeofthebarcodemodule.
Resolution('ResolutionProperty'intheon-linedocumentation)
Setstheresolutionofthebarcode.
Rotation('RotationProperty'intheon-linedocumentation)
Setstherotationangleofthebarcode.
Type('TypeProperty'intheon-linedocumentation)
Setsthebartypeofthebarcode.
Unit('UnitProperty'intheon-linedocumentation)
Setstheunitofmeasureofthebarcode.
TheFixedLength('FixedLengthProperty'intheon-linedocumentation)propertyonlyworkswithPostNet,ITF,orCode39barcodetypes.ThePostNetbarcodeoptionallowsonelessdigitforthevaluethanthesettingfortheFixedLengthproperty.
Onlythebarcodetypesthathavealineatthebottomtodisplaythevaluecandisplayamessage(assetbytheMessage('MessageProperty'intheon-linedocumentation),MessagePosition('MessagePositionProperty'intheon-linedocumentation),andMessageValue('MessageValueProperty'intheon-linedocumentation)properties).
BarcodeTypes
HereisasampleimageofeachofthesupportedbarcodetypesthatcanbesetwiththeType('TypeProperty'intheon-linedocumentation)property.TheJan8typeissimilartotheEAN8type.Formoreinformationaboutbarcodetypes,refertothisarticle:http://www.gs1.org/barcodes.
BarcodeType SampleBarcodeImageCode128
Spread Windows Forms Developer’s Guide 341
Copyright © GrapeCity, Inc. All rights reserved.
Code39
Code49
Code93
EAN128
ITF
Jan13
Jan8
JapanesePostal
Spread Windows Forms Developer’s Guide 342
Copyright © GrapeCity, Inc. All rights reserved.
NW7
PDF417
PostNet
QRCode
UPC
CustomizingtheMessage
Youcandisplayacustomizabletextmessageatthebottomofthebarcodecellforseveralbarcodetypes.Thisissupportedforthosebarcodetypesthatdisplaythenumbervaluebelowthebarcodeimage.(Forexample,PostNet,PDF417,JapanesePostal,andQRCodedonotdisplayamessage.)Intheexamplehere,thevaluehasbeenreplacedwithatextmessage.Thecodethatgeneratedthisbarcodeimageisshownbelow.Themessageissetusingtheseproperties:Message('MessageProperty'intheon-linedocumentation),MessagePosition('MessagePositionProperty'intheon-linedocumentation),andMessageValue('MessageValueProperty'intheon-linedocumentation).
C#FarPoint.Win.Spread.CellType.BarCodeCellType barc = new
Spread Windows Forms Developer’s Guide 343
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Spread.CellType.BarCodeCellType();barc.DisplayMode = FarPoint.Win.Spread.CellType.BarCodeDisplayMode.Image;barc.Message = true;barc.MessagePosition = FarPoint.Win.Spread.CellType.BarCode.MessagePosition.Left;barc.MessageValue = "Display This Instead of Value";barc.Type = new FarPoint.Win.Spread.CellType.BarCode.UPC();fpSpread1.ActiveSheet.Columns[0].Width = 220;fpSpread1.ActiveSheet.Rows[0].Height = 100;fpSpread1.ActiveSheet.Cells[0, 0].CellType = barc;fpSpread1.ActiveSheet.Cells[0, 0].Value = 36000280753;
VBDim barc As New FarPoint.Win.Spread.CellType.BarCodeCellTypebarc.DisplayMode = FarPoint.Win.Spread.CellType.BarCodeDisplayMode.Imagebarc.Message = Truebarc.MessagePosition = FarPoint.Win.Spread.CellType.BarCode.MessagePosition.Leftbarc.MessageValue = "Display This Instead of Value"barc.Type = New FarPoint.Win.Spread.CellType.BarCode.UPCFpSpread1.ActiveSheet.Columns(0).Width = 220FpSpread1.ActiveSheet.Rows(0).Height = 100FpSpread1.ActiveSheet.Cells(0, 0).CellType = barcFpSpread1.ActiveSheet.Cells(0, 0).Value = 36000280753
NotethatsomegraphicalelementsincertaincelltypesareaffectedbyXPthemes(visualstyles).SettingtheVisualStylespropertyoftheSpreadcomponentto"off"canallowvisualcustomizationsofthosegraphicalcelltypestoworkasexpected.Formoreinformation,refertoUsingXPThemeswiththeComponent.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheBarCodeCellType('BarCodeCellTypeClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheBarCodecelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinethebarcodecellbycreatinganinstanceoftheBarCodeCellType('BarCodeCellTypeClass'intheon-linedocumentation)class.
2. Specifythepropertiesofthebarcodecell.3. AssignthebarcodecelltoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,orstyle
totheBarCodeCellType('BarCodeCellTypeClass'intheon-linedocumentation)object.
Example
Spread Windows Forms Developer’s Guide 344
Copyright © GrapeCity, Inc. All rights reserved.
Thisexamplecreatesabarcodecell.
C#FarPoint.Win.Spread.CellType.BarCodeCellType brcdcell = new FarPoint.Win.Spread.CellType.BarCodeCellType();FpSpread1.Sheets[0].Cells[0, 0].CellType = brcdcell;FpSpread1.Sheets[0].Cells[0, 0].Value = "12345";
VBDim brcdcell As New FarPoint.Win.Spread.CellType.BarCodeCellTypeFpSpread1.Sheets(0).Cells(0, 0).CellType = brcdcellFpSpread1.Sheets(0).Cells(0, 0).Value = "12345"
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheBarCodecell
type.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectBarcode.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Button Cell
Youcandisplayabuttoninacellusingthebuttoncell.Abuttoncell,bydefaultdisplaysarectangularbuttonwithadefaultcolor;youcancustomizethetext,color,andanimageforthatbuttonaswellasspecifycertainaspectsofitsbehaviorwhenclicked.
Tocreateacellthatactslikeabutton,usetheButtonCellType('ButtonCellTypeClass'intheon-linedocumentation)classandthesettingsthataresummarizedhere.YoucancreateabuttoncellusingtheexamplesshowninthistopicorinthetopicsfortheindividualmembersoftheButtonCellType('ButtonCellTypeClass'intheon-linedocumentation)class.
CustomizingtheButtonAppearance
Buttoncellscandisplaytext,pictures,orboth.Iftheydisplaypictures,youcanchoosethatadifferentpictureisdisplayedwhenthebuttonispressed.Youcancustomizethecolorsinbuttoncells,includingthecoloroftheborder,text,andbackground.Inaddition,buttoncellscandisplayathree-dimensionalappearance,andyoucancustomizethecolorsofthehighlightandshadowintheappearance.Thefollowingpropertiesrelatetotheoverallappearanceofthebuttoncell.
Property DescriptionBackgroundStyle('BackgroundStyleProperty'intheon-linedocumentation)
Setshowthebackgroundisrendered.
ButtonColor('ButtonColor Setsthecolorofthebutton.
Spread Windows Forms Developer’s Guide 345
Copyright © GrapeCity, Inc. All rights reserved.
Property'intheon-linedocumentation)
ButtonColor2('ButtonColor2Property'intheon-linedocumentation)
Setsthesecondarycolorusedwhendrawingagradientbutton.
DarkColor('DarkColorProperty'intheon-linedocumentation)
Setsthecoloratthebottomandrightedgesofthebutton(thatgiveitthethree-dimensionalappearancealongwiththelightcolor).
GradientMode('GradientModeProperty'intheon-linedocumentation)
Setsthedrawingstyleofagradientbutton.
LightColor('LightColorProperty'intheon-linedocumentation)
Setsthecoloratthetopandleftedgesofthebutton(thatgiveitthethree-dimensionalappearancealongwiththedarkcolor).
Picture('PictureProperty'intheon-linedocumentation)
Setsanimagethatfillsthesurfaceofthebutton.AnyGDI+bitmapcanbeused,suchasaBMP,GIF,orJPGfile.Ifyouareusingatwo-statebutton,thisservesastheunpressedstate.
PictureDown('PictureDownProperty'intheon-linedocumentation)
Setsanimageforthepressedstateofthebutton.
ShadowSize('ShadowSizeProperty'intheon-linedocumentation)
Setsthethicknessoftheshadow,andthedarkandlightcolors(thatgiveitthethree-dimensionalappearance).
TwoState('TwoStateProperty'intheon-linedocumentation)
Setswhetherthebuttonfunctionsasatoggleswitchwithtwostates.Eachtimeyouclickthebutton,thebuttonchangesstate.
Bydefault,thebuttonhasasinglestate,andchangesitsappearanceonlyaslongasyouhavethepointeroveritwiththemousebuttonpressed.Forthissetting,buttoncellsbehavelikepushbuttons,whichyoucanpressbypressingyourleftmousebutton,andwhichdonotstaypressedwhenyoureleaseyourmousebutton.Alternatively,youcansetthebuttontobeatwo-statebuttonandthenthebuttontogglesbetweenthosetwostateswhenclicked.Thebuttonisclickedwhentheuserclicksanywhereinthatcell.Thebuttonstayspressedwhenyouclickitusingyourleftmousebutton.ButtonsareFalsewhentheyarenotpressed,andTruewhentheyarepressed.
CustomizingtheTextAppearance
Youcanspecifythetextthatisdisplayedinthebuttoncellandyoucanspecifytheappearanceofthattext.Youcan
Spread Windows Forms Developer’s Guide 346
Copyright © GrapeCity, Inc. All rights reserved.
specifythealignmentoftextalongsidepicturesinbuttoncellsaswellaswhethertowraptexttomultiplelines.
Thefollowingpropertiesrelatetothetextthatisdisplayedinthebuttoncell.
Property DescriptionHotkeyPrefix('HotkeyPrefixProperty'intheon-linedocumentation)
Setswhethertodisplaytheunderlinethatindicatestheaccesskey(keyboardshortcutorhotkey).
Text('TextProperty'intheon-linedocumentation)
Setsthetextthatappearsinthebutton.
TextAlign('TextAlignProperty'intheon-linedocumentation)
Setsthealignmentofthetextwithrespecttoapicture
TextColor('TextColorProperty'intheon-linedocumentation)
Setsthecolorofthetextinthebutton.
TextDown('TextDownProperty'intheon-linedocumentation)
Setsthetextofthebuttonwhenitispressed,ifitisatwo-statebutton.
TextOrientation('TextOrientationProperty'intheon-linedocumentation)
Setstheorientationofthetextinthebutton.Seethefollowingtablethatshowsexamplesofthevariousorientations.
WordWrap('WordWrapProperty'intheon-linedocumentation)
Setswhethertowrapthetexttomultiplelines.
HerearetheresultsofdifferentsettingsoftheTextOrientation('TextOrientationProperty'intheon-linedocumentation)property.
TextOrientation ExampleButton TextOrientation ExampleButtonTextHorizontal TextHorizontalFlipped
TextVertical TextVerticalFlipped
Spread Windows Forms Developer’s Guide 347
Copyright © GrapeCity, Inc. All rights reserved.
TextTopDown TextTopDownRTL
TextRotateCustom
Beyondthepropertiesofthebuttoncellitself,youcanalsosetapropertyintheFpSpread('FpSpreadClass'intheon-linedocumentation)classthataffectshowbuttonsbehave.TheFpSpread('FpSpreadClass'intheon-linedocumentation)classhasaButtonDrawMode('ButtonDrawModeProperty'intheon-linedocumentation)propertyforbuttoncellsandcomboboxcells.Thispropertyallowsyoutoalwaysshowabutton,orshowbuttonsinthecurrentcolumn,row,orcell.
NotethatsomegraphicalelementsincertaincelltypesareaffectedbyXPthemes(visualstyles).SettingtheVisualStyles('VisualStylesProperty'intheon-linedocumentation)propertyoftheSpreadcomponentto"off"canallowvisualcustomizationsofthosegraphicalcelltypestoworkasexpected.Formoreinformation,refertoUsingXPThemeswiththeComponent.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheButtonCellType('ButtonCellTypeClass'intheon-linedocumentation)class.
Formoreinformationonthecorrespondingeventwhenauserclicksonthebutton,refertotheFpSpread.ButtonClicked('ButtonClickedEvent'intheon-linedocumentation)event.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheButtoncelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinethebuttoncellbycreatinganinstanceoftheButtonCellType('ButtonCellTypeClass'intheon-linedocumentation)class.
2. Specifythepropertiesofthebuttonbysettingthepropertiesofthatinstance,suchasText,TwoState,and
Spread Windows Forms Developer’s Guide 348
Copyright © GrapeCity, Inc. All rights reserved.
ButtonColor.3. AssignthebuttoncelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,or
styletotheButtonCellType('ButtonCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplecreatesabuttonwithtextinabluecoloredbutton.Itdefinesthetexttobedifferentwhenthemousepointerishelddown.Thisexamplecreatesthebuttonshowninthefirstpartofthistopic.
C#FarPoint.Win.Spread.CellType.ButtonCellType bttncell = new FarPoint.Win.Spread.CellType.ButtonCellType();bttncell.ButtonColor = Color.Cyan;bttncell.DarkColor = Color.DarkCyan;bttncell.LightColor = Color.AliceBlue;bttncell.TwoState = false;bttncell.Text = "Click and Hold";bttncell.TextDown = "...now let go.";bttncell.ShadowSize = 3;fpSpread1.Sheets[0].Cells[0,2].CellType = bttncell;fpSpread1.Sheets[0].SetColumnWidth(2,90);
VBDim bttncell As New FarPoint.Win.Spread.CellType.ButtonCellType()bttncell.ButtonColor = Color.Cyanbttncell.DarkColor = Color.DarkCyanbttncell.LightColor = Color.AliceBluebttncell.TwoState = Falsebttncell.Text = "Click and Hold"bttncell.TextDown = "...now let go."bttncell.ShadowSize = 3FpSpread1.Sheets(0).Cells(0,2).CellType = bttncellFpSpread1.Sheets(0).SetColumnWidth(2,90)
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheButtoncelltype.
NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectButton.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Check Box Cell
Youcandisplayacheckboxinacellusingthecheckboxcell.Acheckboxcellcandisplayasmallcheckboxthatcanhaveoneofthreestates(checked,unchecked,orgrayed)ortwostates(checkedorunchecked).Youcancustomizethecheckboxbysettingthetext,determiningtheoperationofthecheckbox,andsettingpicturesinplaceofthestandardcheckboxpictures.
Tocreateacellthatactslikeacheckbox,usetheCheckBoxCellType('CheckBoxCellTypeClass'intheon-linedocumentation)class.Createacheckboxcellusingtheprocedureandexampleshownbelow.
Spread Windows Forms Developer’s Guide 349
Copyright © GrapeCity, Inc. All rights reserved.
CustomizingText
Youcancustomizethecheckboxbyspecifyingtheimageforeachofthestates.Bydefault,thecheckboxhasonlytwostates,checkedorunchecked,sotouseallthreeyoumustsettheThreeState('ThreeStateProperty'intheon-linedocumentation)property.Inthefollowingtable,defaultappearancesareshownwithtextdefinedusingtheTextTrue('TextTrueProperty'intheon-linedocumentation),TextFalse('TextFalseProperty'intheon-linedocumentation),andTextIndeterminate('TextIndeterminateProperty'intheon-linedocumentation)properties.Clickinganywhereinthecellchangesthecheckboxstate.
StateAppearance DescriptionTrue(checked)
Indeterminate(grayed)
False(unchecked)
Youcancustomizethecheckboxcellwiththeseproperties:
Property DescriptionCaption('CaptionProperty'intheon-linedocumentation)
Setsthetextinthecheckboxregardlessofthestate,overridingTextTrue('TextTrueProperty'intheon-linedocumentation),TextFalse('TextFalseProperty'intheon-linedocumentation),andTextIndeterminate('TextIndeterminateProperty'intheon-linedocumentation)textsettings.
HotkeyPrefix('HotkeyPrefixProperty'intheon-linedocumentation)
Setswhethertheampersandcharacterunderlinestextandcreatesanaccesskey.
TextAlign('TextAlignProperty'intheon-linedocumentation)
Setshowthetextisalignedinthecellwithrespecttothecheckboxgraphic.
TextFalse('TextFalseProperty'intheon-linedocumentation)
Setsthetextforthefalsestateofthecheckbox.
TextIndeterminate('TextIndeterminateProperty'intheon-linedocumentation)
Setsthetextfortheindeterminatestateofthecheckbox.
TextTrue('TextTrueProperty'intheon-linedocumentation)
Setsthetextforthetruestateofthecheckbox.
CustomizingPictures
Foreachstate,youcanalsosetcustompicturesforeachstateofthecheckboxcell(makingitappearmorelikeabutton).Youcandeterminetheappearanceofthecheckboxaccordingtowhetherthecellhasfocus(normal),doesnothavefocus(disabled),orisbeingclicked(pressed).
Property DescriptionBackgroundImage('BackgroundImageProperty'intheon-linedocumentation)
Setsthebackgroundimageforthecell.
Spread Windows Forms Developer’s Guide 350
Copyright © GrapeCity, Inc. All rights reserved.
Picture('PictureProperty'intheon-linedocumentation) Setstheimagestouseforthestatesofthecheckbox.
ThreeState('ThreeStateProperty'intheon-linedocumentation)
Setswhetherthecheckboxhasthreestates
NotethatsomegraphicalelementsincertaincelltypesareaffectedbyXPthemes(visualstyles).SettingtheVisualStyles('VisualStylesProperty'intheon-linedocumentation)propertyoftheSpreadcomponentto"off"canallowvisualcustomizationsofthosegraphicalcelltypestoworkasexpected.Formoreinformation,refertoUsingXPThemeswiththeComponent.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheCheckBoxCellType('CheckBoxCellTypeClass'intheon-linedocumentation)class.
Formoreinformationonthecorrespondingeventwhenauserclicksonthecheckbox,refertotheFpSpread.ButtonClicked('ButtonClickedEvent'intheon-linedocumentation)event.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheCheckBoxcelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinethecheckboxcellbycreatinganinstanceoftheCheckBoxCellType('CheckBoxCellTypeClass'intheon-linedocumentation)class.
2. Specifythepropertiesofthecheckboxcell,suchassettingthecheckboxtoshowthreestatesusingtheThreeState('ThreeStateProperty'intheon-linedocumentation)propertyforthatCheckBoxCellType('CheckBoxCellTypeClass'intheon-linedocumentation)object.
3. Enterthetextthatgoesalongwitheachcheckbox,usingtheTextTrue('TextTrueProperty'intheon-linedocumentation),TextFalse('TextFalseProperty'intheon-linedocumentation),andTextIndeterminate('TextIndeterminateProperty'intheon-linedocumentation)properties.
4. Specifythelocationoftheimagesforthecheckedanduncheckedboxesifyoudonotwanttousethedefaults,usingthePicture('PictureProperty'intheon-linedocumentation)property.(Thisisnotdoneinthefollowingexample.)
5. AssignthecheckboxcelltypetoacellorrangeofcellsbysettingtheCellType('CellTypeProperty'intheon-linedocumentation)propertyforacell,column,row,orstyletotheCheckBoxCellType('CheckBoxCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplecreatesacheckboxcell.
C#FarPoint.Win.Spread.CellType.CheckBoxCellType ckbxcell = new
Spread Windows Forms Developer’s Guide 351
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Spread.CellType.CheckBoxCellType();ckbxcell.ThreeState = true;ckbxcell.TextTrue ="Checked";ckbxcell.TextFalse ="Unchecked";ckbxcell.TextIndeterminate ="Not Sure";fpSpread1.ActiveSheet.Cells[0, 0].CellType = ckbxcell;
VBDim ckbxcell As New FarPoint.Win.Spread.CellType.CheckBoxCellType()ckbxcell.ThreeState = trueckbxcell.TextTrue ="Checked"ckbxcell.TextFalse ="Unchecked"ckbxcell.TextIndeterminate ="Not Sure"FpSpread1.ActiveSheet.Cells(0, 0).CellType = ckbxcell
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheCheckBoxcell
type.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectCheckBox.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Color Picker Cell
Youcanallowyourendusertoselectacolorfromacolorpickerusingthecolorpickercell.Acolorpickercelldisplaysadialogforselectingacolor.Thereareseveraloptionsforthecolordialog.
Whenacolorpickercellisselecteditdisplaysasinglecolor,whichcanappeareitherinabox,asshowninthefollowingimage,orfillingtheentireareaofthecell.Optionallytextcanbedisplayed.
Whenthecellisdouble-clicked,eitherthedrop-downcolorpickerisdisplayedorthepop-upcolordialogisdisplayed.Thereareseveraloptionsforthedisplayofthecolordialog.Thefollowingfigureshowsthepop-upcolordialog:
Spread Windows Forms Developer’s Guide 352
Copyright © GrapeCity, Inc. All rights reserved.
Thefollowingfigureshowsthedrop-downcolorpicker:
Tocreateacolorpickercell,usetheColorPickerCellType('BarCodeCellTypeClass'intheon-linedocumentation)class.Createacolorpickercellusingtheprocedureandexampleshownbelow.
CustomizingtheColorCell
TheoptionsforthecolorpickercellareintheColorPickerStyle('ColorPickerStyleEnumeration'intheon-linedocumentation)enumeration.
Spread Windows Forms Developer’s Guide 353
Copyright © GrapeCity, Inc. All rights reserved.
CustomizingtheColorDialog
Thecolorpickercellallowsthesecustomizationsofthecolordialog.
Property DescriptionAllowFullOpen('AllowFullOpenProperty'intheon-linedocumentation)
Setswhethertoallowthecolordialogtoopenfullytoshowthecustomcolorselector.
AnyColor('AnyColorProperty'intheon-linedocumentation)
Setswhetherthecolordialogdisplaysallavailablecolorsinthesetofbasiccolors.
Caption('CaptionProperty'intheon-linedocumentation)
Setsthetextthatappearsinthecell(ifany).
CustomColors('CustomColorsProperty'intheon-linedocumentation)
Setsthecustomcolorsshowninthecolordialog.
DialogShowing('DialogShowingProperty'intheon-linedocumentation)
Setswhethertodisplaythecolordialogautomatically.
DropDown('DropDownProperty'intheon-linedocumentation)
Setswhethertousethedrop-downcolorpicker(notthepop-upcolordialog).
FullOpen('FullOpenProperty'intheon-linedocumentation)
Setswhetherthecolordialogopensfullytoshowcontrolsusedtocreatecustomcolors.
SolidColorOnly('SolidColorOnlyProperty'intheon-linedocumentation)
Setswhetherthecolordialogrestrictsuserstoselectingsolidcolorsonly.
Style('StyleProperty'intheon-linedocumentation)
Setsthestyleofthecolordialog.
UnknownText('UnknownTextProperty'intheon-linedocumentation)
Setsthetextforanunknowncolor.
UnknownTextStyle('UnknownTextStyleProperty'intheon-linedocumentation)
Setsthestyleofthetextforanunknowncolor.
Thefollowingfigureillustratesthecolordialogwhenitissettofullyopen.
Spread Windows Forms Developer’s Guide 354
Copyright © GrapeCity, Inc. All rights reserved.
NotethatsomegraphicalelementsincertaincelltypesareaffectedbyXPthemes(visualstyles).SettingtheVisualStyles('VisualStylesProperty'intheon-linedocumentation)propertyoftheSpreadcomponentto"off"canallowvisualcustomizationsofthosegraphicalcelltypestoworkasexpected.Formoreinformation,refertoUsingXPThemeswiththeComponent.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheColorPickerCellType('BarCodeCellTypeClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheColorPickercelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinethecolorpickercellbycreatinganinstanceoftheColorPickerCellType('BarCodeCellTypeClass'intheon-linedocumentation)class.
Spread Windows Forms Developer’s Guide 355
Copyright © GrapeCity, Inc. All rights reserved.
2. Specifythepropertiesofthecolorpickercell.3. AssignthecolorpickercelltypetoacellorrangeofcellsbysettingtheCellType('CellTypeProperty'intheon-linedocumentation)propertyforacell,column,row,orstyletotheColorPickerCellType('BarCodeCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplecreatesacolorpickercell.
C#FarPoint.Win.Spread.CellType.ColorPickerCellType cp = new FarPoint.Win.Spread.CellType.ColorPickerCellType();cp.AllowFullOpen = true;cp.AnyColor = false;cp.CustomColors = new int[] {255, 190, 50};cp.FullOpen = true;cp.Style = FarPoint.Win.Spread.CellType.ColorPickerStyle.BoxedWithText;FarPoint.Win.Spread.CellType.ColorPickerCellType c = new FarPoint.Win.Spread.CellType.ColorPickerCellType(cp);FpSpread1.ActiveSheet.Cells[0, 0].CellType = c;
VBDim cp As New FarPoint.Win.Spread.CellType.ColorPickerCellTypecp.AllowFullOpen = Truecp.AnyColor = Falsecp.CustomColors = New Integer() {255, 190, 50}cp.FullOpen = Truecp.Style = FarPoint.Win.Spread.CellType.ColorPickerStyle.BoxedWithTextDim c As New FarPoint.Win.Spread.CellType.ColorPickerCellType(cp)FpSpread1.ActiveSheet.Cells(0, 0).CellType = c
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheColorPicker
celltype.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectColorPicker.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Combo Box Cell
Youcanuseacomboboxcelltodisplayaneditabledrop-downlist,allowingtheusertotypeinvaluesaswellaschoosingfromadisplayedlist.Youcanspecifythelistofitems,whethertoincludeiconstoappearalongwithtext,thenumberofitemsthataredisplayedatanytime,andwhetherthecelliseditablebytheuser.
Textonly Textandicon
Spread Windows Forms Developer’s Guide 356
Copyright © GrapeCity, Inc. All rights reserved.
Tocreateacellthatactslikeacombobox,usetheComboBoxCellType('ComboBoxCellTypeClass'intheon-linedocumentation)class.Createacomboboxcellusingthefollowingprocedure.
CustomizingtheListAppearance
Usethefollowingappearancepropertiestocustomizethecombobox.
Property DescriptionBackgroundImage('BackgroundImageProperty'intheon-linedocumentation)
Setsanimagetopaintinthebackgroundoftheeditportionofthecombobox.
ButtonAlign('ButtonAlignProperty'intheon-linedocumentation)
Setswherebuttonsaredisplayed.
ImageList('ImageListProperty'intheon-linedocumentation)
Setsanimagelistfordisplayingiconsalongwithtextinthedrop-downlistinthecombobox.
ItemData('ItemDataProperty'intheon-linedocumentation)
Setsitemdata,whichisdifferentfromtheitemsthataredisplayed,forthedrop-downlistinthecombobox.
Items('ItemsProperty'intheon-linedocumentation)
Setsitemsforthedrop-downlistinthecombobox.
ListAlignment('ListAlignmentProperty'intheon-linedocumentation)
Setsthesideofthecellonwhichthelistaligns.
ListOffset('ListOffsetProperty'intheon-linedocumentation)
Setshowmanypixelstooffsetthelistfromthealignededgeofthecell.
ListWidth('ListWidthProperty'intheon-linedocumentation)
Setsthewidth(inpixels)ofthedrop-downlist.
MaxDrop('MaxDropProperty'intheon-linedocumentation)
Setsthenumberofitemstodisplayatonetimeinthelistportion.Iftherearemoreitemsthanaredisplayed,averticalscrollbarisdisplayed.
MaxLength('MaxLengthProperty'intheon-linedocumentation)
Setsthemaximumnumberofcharactersallowedinthecomboboxcell.
CustomizingtheListOperation
Usethefollowingoperationpropertiestocustomizethecombobox.
Property DescriptionAcceptsArrowKeys('AcceptsArrowKeysProperty'intheon-linedocumentation)
Setshowarrowkeysareprocessedbythecomboboxcontrol.
AutoSearch('AutoSearchProperty'intheon-linedocumentation)
Setshowalistofitemsinacomboboxissearchedbasedoninputofacharacterkey.
CharacterCasing('CharacterCasingProperty'in Setsthecaseofcharactersinthetextcell.
Spread Windows Forms Developer’s Guide 357
Copyright © GrapeCity, Inc. All rights reserved.
theon-linedocumentation)
CharacterSet('CharacterSetProperty'intheon-linedocumentation)
Setswhatcharacterstoallowforthetextcell.
Editable('EditableProperty'intheon-linedocumentation)
Setswhetheryoucantypeintotheeditportionofthecombobox.
EditorValue('EditorValueProperty'intheon-linedocumentation)
Setswhatvalueiswrittentotheunderlyingdatamodel.
ListControl('ListControlProperty'intheon-linedocumentation)
Setsthecontroltouseforthelistportionifyoudonotwanttousethebuilt-inlistcontrolinSpread.
TheSpreadcontrolhasaButtonDrawMode('ButtonDrawModeProperty'intheon-linedocumentation)propertyforbuttoncellsandcomboboxcells.Thispropertyallowsyoutoalwaysshowabutton,orshowbuttonsinthecurrentcolumn,row,orcell.
CustomizingAutomaticCompletion
Usethefollowingpropertiestocustomizetheautomaticcompletionfeatureincomboboxcellswhenusingthe2005buildofthecomponent.
Property DescriptionAutoCompleteCustomSource('AutoCompleteCustomSourceProperty'intheon-linedocumentation)
Setthecustomsource(strings)forautomaticcompletionofentriesinthecombobox.
AutoCompleteMode('AutoCompleteModeProperty'intheon-linedocumentation)
Setthemodeforautomaticcompletionofentriesinthecombobox.
AutoCompleteSource('AutoCompleteSourceProperty'intheon-linedocumentation)
Setthesourceforautomaticcompletionofentriesinthecombobox.
NotethatsomegraphicalelementsincertaincelltypesareaffectedbyXPthemes(visualstyles).SettingtheVisualStyles('VisualStylesProperty'intheon-linedocumentation)propertyoftheSpreadcomponentto"off"canallowvisualcustomizationsofthosegraphicalcelltypestoworkasexpected.Formoreinformation,refertoUsingXPThemeswiththeComponent.
Todisplayatexttipoveracomboboxcell,seethenoteinDisplayingTextTipsinaCell.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheComboBoxCellType('ComboBoxCellTypeClass'intheon-linedocumentation)class.Forinformationonthemultiple-columncombobox,refertoSettingaMultiple-ColumnComboBoxCell.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheComboBoxcelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
Spread Windows Forms Developer’s Guide 358
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
1. DefineacomboboxcellbycreatinganinstanceoftheComboBoxCellType('ComboBoxCellTypeClass'intheon-linedocumentation)class.
2. Specifytheitemsinthelistthatappearaspartofthecombobox.YoucaneitherusetheItemspropertyoftheComboBoxCellType('ComboBoxCellTypeClass'intheon-linedocumentation)classordefineastringandpassthatinwhencreatingtheinstanceoftheclass.
3. Specifyhowthelistofitemsappears.Forexample,settheMaxDrop('MaxDropProperty'intheon-linedocumentation)propertytosetthemaximumnumberofitemstodisplayatatime.Iftherearemoreitems,ascrollbarappears.Youcanalsosetthehorizontalalignmentofthecheckboxwithrespecttothecell.
4. AssignthecomboboxcelltypetoacellorrangeofcellsbysettingtheCellType('CellTypeProperty'intheon-linedocumentation)propertyforacell,column,row,orstyletotheComboBoxCellType('ComboBoxCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplecreatesacombocell.
C#FarPoint.Win.Spread.CellType.ComboBoxCellType cmbocell = new FarPoint.Win.Spread.CellType.ComboBoxCellType();cmbocell.Items = (new String[] {"January", "February", "March", "April", "May", "June"});cmbocell.AutoSearch = FarPoint.Win.AutoSearch.SingleCharacter;cmbocell.Editable = true;cmbocell.MaxDrop = 4;fpSpread1.ActiveSheet.Cells[0, 0].CellType = cmbocell;
VBDim cbstr As string( )cbstr = new String() {"Jan", "Feb", "Mar", "Apr", "May", "Jun"}Dim cmbocell As New FarPoint.Win.Spread.CellType.ComboBoxCellType()cmbocell.Items = cbstrcmbocell.AutoSearch = FarPoint.Win.AutoSearch.SingleCharactercmbocell.Editable = Truecmbocell.MaxDrop = 4FpSpread1.ActiveSheet.Cells(0, 0).CellType = cmbocell
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheComboBoxcell
type.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectComboBox.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Hyperlink Cell
Youcanuseahyperlinkcelltocontaintextthatfunctionsasasinglehyperlinkormultiplehyperlinks.Thedestinationof
Spread Windows Forms Developer’s Guide 359
Copyright © GrapeCity, Inc. All rights reserved.
thehyperlinkcanbeanyuniversalresourcelocator(URL).Forexample:
http://www.grapecity.comwww.help.grapecity.com/spread/SpreadNet10/WF/webframe.html#spwin-welcome.htmlmailto:[email protected]?Subject=Spread
CustomizingLinks
Youcanspecifyhowmuchofthetextfunctionsasahyperlinkandtherestdisplaysasordinarytext.Youcanspecifytheappearanceofthehyperlinkedtext,customizethecolorofthelinkthathasbeenfollowed(visitedorclicked)andwhethertousethetextforthehyperlinkfromtheDataModel.
Property CustomizationBackgroundImage('BackgroundImageProperty'intheon-linedocumentation)
Setsthebackgroundgraphicimage.
Link('LinkProperty'intheon-linedocumentation) SetsthedestinationURL.
LinkArea('LinkAreaProperty'intheon-linedocumentation)
Setstheareaofthetextthatisthehyperlink.
LinkAreas('LinkAreasProperty'intheon-linedocumentation)
Setstheareaofthetextthatisthehyperlink.
LinkColor('LinkColorProperty'intheon-linedocumentation)
Setsthecoloroflinks(beforetheyarefollowed).
Links('LinksProperty'intheon-linedocumentation) Setsthehyperlinks.
Text('TextProperty'intheon-linedocumentation) Setsthelabelofthehyperlink,thatis,whatappearsinthecell.
VisitedLinkColor('VisitedLinkColorProperty'intheon-linedocumentation)
Setsthecoloroffollowedlinks.
UseModelValueAsText('UseModelValueAsTextProperty'intheon-linedocumentation)
GetsavalueindicatingwhethertousethetextforthehyperlinkfromtheDataModel.
MakingLinksinText
Tocreateacellthatactslikeahyperlink,usetheHyperLinkCellType('HyperLinkCellTypeClass'intheon-linedocumentation)class.Createahyperlinkcellusingthefollowingprocedure.Theresultsoftheprocedure,bothnormalandfollowedlinks,areshowninthefollowingfigure.
HyperlinkTextBeforeClickingLink HyperlinkTextAfterFollowingLink
Thefollowingfiguredisplaysahyperlinkcellwithmultiplelinks.
Spread Windows Forms Developer’s Guide 360
Copyright © GrapeCity, Inc. All rights reserved.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheHyperLinkCellType('HyperLinkCellTypeClass'intheon-linedocumentation)class.
Formoreinformationonthecorrespondingeventwhenauserclicksonahyperlink,refertotheFpSpread.ButtonClicked('ButtonClickedEvent'intheon-linedocumentation)event.
SortingandFilteringHyperlinksbyText
Aftercreatinghyperlinks,youcanalsoperformsortingandfilteringoperationsonthembytextvalues.
Todothis,youcanusetheUseModelValueAsText('UseModelValueAsTextProperty'intheon-linedocumentation)property.Bydefault,thevalueofthispropertyisabooleanfalse.Whenthispropertyissettotrue,itfetchesthetextvaluefromtheDataModelandsetsthisvalueinthecellofHyperlinkCellType.Thetextvalues(fetchedfromtheDataModel)enteredinthecellscanlaterbesortedandfilteredasandwhendesired,likeothercelltypes.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheHyperLinkcelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinethehyperlinkcellbycreatinganinstanceoftheHyperLinkCellType('HyperLinkCellTypeClass'intheon-linedocumentation)class.
2. Besuretosetthesizeofthecellsothatallthetextincludingthehyperlinkarevisibleanddisplayproperly.3. SpecifythetextthatappearsinthecellbyspecifyingtheText('TextProperty'intheon-linedocumentation)propertyfortheHyperLinkCellType('HyperLinkCellTypeClass'intheon-linedocumentation)object.SpecifyhowmuchofthetextishyperlinkusingtheLinkArea('LinkAreaProperty'intheon-linedocumentation)propertyforthatobject.
4. Specifytheappearanceofthehyperlinkbysettingproperties,suchasLinkColor('LinkColorProperty'intheon-linedocumentation).
5. AssignthehyperlinkcelltypetoacellorrangeofcellsbysettingtheCellType('CellTypeProperty'intheon-linedocumentation)propertyforacell,column,row,orstyletotheHyperLinkCellType('HyperLinkCellTypeClass'intheon-linedocumentation)object.
6. Ifyouwanttoperformsort/filteroperationsonthehyperlinkcell,settheUseModelValueAsText('UseModelValueAsTextProperty'intheon-linedocumentation)propertytotrueinordertoindicatethatthetextforthehyperlinkmustbeusedfromthedatamodel.
Example
Thisexamplecodesetsthesizeofthecell(bycolumnandrow),createsahyperlinkbutton,andspecifiesthedestinationURL.
Also,itshowshowtousetheUseModelValueAsTextpropertytoindicatethatthetextvalueforthehyperlinkmustbefetchedfromtheDataModel.
Spread Windows Forms Developer’s Guide 361
Copyright © GrapeCity, Inc. All rights reserved.
C#fpSpread1.ActiveSheet.Columns[1].Width = 145;fpSpread1.ActiveSheet.Rows[1].Height = 45;FarPoint.Win.Spread.CellType.HyperLinkCellType hlnkcell = new FarPoint.Win.Spread.CellType.HyperLinkCellType();hlnkcell.Text ="Click to See Our Web Site";hlnkcell.Link ="http://www.grapecity.com";hlnkcell.LinkArea = new LinkArea(9,16);hlnkcell.LinkColor = Color.DarkGreen;hlnkcell.VisitedLinkColor = Color.Chartreuse;fpSpread1.ActiveSheet.Cells[1, 1].CellType = hlnkcell;// Set value in the Data ModelfpSpread1.ActiveSheet.SetValue(1,1,"Click to see our website");hlnkcell.UseModelValueAsText = true; // Indicates that text must be used from data model
VBFpSpread1.ActiveSheet.Columns(1).Width = 145FpSpread1.ActiveSheet.Rows(1).Height = 45Dim hlnkcell As New FarPoint.Win.Spread.CellType.HyperLinkCellType()hlnkcell.Text = "Click to See Our Web Site"hlnkcell.Link ="http://www.grapecity.com"hlnkcell.LinkArea = new LinkArea(9,16)hlnkcell.LinkColor = Color.DarkGreenhlnkcell.VisitedLinkColor = Color.ChartreuseFpSpread1.ActiveSheet.Cells(1, 1).CellType = hlnkcell' Set value in the Data ModelfpSpread1.ActiveSheet.SetValue(1, 1, "Click to see our website")' Indicates that text must be used from data modelhlnkcell.UseModelValueAsText = True
UsingCode
1. DefinethehyperlinkcellbycreatinganinstanceoftheHyperLinkCellType('HyperLinkCellTypeClass'intheon-linedocumentation)class.
2. Besuretosetthesizeofthecellsothatallthetextincludingthehyperlinkarevisibleanddisplayproperly.3. SpecifythetextthatappearsinthecellbyspecifyingtheText('TextProperty'intheon-linedocumentation)propertyfortheHyperLinkCellType('HyperLinkCellTypeClass'intheon-linedocumentation)object.SpecifyhowmuchofthetextishyperlinkusingtheLinkAreas('LinkAreasProperty'intheon-linedocumentation)propertyforthatobject.
4. Specifytheappearanceofthehyperlinkbysettingproperties,suchasLinkColor('LinkColorProperty'intheon-linedocumentation).
5. AssignthehyperlinkcelltypetoacellorrangeofcellsbysettingtheCellType('CellTypeProperty'intheon-linedocumentation)propertyforacell,column,row,orstyletotheHyperLinkCellType('HyperLinkCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplecreatesahyperlinkcellwithmultiplelinks.
C#fpSpread1.ActiveSheet.Columns[0].Width = 145;fpSpread1.ActiveSheet.Rows[0].Height = 45;
Spread Windows Forms Developer’s Guide 362
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Spread.CellType.HyperLinkCellType mhp = new FarPoint.Win.Spread.CellType.HyperLinkCellType();mhp.Text = "Google and Microsoft";string[] s = new string[]{"www.google.com", "www.microsoft.com"};mhp.Links = s;mhp.VisitedLinkColor = Color.Maroon;LinkArea[] la = new LinkArea[]{new LinkArea(0, 8), new LinkArea(13, 9)};mhp.LinkAreas = la;fpSpread1.ActiveSheet.Cells[0, 0].CellType = mhp;
VBFpSpread1.ActiveSheet.Columns(0).Width = 145FpSpread1.ActiveSheet.Rows(0).Height = 45Dim mhp As New FarPoint.Win.Spread.CellType.HyperLinkCellTypemhp.Text = "Google and Microsoft"Dim s() As String = New String() {"www.google.com", "www.microsoft.com"}mhp.Links = smhp.VisitedLinkColor = Color.MaroonDim la() As LinkArea = New LinkArea() {New LinkArea(0, 8), New LinkArea(13, 9)}mhp.LinkAreas = laFpSpread1.ActiveSheet.Cells(0, 0).CellType = mhp
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheHyperLinkcell
type.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectHyperLink.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.Ifyoucreatemultiplehyperlinksthenmakesurethetextissetaswell.Notethatifyouweretocreatethepreviouscodesampleinthedesignerthenthetextwouldneedtocontain23characterssincethesecondlinkstartsat13andcontinuesfor9characters.Thetextiszerobased.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting an Image Cell
Youcandisplayagraphicimageinacellusingtheimagecelltype.Animagecellshowsanimageasdata.Ifthedatatypeforaboundcolumnisabitarraythenthedefaultcelltypeforthatboundcolumnwouldbeanimagecelltype.
AnimageobjectcanbeassignedtotheValue('ValueProperty'intheon-linedocumentation)propertyofacell.Theimageorserializedimageobjectmustbeinthedatamodel.
Tocreateacellthatcontainsanimage,usetheImageCellType('ImageCellTypeClass'intheon-linedocumentation)class.Createanimagecellusingthefollowingprocedure.Theresultisshowninthisfigure.
Noticethatbothcellshaveamagentabackground,buttheonewiththeimageonlyshowsthemagentathroughthetransparentareasspecifiedbythetransparencycolorpropertyandthetransparencytoleranceproperty.Theimageis
Spread Windows Forms Developer’s Guide 363
Copyright © GrapeCity, Inc. All rights reserved.
mostlywhitesoblocksoutmostofthemagenta.Theletteringthatismoreblueisbeyondthetoleranceandsoisnottransparent.Whenyousetatransparencycolor,thebackgroundbehindthepictureshowsthroughintheareathatoriginallyhadthecoloryouspecify.Settingthetransparencytoleranceto255willcauseeverythingtobetransparentsoyoumaywishtouseavaluelessthan255.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheImageCellType('ImageCellTypeClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheImagecelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinetheimagecellbycreatinganinstanceoftheImageCellType('ImageCellTypeClass'intheon-linedocumentation)class.
2. Createtheimage.3. SpecifywhatappearsinthecellbysettingtheValue('ValueProperty'intheon-linedocumentation)
propertyfortheImageCellType('ImageCellTypeClass'intheon-linedocumentation)object.4. SpecifytheappearanceoftheimagebysettingpropertiessuchasStyle.5. AssigntheimagecelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,orstyletotheImageCellType('ImageCellTypeClass'intheon-linedocumentation)object.
Example
ThisexamplesetsthepropertiesofanimagecelltypethenloadsalogoimageintoacellusingtheValue('ValueProperty'intheon-linedocumentation)property.Withbackgroundcolorset,theuseoftransparencycanbeseen.
C#FarPoint.Win.Spread.CellType.ImageCellType imgct = new FarPoint.Win.Spread.CellType.ImageCellType();System.Drawing.Image image = System.Drawing.Image.FromFile("D:\\Logos\\logo.jpg");imgct.Style = FarPoint.Win.RenderStyle.Stretch;imgct.TransparencyColor = Color.Black;imgct.TransparencyTolerance = 20;
fpSpread1.Sheets[0].Cells[1,1,1,2].BackColor = Color.Magenta;fpSpread1.Sheets[0].Columns[1,2].Width = 100;fpSpread1.Sheets[0].Rows[1,1].Height = 50;fpSpread1.Sheets[0].Cells[1,1,2,2].CellType = imgct;fpSpread1.Sheets[0].Cells[1,1].Value = image;
VB
Spread Windows Forms Developer’s Guide 364
Copyright © GrapeCity, Inc. All rights reserved.
Dim imgct As New FarPoint.Win.Spread.CellType.ImageCellType()Dim image As System.Drawing.Image = System.Drawing.Image.FromFile("D:\Logos\logo.jpg")imgct.Style = FarPoint.Win.RenderStyle.Stretchimgct.TransparencyColor = Color.Blackimgct.TransparencyTolerance = 20
FpSpread1.Sheets(0).Cells(1,1,1,2).BackColor = Color.MagentaFpSpread1.Sheets(0).Columns(1,2).Width =100FpSpread1.Sheets(0).Rows(1,1).Height = 50FpSpread1.Sheets(0).Cells(1,1,2,2).CellType = imgctFpSpread1.Sheets(0).Cells(1, 1).Value = image
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheImagecelltype.
NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectImage.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a List Box Cell
Youcanusealistboxcelltodisplayalist,whichallowstheusertoselectfromthedisplayedlist.Youcanspecifythelistofitems,whethertoincludeiconstoappearalongwithtext,thenumberofitemsthataredisplayedatanytime,andotheraspectsofthedisplay.
Textonly Textandicon
Tocreateacellthatactslikealistbox,usetheListBoxCellType('ListBoxCellTypeClass'intheon-linedocumentation)class.Createalistboxcellusingthefollowingprocedure.
CustomizingtheListAppearance
Hereisasummaryoftheappearancepropertiesthatyoucanusetocustomizethelistbox.
Property DescriptionEditorValue('EditorValueProperty'intheon-linedocumentation)
Setswhatvalueiswrittentotheunderlyingdatamodel.
ImageList('ImageListProperty'intheon-line Setsanimagelistfordisplayingiconsalongwithtextinthe
Spread Windows Forms Developer’s Guide 365
Copyright © GrapeCity, Inc. All rights reserved.
documentation) list.
ItemHeight('ItemHeightProperty'intheon-linedocumentation)
Setstheheightforeachiteminthelist.
ItemData('ItemDataProperty'intheon-linedocumentation)
Setsitemdata,whichisdifferentfromtheitemsthataredisplayed,touseforthelist.
Items('ItemsProperty'intheon-linedocumentation)
Setsitemstouseforthelist.
Foracompletelistofthepropertiesandmethodsofthiscelltype,refertotheListBoxCellType('ListBoxCellTypeClass'intheon-linedocumentation)class.Forinformationonthecombobox(whichincludesbothalistboxandaneditablearea),refertoSettingaComboBoxCell.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheListBoxcelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinealistboxcellbycreatinganinstanceoftheListBoxCellType('ListBoxCellTypeClass'intheon-linedocumentation)class.
2. Specifytheitemsinthelistthatappearaspartofthelistbox.YoucaneitherusetheItems('ItemsProperty'intheon-linedocumentation)propertyoftheListBoxCellType('ListBoxCellTypeClass'intheon-linedocumentation)classordefineastringandpassthatinwhencreatingtheinstanceoftheclass.
3. AssignthelistboxcelltypetoacellorrangeofcellsbysettingtheCellType('CellTypeProperty'intheon-linedocumentation)propertyforacell,column,row,orstyletotheListBoxCellType('ListBoxCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplecreatesalistboxcellandusesimagesfromanimagelistcontrol.
C#FarPoint.Win.Spread.CellType.ListBoxCellType listcell = new FarPoint.Win.Spread.CellType.ListBoxCellType();listcell.ImageList = ImageList1;listcell.ItemData = new string[] { "One", "Two", "Three"};listcell.Items = new string[] {"One","Two","Three"};listcell.ItemHeight = 40;fpSpread1.ActiveSheet.Cells[0, 0].CellType = listcell;fpSpread1.ActiveSheet.Rows[0].Height = 120;
VB
Spread Windows Forms Developer’s Guide 366
Copyright © GrapeCity, Inc. All rights reserved.
Dim listcell As New FarPoint.Win.Spread.CellType.ListBoxCellType()listcell.ImageList = ImageList1listcell.ItemData = New String() {"One", "Two", "Three"}listcell.Items = New String() {"One", "Two", "Three"}listcell.ItemHeight = 40FpSpread1.ActiveSheet.Cells(0, 0).CellType = listcellFpSpread1.ActiveSheet.Rows(0).Height = 120
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheListBoxcell
type.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectListBox.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Multiple-Column Combo Box Cell
Youcancreateacomboboxcellwithmultiplecolumnsinthedrop-downlist.Youcanprovideadrop-downlistaswellasaneditableareaallowingtheusertotypeinvaluesaswellaschoosingfromadisplayedlist.Youspecifythelistofitems,thenumberthatisdisplayedatanytime,andwhetherthecelliseditablebytheuser.
TheSpreadcontrolhasaButtonDrawMode('ButtonDrawModeProperty'intheon-linedocumentation)propertyforbuttoncellsandcomboboxcells.Thispropertyallowsyoutoalwaysshowabutton,orshowbuttonsinthecurrentcolumn,row,orcell.
Tocreateacellthatactslikeamultiple-columncombobox,usetheMultiColumnComboBoxCellType('MultiColumnComboBoxCellTypeClass'intheon-linedocumentation)class.Createsuchacomboboxcellusingthefollowingprocedure.
CustomizingtheDisplay
Youcancustomizethedisplayofthemultiple-columncomboboxcellbysettingthefollowingproperties.
Property DescriptionBackgroundImage('BackgroundImageProperty'intheon-linedocumentation)
Setsthebackgroundimageinthecell.
ButtonAlign('ButtonAlignProperty'intheon-line Setswherethebuttonsaredisplayed.
Spread Windows Forms Developer’s Guide 367
Copyright © GrapeCity, Inc. All rights reserved.
documentation)
ColumnEdit('ColumnEditProperty'intheon-linedocumentation)
Setsthecolumnofthelisttousefortheeditportion.
DataColumn('DataColumnProperty'intheon-linedocumentation)
Setswhichlistcolumntouseasthedatacolumn.
DataSourceList('DataSourceListProperty'intheon-linedocumentation)
Setsthedatasourceforthelistportionofthecell.
ListAlignment('ListAlignmentProperty'intheon-linedocumentation)
Setswhichsideoftheeditorthelistalignsto.
ListOffset('ListOffsetProperty'intheon-linedocumentation)
Setshowmuchthelistoffsetsfromtheeditor.
ListWidth('ListWidthProperty'intheon-linedocumentation)
Setsthewidthofthelist.
MaxDrop('MaxDropProperty'intheon-linedocumentation)
Setsthemaximumnumberofitemstodisplayinthelistatonetime.
StringTrim('StringTrimProperty'intheon-linedocumentation)
Setshowtotrimcharactersthatdonotfitinthecell.
SubEditor('SubEditorProperty'intheon-linedocumentation)
Setsthesubeditor.
CustomizingtheOperation
Youcancustomizetheoperationofthemultiple-columncomboboxcellbysettingthefollowingproperties.
Property DescriptionAcceptsArrowKeys('AcceptsArrowKeysProperty'intheon-linedocumentation)
Setshowarrowkeysareprocessedbythecell.
AutoSearch('AutoSearchProperty'intheon-linedocumentation)
Setshowalistofitemsinacomboboxcellissearchedbasedoninputofacharacterkey.
DataColumn('DataColumnProperty'intheon-linedocumentation)
Setswhichlistcolumntouseasthedatacolumn.
DataSourceList('DataSourceListProperty'intheon-linedocumentation)
Setsthedatasourceforthelistportionofthecell.
Editable('EditableProperty'intheon-linedocumentation)
Allowstheusertotypeintheeditportionofthecell.
SubEditor('SubEditorProperty'intheon-linedocumentation)
Setsthesubeditor.
NotethatsomegraphicalelementsincertaincelltypesareaffectedbyXPthemes(visualstyles).SettingtheVisualStylespropertyoftheSpreadcomponentto"off"canallowvisualcustomizationsofthosegraphicalcelltypestoworkasexpected.Formoreinformation,refertoUsingXPThemeswiththeComponent.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheMultiColumnComboBoxCellType('MultiColumnComboBoxCellTypeClass'intheon-linedocumentation)class.Formoreinformationonastandardcombobox(singlecolumn),refertoSettingaComboBoxCell.
UsingthePropertiesWindow
Spread Windows Forms Developer’s Guide 368
Copyright © GrapeCity, Inc. All rights reserved.
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheMultiColumnComboBoxcelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefineacomboboxcellbycreatinganinstanceoftheMultiColumnComboBoxCellType('MultiColumnComboBoxCellTypeClass'intheon-linedocumentation)class.
2. Specifytheitemsinthelistthatappearaspartofthecombobox.YoucaneitherusetheItemspropertyoftheMultiColumnComboBoxCellType('MultiColumnComboBoxCellTypeClass'intheon-linedocumentation)classordefineastringandpassthatinwhencreatingtheinstanceoftheclass.
3. Specifyhowthelistofitemsappears.Forexample,settheMaxDroppropertytosetthemaximumnumberofitemstodisplayatatime.Iftherearemoreitems,ascrollbarappears.Youcanalsosetthehorizontalalignmentofthecheckboxwithrespecttothecell.
4. AssignthecomboboxcelltypetoacellorrangeofcellsbysettingtheCellType('CellTypeProperty'intheon-linedocumentation)propertyforacell,column,row,orstyletotheMultiColumnComboBoxCellType('MultiColumnComboBoxCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplecreatesamultiple-columncomboboxcellandaddsdatafromadatasource.
C#string conStr = "Provider=Microsoft.JET.OLEDB.4.0;data source=C:\\SpreadStudio\\Common\\Patients2000.mdb";string sqlStr = "SELECT * FROM Patients";System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(conStr);DataSet ds = new DataSet();System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(sqlStr, conn);da.Fill(ds);FarPoint.Win.Spread.CellType.MultiColumnComboBoxCellType mcb = new FarPoint.Win.Spread.CellType.MultiColumnComboBoxCellType();mcb.DataSourceList = ds;mcb.DataColumn = 2;mcb.ColumnEdit = 2;mcb.ButtonAlign = FarPoint.Win.ButtonAlign.Left;mcb.ListAlignment = FarPoint.Win.ListAlignment.Right;mcb.ListWidth = 500;mcb.ListOffset = 5;mcb.MaxDrop = 5;fpSpread1.ActiveSheet.Cells[0, 0].CellType = mcb;
VBDim conStr As String = "Provider=Microsoft.JET.OLEDB.4.0;data
Spread Windows Forms Developer’s Guide 369
Copyright © GrapeCity, Inc. All rights reserved.
source=C:\SpreadStudio\Common\Patients2000.mdb"Dim sqlStr As String = "SELECT * FROM Patients"Dim conn As New System.Data.OleDb.OleDbConnection(conStr)Dim ds As DataSet = New DataSet()Dim da As New System.Data.OleDb.OleDbDataAdapter(sqlStr, conn)da.Fill(ds)Dim mcb As New FarPoint.Win.Spread.CellType.MultiColumnComboBoxCellType()mcb.DataSourceList = dsmcb.DataColumn = 1mcb.ButtonAlign = FarPoint.Win.ButtonAlign.Leftmcb.ListWidth = 500mcb.ListOffset = 5mcb.MaxDrop = 5FpSpread1.ActiveSheet.Cells(0, 0).CellType = mcb
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheComboBoxcell
type.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectComboBox.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Multiple Option Cell
Youcandefinemultipleoptionbuttonsinamultipleoptioncell.Thiscelltypeoffersseveraloptionbuttons,eitherhorizontallyorvertically,fortheusertoselect.Onlyonebuttoncanbeselectedatatime.Thedefaultisfornoneofthebuttonstobeselected.
Tocreateacellthatactslikealistofmultipleoptionbuttons,usetheMultiOptionCellType('MultiOptionCellTypeClass'intheon-linedocumentation)class.Createamultipleoptioncellusingthefollowingprocedure.
CustomizingDisplayandOperation
Youcancustomizethedisplayandoperationofthemultipleoptionsinthecellbysettingthefollowingproperties.
Property DescriptionBackgroundImage('BackgroundImageProperty'intheon-linedocumentation)
Setsthebackgroundimageforthecell.
EditorValue('EditorValueProperty'intheon-linedocumentation)
Setswhichvalueiswrittentotheunderlyingdatamodel.
Spread Windows Forms Developer’s Guide 370
Copyright © GrapeCity, Inc. All rights reserved.
ItemData('ItemDataProperty'intheon-linedocumentation)
SetstheItemDatatouseforthelist.
Items('ItemsProperty'intheon-linedocumentation) Createsthelisttousefortheoptionbuttons.
Orientation('OrientationProperty'intheon-linedocumentation)
Setstheorientationoftheoptionbuttons.
Picture('PictureProperty'intheon-linedocumentation)
Customizestheoptionbuttonimages.
TextAlign('TextAlignProperty'intheon-linedocumentation)
Setshowtextalignsinthecell.
UseMnemonic('UseMnemonicProperty'intheon-linedocumentation)
Setswhetheraccesskeys(hotkeysorkeyboardshortcuts)areusedinthecell.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheMultiOptionCellType('MultiOptionCellTypeClass'intheon-linedocumentation)class.
Formoreinformationonthecorrespondingeventwhenauserclicksonanoption,refertotheFpSpread.ButtonClicked('ButtonClickedEvent'intheon-linedocumentation)event.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheMultiOptioncelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinethemultipleoptionlistcellbycreatinganinstanceoftheMultiOptionCellType('MultiOptionCellTypeClass'intheon-linedocumentation)class.
2. Specifytheitemsinthelistofoptions.3. AssignthemultipleoptioncelltypetoacellorrangeofcellsbysettingtheCellType('CellTypeProperty'intheon-linedocumentation)propertyforacell,column,row,orstyletotheMultiOptionCellType('MultiOptionCellTypeClass'intheon-linedocumentation)object.
Example
Thefollowingexampledisplaysasetofoptionsfortheusertochoosefrom.
C#FarPoint.Win.Spread.CellType.MultiOptionCellType multcell = new FarPoint.Win.Spread.CellType.MultiOptionCellType();multcell.Items = new String[] {"Carbon", "Oxygen", "Hydrogen"};multcell.Orientation = FarPoint.Win.RadioOrientation.Horizontal;fpSpread1.ActiveSheet.Cells[0, 0].CellType = multcell;
Spread Windows Forms Developer’s Guide 371
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.ActiveSheet.Columns[0].Width = 220;
VBDim multcell As New FarPoint.Win.Spread.CellType.MultiOptionCellType()multcell.Items = new String() {"Carbon", "Oxygen", "Hydrogen"}multcell.Orientation = FarPoint.Win.RadioOrientation.HorizontalFpSpread1.ActiveSheet.Cells(0, 0).CellType = multcellFpSpread1.ActiveSheet.Columns(0).Width = 220
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheMultiOption
celltype.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectMultiOption.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Progress Indicator Cell
Aprogressindicatorcelldisplaysaprogressindicatorcontrolacrosstheentirecell.Youcanspecifythecolorofthefill,thetexttodisplay,thecolorofthetextandotherproperties.
Tocreateacellthatactslikeaprogressindicator,usetheProgressCellType('ProgressCellTypeClass'intheon-linedocumentation)class.Createaprogressindicatorcellusingtheproceduredescribedhere.
CustomizetheIndicator
Youcanfillintheindicatorwithasolidcolor,bydefault,orwithindividualbars,asshowninthisfigure.
Youcancustomizethedisplayandoperationoftheprogressindicatorinthecellbysettingthefollowingproperties.
Property DescriptionBackgroundImage('BackgroundImageProperty'intheon-linedocumentation)
Setsthebackgroundimageforthecell.
FillColor('FillColorProperty'intheon-linedocumentation)
Setsthecolortouseforthefilledpartoftheprogressindicator.
FillColor2('FillColor2Property'intheon-linedocumentation)
Setsthesecondfillcolortouseforthegradientpartoftheprogressindicator.
FillTextColor('FillTextColorProperty'intheon-linedocumentation)
Setsthecolortouseforthetextinthefilledpartoftheindicator.
GradientMode('GradientModeProperty'intheon-linedocumentation)
Setsthegradientmodeforagradientstyleprogressindicator.
Spread Windows Forms Developer’s Guide 372
Copyright © GrapeCity, Inc. All rights reserved.
Maximum('MaximumProperty'intheon-linedocumentation)
Setsthemaximumvalueforuserentry.
Minimum('MinimumProperty'intheon-linedocumentation)
Setstheminimumvalueforuserentry.
Orientation('OrientationProperty'intheon-linedocumentation)
Setstheorientationoftheprogressbar.
Picture('PictureProperty'intheon-linedocumentation)
SetstheimagetousefortheprogressbarwhenthestyleissettoPicture.
ShowText('ShowTextProperty'intheon-linedocumentation)
Setswhetherthepercentfilledstringisdisplayed.
Style('StyleProperty'intheon-linedocumentation) Setsthestyleoftheprogressbar(s).
Text('TextProperty'intheon-linedocumentation) SetsthestringtousewhenTextStyleissettoCustom.
TextStyle('TextStyleProperty'intheon-linedocumentation)
Setshowthetextportionoftheprogressbarisdisplayed.
Withtheseproperties,youcansetthevariousaspectsofthetext,youcansetapicturetodisplay,andyoucandefinethecolors,evenspecifyingtwocolorsforagradientfromonecolortoanother.
NotethatsomegraphicalelementsincertaincelltypesareaffectedbyXPthemes(visualstyles).SettingtheVisualStyles('VisualStylesProperty'intheon-linedocumentation)propertyoftheSpreadcomponentto"off"canallowvisualcustomizationsofthosegraphicalcelltypestoworkasexpected.Formoreinformation,refertoUsingXPThemeswiththeComponent.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheProgressCellType('ProgressCellTypeClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheProgresscelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinetheprogressindicatorcellbycreatinganinstanceoftheProgressCellType('ProgressCellTypeClass'intheon-linedocumentation)class.
2. Formatandspecifytheappearanceoftheprogressindicator.3. AssigntheprogressindicatorcelltypetoacellorrangeofcellsbysettingtheCellType('CellTypeProperty'intheon-linedocumentation)propertyforacell,column,row,orstyletotheProgressCellType('ProgressCellTypeClass'intheon-linedocumentation)object.
Example
Spread Windows Forms Developer’s Guide 373
Copyright © GrapeCity, Inc. All rights reserved.
Thisexamplecreatesaprogresscell.
C#FarPoint.Win.Spread.CellType.ProgressCellType progcell = new FarPoint.Win.Spread.CellType.ProgressCellType();progcell.FillColor = Color.Red;fpSpread1.ActiveSheet.Cells[0, 0].CellType = progcell;fpSpread1.ActiveSheet.Cells[0, 0].VisualStyles = FarPoint.Win.VisualStyles.Off;fpSpread1.ActiveSheet.Cells[0, 0].Value = 50;
VBDim progcell As New FarPoint.Win.Spread.CellType.ProgressCellType()progcell.FillColor = Color.RedFpSpread1.ActiveSheet.Cells(0, 0).CellType = progcellFpSpread1.ActiveSheet.Cells(0, 0).VisualStyles = FarPoint.Win.VisualStyles.OffFpSpread1.ActiveSheet.Cells(0, 0).Value = 50
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheProgresscell
type.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectProgress.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Rich Text Cell
Youcancreatearichtextcellthathastextwithmultiplecolorsandfontsinthecell.
Therichtextcellhasarun-timemenuforformattingthetextinacellandforloadingarichtextformattedfile(RTF).Themenualsohasbasiceditoperationssuchascut,copy,paste,delete,andselectall.TobringupthemenuatruntimethecellmustbeinEditmode.Thenyouright-clickinthecelltobringupthemenuforhandlingthecontentsofthatcell.Highlightthetextfirstifyouwanttosetthecolor,font,orstyleofthetextinthecell.Anexampleoftheuseofthemenuisshowninthisfigure.
Spread Windows Forms Developer’s Guide 374
Copyright © GrapeCity, Inc. All rights reserved.
UnderstandingContextMenuChoices
Thechoicesinthecontextmenuaredescribedinthistable.
MenuItem
Description
CutCopyPaste
StandardClipboardoperationsthatcut,copy,andpastetoandfromtheClipboardthecontents(textandformatting)ofthecell
Delete Removestheselectedcontents(textandformatting)ofthecell
SelectAll Selectstheentirecontents(textandformatting)ofthecell
ClearAll Clearstheentirecontents(textandformatting)ofthecell
Load OpenstheFileOpendialogtoallowyoutoselectanRTFfiletoload
Color Opensacolorpalettetoallowyoutoselectacolorthatiseitherappliedtoselectedtextorisusedasthecolorofsubsequenttext
Font Opensafontpickertoallowyoutoselectafontfaceandsizethatiseitherappliedtoselectedtextorisusedasthefontofsubsequenttext
Style Opensamenutoallowyoutoselectafontstyle(bold,italics,orunderline)thatiseitherappliedtoselectedtextorisusedasthefontofsubsequenttext
Align Opensamenutoallowyoutosetthetextalignment
UsingtheRich-TextCell
Whentherich-textcellisfirsteditedortextisloaded,theRTFstringofdataandformattinginformationissetinthe
Spread Windows Forms Developer’s Guide 375
Copyright © GrapeCity, Inc. All rights reserved.
cell.Subsequentchangestothecell,column,orrowappearancesettings(suchasfont,textcolor,alignment)donotaffecttheexistingtextbecausetheformattinginformationforthattextisalreadyset.Forthenewersettingstobeappliedtotheoriginalstring,youmustcompletelyclearthecellofbothdataandformatting.
YoucanusetheValue('ValueProperty'intheon-linedocumentation)propertyincodetoloadthecontentsofanRTFfileasastringofRTFcommands,oryoucansetanysetofRTFcommandsdirectly.
Settingapropertysuchasalignmentmaynotapplyafterthecellhasbeenmodifiedineditmode.Manyformattingproperties(HorizontalAlignment('HorizontalAlignmentProperty'intheon-linedocumentation),Font('FontProperty'intheon-linedocumentation),ForeColor('ForeColorProperty'intheon-linedocumentation),andsoon)canbesetinthehiddenRTFcodeassociatedwiththevalueofthecell.Forexample,settingtheHorizontalAlignmentpropertypriortoanyeditingmaycorrectlysetthealignment,butsettingthispropertyaftereditingmightnothavethedesiredeffect.RTFhashiddenformattingembeddedintheRTFstringwhichcanbeparsedorviewedthroughtheValue('ValueProperty'intheon-linedocumentation)propertyofthecell.
Thecellwidthmaybeoffseveralpixelsifyouautomaticallysizetherichtextcellandyouareusingmultiplefonts.
Deletingthetextfromarich-textcellputsanon-nullstringinthecell.ThismaycauseunexpectedresultswiththeISBLANKandCOUNTBLANKformulafunctionssincetheytreatthenon-nullstringasnon-blank.
IftheWordWrap('WordWrapProperty'intheon-linedocumentation)propertyistruewhenusingtheGetPreferredRowHeight('GetPreferredRowHeightMethod'intheon-linedocumentation)method,theheightmaybeslightlylargerifthelastcharacteronawrappedlineisontheborder.
ImportantNotes
Therich-textcellusestheMicrosoft.NETRichTextBoxclassforediting.Textusingafontwithextendedcharactersets,likeMSPMincho,cannotbesettoafontthatdoesnotsupportextendedcharactersets,likeTahoma.TheresultisthatRichTextBoxdoesnotallowyoutochangethefontofaFarEastscript-basedfonttoaWesternfont.
ThisfontissueisalimitationoftheRichTextBoxfortheMicrosoftWindows2000operatingsystem.Ifyoutrytosetafontthatdoesnotsupportextendedcharactersets,likeTahoma,ontextwithextendedcharacters,amessageboxisdisplayed.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheRichTextCellType('RichTextCellTypeClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheRichTextcelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinearichtextcellbycreatinganinstanceoftheRichTextCellType('RichTextCellTypeClass'intheon-linedocumentation)class.
2. SpecifythepropertiesoftheRichTextCellType('RichTextCellTypeClass'intheon-linedocumentation)class.
Spread Windows Forms Developer’s Guide 376
Copyright © GrapeCity, Inc. All rights reserved.
3. IfyouwanttoloadRTFdata,settheValuepropertyoftheRichTextCellType('RichTextCellTypeClass'intheon-linedocumentation)classtoloadthedata
4. AssigntherichtextcelltypetoacellorrangeofcellsbysettingtheCellType('CellTypeProperty'intheon-linedocumentation)propertyforacell,column,row,orstyletotheRichTextCellType('RichTextCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplecreatesarichtextcellandloadsdata.
C#FarPoint.Win.Spread.CellType.RichTextCellType rtf = new FarPoint.Win.Spread.CellType.RichTextCellType();rtf.WordWrap = true;rtf.Multiline = true;fpSpread1.ActiveSheet.Cells[0, 0].CellType = rtf;fpSpread1.ActiveSheet.Columns[0].Width = 300;fpSpread1.ActiveSheet.Rows[0].Height = 150;fpSpread1.ActiveSheet.Cells[0, 0].Value = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fscript\fprq2\fcharset0 Comic Sans MS;}{\f1\froman\fprq2\fcharset0 Times New Roman;}{\f2\fswiss\fcharset0 Arial;}}{\colortbl ;\red128\green0\blue128;\red0\green255\blue255;\red255\green0\blue0;\red0\green255\blue0;\red0\green0\blue255;}\viewkind4\uc1\pard\cf1\b\f0\fs24 Testing\cf2\b0\fs28 \cf3\f1\fs40 1... \cf4\i 2... \cf5\ul\i0 3...\cf0\f2\fs20\par}";
VBDim rtf As New FarPoint.Win.Spread.CellType.RichTextCellType()rtf.WordWrap = Truertf.Multiline = TrueFpSpread1.ActiveSheet.Cells(0, 0).CellType = rtfFpSpread1.ActiveSheet.Columns(0).Width = 300FpSpread1.ActiveSheet.Rows(0).Height = 150FpSpread1.ActiveSheet.Cells(0, 0).Value = "{\rtf1\ansi\ansicpg1252\deff0\deflang1033" + _"{\fonttbl{\f0\fscript\fprq2\fcharset0 Comic Sans MS;}" + _"{\f1\froman\fprq2\fcharset0 Times New Roman;}" + _"{\f2\fswiss\fcharset0 Arial;}}" + _"{\colortbl ;\red128\green0\blue128;\red0\green255\blue255;" + _"\red255\green0\blue0;" + _"\red0\green255\blue0;\red0\green0\blue255;}" + _"\viewkind4\uc1\pard\cf1\b\f0\fs24 Testing\cf2\b0\fs28" + _" \cf3\f1\fs40 1... \cf4\i 2... \cf5\ul\i0 3...\cf0\f2\fs20\par" + _"}"
Example
Thisexampleloadsarichtextfile.
C#System.IO.TextReader f = System.IO.File.OpenText("your_file.rtf");string bits;bits = f.ReadToEnd();
Spread Windows Forms Developer’s Guide 377
Copyright © GrapeCity, Inc. All rights reserved.
f.Close();fpSpread1.ActiveSheet.Cells[0, 0].CellType = new FarPoint.Win.Spread.CellType.RichTextCellType();fpSpread1.ActiveSheet.Cells[0, 0].Value = bits;
VBDim f as System.IO.TextReader = System.IO.File.OpenText("your_file.rtf")Dim bits As Stringbits = f.ReadToEnd()f.Close()FpSpread1.ActiveSheet.Cells(0, 0).CellType = New FarPoint.Win.Spread.CellType.RichTextCellType()FpSpread1.ActiveSheet.Cells(0, 0).Value = bits
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheRichTextCellTypecelltype.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectRichText.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting a Slider Cell
Aslidercelldisplaysaslidercontrolinthecell.
Tocreateacellthatactslikeaslider,usetheSliderCellType('SliderCellTypeClass'intheon-linedocumentation)classandfollowtheproceduredescribedinthistopic.
CustomizingtheSlider
Thepartsoftheslider(correspondingtotheirpropertynames)areshownhere.Forthisexample,theorientationishorizontalandsolidcolorsareused(asopposedtopictures).
Spread Windows Forms Developer’s Guide 378
Copyright © GrapeCity, Inc. All rights reserved.
Youcancustomizethedisplayandoperationofthesliderinthecellbysettingthefollowingproperties.
Property CustomizationBackgroundImage('BackgroundImageProperty'intheon-linedocumentation)
Setsthebackgroundimageforthecell.
ChangeOnFocus('ChangeOnFocusProperty'intheon-linedocumentation)
Setswhethertheslidermoveswiththeinitialclick.
KnobColor('KnobColorProperty'intheon-linedocumentation)
Setsthecolorofthesliderknob.
KnobPicture('KnobPictureProperty'intheon-linedocumentation)
Customizesthesliderknobimage.
KnobWidth('KnobWidthProperty'intheon-linedocumentation)
Setsthewidth(inpixels)ofthesliderknob.
Maximum('MaximumProperty'intheon-linedocumentation) Setsthemaximumvalueforuserentry.
Minimum('MinimumProperty'intheon-linedocumentation) Setstheminimumvalueforuserentry.
Orientation('OrientationProperty'intheon-linedocumentation)
Setstheorientationoftheslider.
TickColor('TickColorProperty'intheon-linedocumentation) Setsthecoloroftheslidertickmark.
TickLength('TickLengthProperty'intheon-linedocumentation)
Setsthesizeoftheslidertickmark.
TickSpacing('TickSpacingProperty'intheon-linedocumentation)
Setshowfrequentlytospacethetickmarks.
TrackColor('TrackColorProperty'intheon-linedocumentation)
Setsthecoloroftheslidertrack.
TrackPicture('TrackPictureProperty'intheon-linedocumentation)
Customizestheimagefortheslidertrack.
TrackWidth('TrackWidthProperty'intheon-linedocumentation)
Setsthewidth(inpixels)oftheslidertrack.
YoucanprogrammaticallychangethelocationoftheknobintheslidercellbysettingtheValue('ValueProperty'intheon-linedocumentation)propertytoavaluethatisgreaterthanorequaltothemininumorlessthanorequaltothemaximumsetting.
NotethatsomegraphicalelementsincertaincelltypesareaffectedbyXPthemes(visualstyles).SettingtheVisualStyles('VisualStylesProperty'intheon-linedocumentation)propertyoftheSpreadcomponentto"off"canallowvisualcustomizationsofthosegraphicalcelltypestoworkasexpected.Formoreinformation,refertoUsing
Spread Windows Forms Developer’s Guide 379
Copyright © GrapeCity, Inc. All rights reserved.
XPThemeswiththeComponent.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheSliderCellType('SliderCellTypeClass'intheon-linedocumentation)class.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheSlidercelltype.8. ExpandthelistofpropertiesundertheCellTypeproperty.Selectandsetthesespecificpropertiesasneeded.9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. DefinetheslidercellbycreatinganinstanceoftheSliderCellType('SliderCellTypeClass'intheon-linedocumentation)class.
2. Formatandspecifytheappearanceoftheslider.3. AssigntheslidercelltypetoacellorrangeofcellsbysettingtheCellType('CellTypeProperty'intheon-linedocumentation)propertyforacell,column,row,orstyletotheSliderCellType('SliderCellTypeClass'intheon-linedocumentation)object.
Example
Thisexamplecreatesaslidercell.
C#fpSpread1.ActiveSheet.Columns[1].Width = 250;fpSpread1.ActiveSheet.Rows[1].Height = 150;fpSpread1.VisualStyles = FarPoint.Win.VisualStyles.Off;
FarPoint.Win.Spread.CellType.SliderCellType slider = new FarPoint.Win.Spread.CellType.SliderCellType();slider.BackgroundImage = new FarPoint.Win.Picture(Image.FromFile("C:\\images\\scene.jpg"));slider.ChangeOnFocus = true;
slider.KnobColor = Color.Red;// Or if you want to use an image instead of a solid color:// slider.KnobPicture = new FarPoint.Win.Picture(Image.FromFile("..\\images\\brush.gif"));slider.KnobWidth = 10;slider.Maximum = 200;slider.Minimum = 0;slider.Orientation = FarPoint.Win.SliderOrientation.Horizontal;slider.TickColor = Color.DarkBlue;slider.TickLength = 5;slider.TickSpacing = 20;
Spread Windows Forms Developer’s Guide 380
Copyright © GrapeCity, Inc. All rights reserved.
slider.TrackColor = Color.Green;// Or if you want to use an image instead of a solid color:// slider.TrackPicture = new FarPoint.Win.Picture(Image.FromFile("..\\images\\pattern.jpg"));slider.TrackWidth = 10;
fpSpread1.ActiveSheet.Cells[1, 1].CellType = slider;
VBFpSpread1.ActiveSheet.Columns(1).Width = 250FpSpread1.ActiveSheet.Rows(1).Height = 150FpSpread1.VisualStyles = FarPoint.Win.VisualStyles.Off
Dim slider As New FarPoint.Win.Spread.CellType.SliderCellType()slider.BackgroundImage = New FarPoint.Win.Picture(Image.FromFile("C:\\images\\scene.jpg"))slider.ChangeOnFocus = Trueslider.KnobColor = Color.Red‘ Or if you want to use an image instead of a solid color:‘ slider.KnobPicture = New FarPoint.Win.Picture(Image.FromFile("..\\images\\brush.gif"))slider.KnobWidth = 10slider.Maximum = 200slider.Minimum = 0slider.Orientation = FarPoint.Win.SliderOrientation.Horizontalslider.TickColor = Color.DarkBlueslider.TickLength = 5slider.TickSpacing = 20slider.TrackColor = Color.Green‘ Or if you want to use an image instead of a solid color:‘ slider.TrackPicture = New FarPoint.Win.Picture(Image.FromFile("..\\images\\pattern.jpg"))slider.TrackWidth = 10FpSpread1.ActiveSheet.Cells(1, 1).CellType = slider
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheSlidercelltype.
NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.Selectandsetthosepropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectSlider.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Understanding Additional Features of Cell Types
Youcanspecifythecelltypeforindividualcells,columns,rows,arangeofcells,oranentiresheet.Foranycelltypetherearepropertiesofacellthatcanbeset.Ingeneral,workingwithcelltypesincludesdefiningthecelltype,settingtheproperties,andapplyingthatcelltypetocells.
Thefollowingtopicsprovideadditionalinformationaboutcustomizingcellsbasedoncelltypes:
DisplayingSpinButtons
Spread Windows Forms Developer’s Guide 381
Copyright © GrapeCity, Inc. All rights reserved.
AllowingaComboBoxCelltoHandleaDoubleClickLimitingValuesforaNumericCellCustomizingthePop-UpDate-TimeControlCustomizingthePop-UpCalculatorControlCustomizingAutomaticCompletion(TypeAhead)WorkingwithaSubEditorCreatingaCustomCellType
Displaying Spin Buttons
Insomecelltypes,youcandisplayspinbuttons,toletuserschangethevalueinacellquickly.Spinbuttonsareasetoftwoarrowbuttonsthatappeartogether,oneforincreasingthevalueandonefordecreasingthevalue.Spinbuttonsappearwhenthecellisineditmode.Thefollowingfigureillustratesspinbuttonsontheright-handsideofanumbercell.
Youspecifyhowmuchthevaluechangeswhentheuserclicksaspinbuttonandyoudeterminewhetherthevaluewrapswhentheminimumormaximumvalueisreached.
Spinbuttonscanbedisplayedin:
CurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation)(seeSettingaCurrencyCell)DateTimeCellType('DateTimeCellTypeClass'intheon-linedocumentation)(seeSettingaDate-TimeCell)NumberCellType('NumberCellTypeClass'intheon-linedocumentation)(seeSettingaNumberCell)PercentCellType('PercentCellTypeClass'intheon-linedocumentation)(seeSettingaPercentCell)
Forthenumericcelltypes,ifthecursorisleftofthedecimalpoint,bydefaultthespinbuttonincrementsthevalueusingthewholenumber.Ifthecursoristotheright,bydefaultthespinbuttonincrementsthevalueusingthefirst,ortenths,decimalplace.
Forthedate-timecelltype,theday,month,year,etc.areincrementedordecrementeddependingonwhichpartofthedateandtimethecursorisin.
Thespinbuttonsexpandverticallytofilltheentireheightofthecell,sothetallerthecell,thebiggerthespinbuttons.Thepropertiesofthecurrency,number,andpercentcelltypesthatrelatetospinbuttonsarelistedinthefollowingtable.Thedate-timecelltypeonlyprovidestheSpinButtonproperty.
Property DescriptionSpinButton Setswhetheraspinbuttonisdisplayedwhenediting.
SpinDecimalIncrement Setstheamountbywhichthevalueincrementswhenusingthespinbuttonsandthecursorisinthedecimalportion.
SpinIntegerIncrement Setstheamountbywhichthevalueincrementswhenusingthespinbuttonsandthecursorisintheintegerportion.
SpinWrap Setswhetherthevaluewrapswhentheminimumormaximumisreached.
Formoreinformationrefertothepropertyforeachcelltype:
CurrencyCellType.SpinButton('SpinButtonProperty'intheon-linedocumentation)DateTimeCellType.SpinButton('SpinButtonProperty'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 382
Copyright © GrapeCity, Inc. All rights reserved.
NumberCellType.SpinButton('SpinButtonProperty'intheon-linedocumentation)PercentCellType.SpinButton('SpinButtonProperty'intheon-linedocumentation)
Forinformationontheeditablecelltypes,refertoWorkingwithEditableCellTypes.
Forinformationonotherfeaturesofcelltypes,refertoUnderstandingAdditionalFeaturesofCellTypes.
UsingCode
DisplaythespinbuttonsbysettingtheSpinButtonpropertytoTrue.SpecifytheamountbywhichthevalueinthecellisincrementedordecrementedwhentheuserclicksonthespinbuttonsbysettingtheSpinIncrementpropertytoanonzerovalue.SpecifywhetherthevalueinthecellwrapswhenthecellreachestheminimumormaximumvaluebysettingtheSpinWrappropertytoTrueorFalse.
Example
Thisexamplespecifiesacurrencycellandsetsspinbuttonproperties.
C#FarPoint.Win.Spread.CellType.CurrencyCellType crcycell = new FarPoint.Win.Spread.CellType.CurrencyCellType();crcycell.SpinButton = true;crcycell.SpinDecimalIncrement = 0.5F;crcycell.SpinIntegerIncrement = 5;crcycell.SpinWrap = true;crcycell.MaximumValue = 500;crcycell.MinimumValue = -100;fpSpread1.Sheets[0].Cells[6,2].CellType = crcycell;fpSpread1.Sheets[0].Cells[6,2].Value = 443.3482;
VBDim curr As New FarPoint.Win.Spread.CellType.CurrencyCellType()curr.SpinButton = Truecurr.SpinDecimalIncrement = 0.5curr.SpinIntegerIncrement = 5curr.SpinWrap = Truecurr.MaximumValue = 500curr.MinimumValue = -100FpSpread1.ActiveSheet.Cells(0, 0).CellType = currFpSpread1.ActiveSheet.Cells(0, 0).Value = 443.3482
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosethecelltype.Now
expandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.SetSpinButtontoTruetodisplaythespinbuttons.Selectandsetotherpropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectthecelltype.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Allowing a Combo Box Cell to Handle a Double Click
Spread Windows Forms Developer’s Guide 383
Copyright © GrapeCity, Inc. All rights reserved.
Bydefault,acomboboxcell(ComboBoxCellType('ComboBoxCellTypeClass'intheon-linedocumentation))cannotreceiveadouble-clickwiththeleftmousebutton.Thecellgoesintoeditmodeonthefirstclick,sothenextclickgoestotheFpCombocontrolthatisthesubeditor.Tohandledouble-clickingonacomboboxcell,usecodebasedontheexampleshownhere.
Formoreinformationonthepropertiesandmethodsofthiscelltype,refertotheComboBoxCellType('ComboBoxCellTypeClass'intheon-linedocumentation)class.
Forinformationonthegraphicalcelltypes,refertoWorkingwithGraphicalCellTypes.
Forinformationonotherfeaturesofcelltypes,refertoUnderstandingAdditionalFeaturesofCellTypes.
UsingCode
1. DefineacomboboxcellbycreatinganinstanceoftheComboBoxCellType('ComboBoxCellTypeClass'intheon-linedocumentation)class.
2. Definetheitemsinthecomboboxlist.3. Handlethedouble-clickevent.
Example
Thisexampleprovidesaneventwhendouble-clickingonacombocell.
C#private void Form1_Load(object sender, System.EventArgs e){ FarPoint.Win.Spread.CellType.ComboBoxCellType c = new FarPoint.Win.Spread.CellType.ComboBoxCellType(); c.Items = new String[] {"a", "b", "c"}; fpSpread1.Sheets[0].Rows[0].CellType = c;}
private void HeaderDoubleClick(object sender, System.EventArgs e){//Add event code}
private void FpSpread1_EditModeOn(object sender, System.EventArgs e){ FarPoint.Win.FpCombo c; if (fpSpread1.Sheets[0].ActiveRowIndex == 0) { c = ((FarPoint.Win.FpCombo)(fpSpread1.EditingControl)); c.Click += new System.EventHandler(HeaderDoubleClick); } }
VBPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim c As New FarPoint.Win.Spread.CellType.ComboBoxCellType c.Items = New String() {"a", "b", "c"} FpSpread1.Sheets(0).Rows(0).CellType = cEnd Sub
Private Sub HeaderDoubleClick(ByVal sender As Object, ByVal e As System.EventArgs)'Add event code
Spread Windows Forms Developer’s Guide 384
Copyright © GrapeCity, Inc. All rights reserved.
End Sub
Private Sub FpSpread1_EditModeOn(ByVal sender As Object, ByVal e As System.EventArgs) Handles FpSpread1.EditModeOn Dim c As FarPoint.Win.FpCombo If FpSpread1.Sheets(0).ActiveRowIndex = 0 Then c = CType(FpSpread1.EditingControl, FarPoint.Win.FpCombo) AddHandler c.Click, AddressOf HeaderDoubleClick End IfEnd Sub
Limiting Values for a Numeric Cell
Youcansettheminimumandmaximumvaluesthatcanbeenteredinacellandnotifytheuserwithamessageiftheentryissmallerthantheminimumorlargerthanthemaximum.
Thecelltypesthatallowyoutosetaminimumandmaximumvalueare:
CurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation)NumberCellType('NumberCellTypeClass'intheon-linedocumentation)PercentCellType('PercentCellTypeClass'intheon-linedocumentation)ProgressCellType('ProgressCellTypeClass'intheon-linedocumentation)SliderCellType('SliderCellTypeClass'intheon-linedocumentation)
Formoreinformationaboutthesecelltypes,refertothefollowingtopics:
SettingaCurrencyCellSettingaNumberCellSettingaPercentCellSettingaProgressIndicatorCellSettingaSliderCell
Forinformationonotherfeaturesofcelltypes,refertoUnderstandingAdditionalFeaturesofCellTypes.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertylist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthecelltype.7. Inthepropertylist,selecttheCellTypepropertyandchoosetheCurrency,Number,Percent,Progress,orSlidercelltype.
8. ExpandthelistofpropertiesundertheCellTypeproperty.SelectandsettheMaximumValueandMinimumValuepropertiestothehighestandlowestallowablecurrencyvalues.
9. ClickOKtoclosetheCell,Column,andRowEditor.10. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. SettheminimumormaximumvalueorbothforacurrencycellbysettingtheMaximumValueand
Spread Windows Forms Developer’s Guide 385
Copyright © GrapeCity, Inc. All rights reserved.
MinimumValuepropertiesforaCurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation),NumberCellType('NumberCellTypeClass'intheon-linedocumentation),PercentCellType('PercentCellTypeClass'intheon-linedocumentation),ProgressCellType('ProgressCellTypeClass'intheon-linedocumentation),orSliderCellType('SliderCellTypeClass'intheon-linedocumentation)object.
2. AssignthecelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,orstyletotheparticularcelltypeobject.
Example
Thisexamplecreatesacurrencycellandsetstheminimumandmaximumvalues.
C#FarPoint.Win.Spread.CellType.CurrencyCellType currcell = new FarPoint.Win.Spread.CellType.CurrencyCellType();currcell.MinimumValue = 1;currcell.MaximumValue = 10;fpSpread1.ActiveSheet.Cells[1,1].CellType = currcell;fpSpread1.ActiveSheet.Cells[1,1].Note = "Pick a number between 1 and 10!";
VBDim currcell As New FarPoint.Win.Spread.CellType.CurrencyCellType()currcell.MinimumValue = 1currcell.MaximumValue = 10FpSpread1.ActiveSheet.Cells(1,1).CellType = currcellFpSpread1.ActiveSheet.Cells(1,1).Note = "Pick a number between 1 and 10!"
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType(orright-clickonthecellsandselectthecelltype).
Fromthedrop-downlist,chooseCurrencyorothernumericcelltype.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.
3. SelectandsettheMaximumValueandMinimumValuepropertiestothehighestandlowestallowablecurrencyvalues.
4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing the Pop-Up Date-Time Control
IfyoupressF4ordouble-clickadate-timecellwhenitisineditmode,apop-upcalendar(orpop-upclock)appears,asshowninthefollowingfigures.Thecalendarcontrolappearsifyouhavethedate-timecellsettoanyformatbesidesTimeOnlyformat.TheclockcontrolappearsifyouhavetheformatsettoTimeOnly.Thedateyouchoosefromthecalendar(orthetimeyouchoosefromtheclock)isplacedinthedate-timecell.Ifyouwantthepresentdateandtime,inthecalendarcontrolclickToday;ifyouwantthepresenttime,intheclockcontrolclickNow.
Pop-UpCalendarControl Pop-UpClockControl
Spread Windows Forms Developer’s Guide 386
Copyright © GrapeCity, Inc. All rights reserved.
YoucanalsodisplaytheclockcontroliftheDateTimeFormat('DateTimeFormatProperty'intheon-linedocumentation)propertyissettoUserDefinedandtheUserDefinedFormat('UserDefinedFormatProperty'intheon-linedocumentation)propertyusesatimesettingsuchasHH:mm.
Youcanspecifynormalandabbreviateddaynames,normalandabbreviatedmonthnames,andthetextforthebuttonsatthebottomofthecontrol.UsetheSetCalendarText('SetCalendarTextMethod'intheon-linedocumentation)methodoftheDateTimeCellType('DateTimeCellTypeClass'intheon-linedocumentation)classtosetthese.
Notethatthetextappearscenteredonthebutton.Ifyousetcustomtextforthebuttons,trytolimityourtexttoeightorninecharactersinlength.Thebuttonwilldisplaytencharacters,butthefirstandlastappearveryclosetotheedges.
Whenusingthecontrols,youmustclicktheOKorCancelbuttontoclosethecontrol.TheToday(orNow)buttonsimplysetsthevalueinthecelltothecurrentdate(ortime).
Formoreinformationonsettingtheformatofthedate-timecell,refertotheDateTimeFormat('DateTimeFormatEnumeration'intheon-linedocumentation)enumeration.
Forinformationontheeditablecelltypes,refertoWorkingwithEditableCellTypes.
Forinformationonotherfeaturesofcelltypes,refertoUnderstandingAdditionalFeaturesofCellTypes.
UsingCode
1. Definethedate-timecellbycreatinganinstanceoftheDateTimeCellType('DateTimeCellTypeClass'intheon-linedocumentation)class.
2. Specifythevaluesforthebuttonsorforallthedayandmonthnamesandthebuttons.3. Assignthedate-timecelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,
orstyletotheDateTimeCellType('DateTimeCellTypeClass'intheon-linedocumentation)object.
Example
Thefollowingexamplesetsthetextofthebuttonsandspecifiesdayandmonthnamesinarraylists.
C#FarPoint.Win.Spread.CellType.DateTimeCellType datecell = new FarPoint.Win.Spread.CellType.DateTimeCellType();string[] daynames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
Spread Windows Forms Developer’s Guide 387
Copyright © GrapeCity, Inc. All rights reserved.
"Saturday"};string[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};string[] dayabbrev = {"Su","My","Ty","Wy","Th","Fy","Sy"};string[] mthabbrev = {"Jy","Fy","Mh","Al","My","Jn","Jl","At","Sr","Or","Nr","Dr"};string okbuttn = "Fine";string cancelb = "Quit";datecell.DateTimeFormat = FarPoint.Win.Spread.CellType.DateTimeFormat.UserDefined;datecell.UserDefinedFormat = "dddd MMMM d, yyyy";datecell.SetCalendarText(daynames,months,dayabbrev,mthabbrev,okbuttn, cancelb);fpSpread1.ActiveSheet.Cells[1, 1].CellType = datecell;fpSpread1.ActiveSheet.Cells[1, 1].Value = System.DateTime.Now;fpSpread1.ActiveSheet.Columns[1].Width = 130;
VBDim datecell As New FarPoint.Win.Spread.CellType.DateTimeCellType()Dim daynames() As String = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }Dim months() As String = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}Dim dayabbrev() As String = {"Su","My","Ty","Wy","Th","Fy","Sy"}Dim mthabbrev() As String = {"Jy","Fy","Mh","Al","My","Jn","Jl","At","Sr","Or","Nr","Dr"}Dim okbuttn As String = "Fine"Dim cancelb As String = "Quit"datecell.DateTimeFormat = FarPoint.Win.Spread.CellType.DateTimeFormat.UserDefineddatecell.UserDefinedFormat = "dddd MMMM d, yyyy"datecell.SetCalendarText(daynames,months,dayabbrev,mthabbrev,okbuttn, cancelb)FpSpread1.ActiveSheet.Cells(1, 1).CellType = datecellFpSpread1.ActiveSheet.Cells(1, 1).Value = System.DateTime.NowFpSpread1.ActiveSheet.Columns(1).Width = 130
UsingtheSpreadDesigner
1. Selectthecellorcellsintheworkarea.2. Inthepropertylist,intheMisccategory,selectCellType.Fromthedrop-downlist,choosetheDateTimecell
type.NowexpandtheCellTypepropertyandvariouspropertiesareavailablethatarespecifictothiscelltype.SetpropertiessuchasShortDayNamesandShortMonthNamestochangethecalendartext.Setotherpropertiesasneeded.Orright-clickonthecellorcellsandselectCellType.Fromthelist,selectthecelltype.IntheCellTypeeditor,setthepropertiesyouneed.ClickApply.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing the Pop-Up Calculator Control
IftheuserpressesF4ordouble-clicksanyoftheseveralnumericcelltypeswhenthecellisineditmode,apop-upcalculatorappears,asshowninthefollowingfigure.
Spread Windows Forms Developer’s Guide 388
Copyright © GrapeCity, Inc. All rights reserved.
Youcanusethecalculatortotypeanumberortoperformacalculation.Theresultfromthecalculatorisplacedinthenumericcell.Thecelltypesthatallowacalculatorpop-upare:
CurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation)(seeSettingaCurrencyCell)NumberCellType('NumberCellTypeClass'intheon-linedocumentation)(seeSettingaNumberCell)PercentCellType('PercentCellTypeClass'intheon-linedocumentation)(seeSettingaPercentCell)
Whenusingthecontrols,youmustclicktheOKorCancelbuttontoclosethecontrol.YoucanchangethetextofthebuttonsatthebottomwiththeSetCalculatorTextmethodforthatcelltype.
Notethatthetextappearscenteredonthebutton.Ifyousetcustomtextforthebuttons,trytolimityourtexttoeightorninecharactersinlength.Thebuttonwilldisplaytencharacters,butthefirstandlastappearveryclosetotheedgesofthebutton.
Forinformationontheeditablecelltypes,refertoWorkingwithEditableCellTypes.
Forinformationonotherfeaturesofcelltypes,refertoUnderstandingAdditionalFeaturesofCellTypes.
UsingCode
1. DefinethecellbycreatinganinstanceoftheCurrencyCellType('CurrencyCellTypeClass'intheon-linedocumentation)class(orothernumerictypecell).
2. Specifythetextforthebuttons.3. AssignthecelltypetoacellorrangeofcellsbysettingtheCellTypepropertyforacell,column,row,orstyle.
Example
Thisexamplesetsthetextofthebuttons.
C#
Spread Windows Forms Developer’s Guide 389
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Spread.CellType.CurrencyCellType ctest = new FarPoint.Win.Spread.CellType.CurrencyCellType();ctest.SetCalculatorText("Accept", "Cancel");fpSpread1.Sheets[0].Cells[0, 0].CellType = ctest;
VBDim ctest As New FarPoint.Win.Spread.CellType.CurrencyCellType()ctest.SetCalculatorText("Accept", "Cancel")FpSpread1.Sheets(0).Cells(0, 0).CellType = ctest
Customizing Automatic Completion (Type Ahead)
Youcanprovideautomaticcompletion(typeahead)ofuserinputtoacell.YouusetheIAutoCompleteSupport('IAutoCompleteSupportInterface'intheon-linedocumentation)interfaceanditspropertiestoprovidetheautomaticcompletionfeatureintheeditablecelltypes.
Basicallytherearetwopropertiesthatareset.Firstyousetthemodeofautomaticcompletion,asshowninthefigureabove.Theoptionsincludewhethertosuggestalistofpossiblecompletionsoradrop-downlistofpossiblecompletionsorboth(ornone).
Second,youcansetthesourceofthesuggestionsanddrop-downlist.Thesourceisthelistofitemsthatareconsideredforcompletion.Youcancreateacustomsourceanddefineyourownlistofitemsoryoucansetvarioussystemsources.Therearetwopropertiesintheinterfacethatprovidesettingsforthecustomsource.Thefirstonesetsthelistofpossiblecandidatesforacustomsource.Thesecondsetswhethertofillthelistwiththelistofvaluesfromothercellsinthecolumn.Tousethevaluesinthecellsinthecolumn,forexample,youwouldsetthesourcetocustomandthenturnonautomaticfill.Theautomaticfillonlyaddsitemstothecustomsourceiftheyareaboveorbelowthecellwithoutablankcellinbetween.
Foranexampleofautomaticcompletion,refertothewebsiteathttp://www.componentone.com/SuperProducts/SpreadStudio/Demos/.
Forinformationonotherfeaturesofcelltypes,refertoUnderstandingAdditionalFeaturesofCellTypes.
Working with a SubEditor
Spread Windows Forms Developer’s Guide 390
Copyright © GrapeCity, Inc. All rights reserved.
Forseveraleditablecelltypes(theonesinWorkingwithEditableCellTypes),whenyouclickinsidethecell,aneditorisdisplayed.Youcangobeyondthissimplelineeditorandprovideacustomuserinterface(toprovideoptionstomakethetaskofuserinputeasier).Thisotherlevelofinterfaceiscontrolledbythesubeditor,ortheeditorwithinthecelleditor.Forexample,whenyouselectthedate-timecell,youcanprovideacalendarfortheusertoselectadate.Thiscalendarcontrolwouldbecalledbythesubeditor.
CreatingaSubeditor
Youcancreateyourownsubeditor,whichcanbedisplayedbythefollowingactions:
bypressingF4keybydouble-clickingcellsineditmodebypressingadrop-downbutton(whenDropDownButtonpropertyissettotrue)
Thestepsforcreatingyourownsubeditorare:
1. CreateanewFormclassforasubeditor.2. ImplementISubEditorinterfacetotheFormthatyouhavejustcreated.3. Setthesubeditor(SubEditorproperty)tothecaller.
Toseeanexampleofasubeditor,refertoCustomizingthePop-UpDate-TimeControlwherethecalendarsubeditorisavailableforadate-timecell,andCustomizingthePop-UpCalculatorControlwhereacalculatorsubeditorisavailableforseveralnumericcelltypes.
CancelingaSubeditor
Forseveraleditablecelltypes,whenyouclickinsidethecell,asubeditorisdisplayedbydefault.Butsometimesyoumightwanttodisablethesesubeditors.Forexample,indate-timecellsyoumightwanttodisablethepop-upcalendarcontrol;inthenumbercells,youmightwanttodisablethepop-upcalculatorcontrol.
Example
Tocancelsubeditors,youcansete.CanceltoTrueintheSubEditorOpening('SubEditorOpeningEvent'intheon-linedocumentation)event,asshowninthefollowingexample.
C#private void FpSpread1_SubEditorOpening(object sender, FarPoint.Win.Spread.SubEditorOpeningEventArgs e){ e.Cancel = true;}
VBPrivate Sub FpSpread1_SubEditorOpening(ByVal sender As Object, ByVal e As FarPoint.Win.Spread.SubEditorOpeningEventArgs) Handles FpSpread1.SubEditorOpening e.Cancel = TrueEnd Sub
Forinformationontheeditablecelltypes,refertoWorkingwithEditableCellTypes.
Forinformationonotherfeaturesofcelltypes,refertoUnderstandingAdditionalFeaturesofCellTypes.
Creating a Custom Cell Type
Youcanimplementyourowntypesofcellsbycreatingasubclassthatinheritsanexistingcelltype(thatis,overriding
Spread Windows Forms Developer’s Guide 391
Copyright © GrapeCity, Inc. All rights reserved.
eachmethodinthatclass).ThecustomcelltypeclassshouldbemarkedasserializableiftheClipboardwillbeusedwithitoriftheexporttoExcelmethodsareused.
Forinformationonotherfeaturesofcelltypes,refertoUnderstandingAdditionalFeaturesofCellTypes.
UsingCode
Thisexamplesubclassesthecheckboxcelltypetoillustratetheuseofthemethods.
C#class myCkBox : FarPoint.Win.Spread.CellType.CheckBoxCellType{CheckBox ckbx = new CheckBox();
public myCkBox(){}new event EventHandler EditingCanceled;new event EventHandler EditingStopped;
public override void StartEditing(EventArgs e, bool selectAll, bool autoClipboard){ return;}public override void CancelEditing(){ EditingCanceled(ckbx, EventArgs.Empty); base.FireEditingCanceled();}public override bool StopEditing(){ if (EditingStopped != null) { EditingStopped(ckbx, EventArgs.Empty); base.FireEditingStopped(); return true; } else { return false; }}
public override bool IsReservedKey(KeyEventArgs e){ return base.IsReservedKey(e);}public override object IsReservedLocation(Graphics g, int x, int y, Rectangle r,FarPoint.Win.Spread.Appearance appr, objectvalue, float zoom){ return base.IsReservedLocation(g, x, y, r, appr, value, zoom);}public override Size GetPreferredSize(Graphics g, Size size,FarPoint.Win.Spread.Appearance appr, object value, float zoom){ return base.GetPreferredSize(g, size, appr, value, zoom);
Spread Windows Forms Developer’s Guide 392
Copyright © GrapeCity, Inc. All rights reserved.
}public override object Parse(string s){ return base.Parse(s);}public override string Format(object o){ return base.Format(o.ToString());}public override Control GetEditorControl(FarPoint.Win.Spread.Appearance appearance,float zoomFactor){ return ckbx;}public override object GetEditorValue(){ return ckbx.CheckState;}public override void PaintCell(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearanceappr, object value, bool issel, boolislocked, float zoom){ GetEditorValue(); if (ckbx.CheckState == CheckState.Checked) { ControlPaint.DrawCheckBox(g, r.X, r.Y, r.Width - 40, r.Height - 6,ButtonState.Checked); } else if (ckbx.CheckState == CheckState.Unchecked) { ControlPaint.DrawCheckBox(g, r.X, r.Y, r.Width - 40, r.Height - 6,ButtonState.Normal); }}public override void SetEditorValue(object value){ ckbx.CheckState = CheckState.Checked;}public override Cursor GetReservedCursor(object o){ return base.GetReservedCursor(o);}}
private void menuItem4_Click(object sender, System.EventArgs e){ myCkBox ckbx = new myCkBox(); fpSpread1.ActiveSheet.Cells[0, 0].CellType = ckbx;}
VBPublic Class myCkBoxInherits FarPoint.Win.Spread.CellType.CheckBoxCellType
Dim ckbx As New CheckBox()
Spread Windows Forms Developer’s Guide 393
Copyright © GrapeCity, Inc. All rights reserved.
Sub New()
End Sub
Public Shadows Event EditingStopped(ByVal sender As Object, ByVal e As EventArgs)
Public Shadows Event EditingCancelled(ByVal sender As Object, ByVal e As EventArgs)
Public Overrides Sub StartEditing(ByVal e As EventArgs, ByVal selectAll As Boolean,ByVal autoClipboard As Boolean) MyBase.StartEditing(e, selectAll, autoClipboard)End Sub
Public Overrides Sub CancelEditing() RaiseEvent EditingCancelled(ckbx, EventArgs.Empty) MyBase.FireEditingCanceled()End Sub
Public Overrides Function StopEditing() As Boolean RaiseEvent EditingStopped(ckbx, EventArgs.Empty) MyBase.FireEditingStopped() Return TrueEnd Function
Public Overrides Function IsReservedKey(ByVal e As KeyEventArgs) As Boolean Return MyBase.IsReservedKey(e)End Function
Public Overrides Function IsReservedLocation(ByVal g As Graphics, ByVal x As Integer,ByVal y As Integer, ByVal r As Rectangle,ByVal appr As FarPoint.Win.Spread.Appearance, ByVal value As Object, ByVal zoom AsSingle) As Object Return MyBase.IsReservedLocation(g, x, y, r, appr, value, zoom)End Function
Public Overrides Function GetPreferredSize(ByVal g As Graphics, ByVal s As Size, ByValappr As FarPoint.Win.Spread.Appearance,ByVal value As Object, ByVal zoom As Single) As Size Return MyBase.GetPreferredSize(g, s, appr, value, zoom)End Function
Public Overrides Function Parse(ByVal s As String) As Object Return MyBase.Parse(s)End Function
Public Overrides Function Format(ByVal o As Object) As String Return MyBase.Format(o)End Function
Public Overrides Function GetEditorControl(ByVal appr AsFarPoint.Win.Spread.Appearance, ByVal zoom As Single) As Control Return ckbxEnd Function
Public Overrides Function GetEditorValue() As Object Return ckbx.CheckStateEnd Function
Spread Windows Forms Developer’s Guide 394
Copyright © GrapeCity, Inc. All rights reserved.
Public Overrides Sub PaintCell(ByVal g As Graphics, ByVal r As Rectangle, ByVal appr AsFarPoint.Win.Spread.Appearance, ByValValue As Object, ByVal issel As Boolean, ByVal islocked As Boolean, ByVal zoom AsSingle) GetEditorValue() If ckbx.CheckState = CheckState.Checked Then ControlPaint.DrawCheckBox(g, r.X, r.Y, r.Width - 40, r.Height - 6,ButtonState.Checked) ElseIf ckbx.CheckState = CheckState.Unchecked Then ControlPaint.DrawCheckBox(g, r.X, r.Y, r.Width - 40, r.Height - 6,ButtonState.Normal) End IfEnd Sub
Public Overrides Sub SetEditorValue(ByVal value As Object) ckbx.CheckState = CheckState.CheckedEnd Sub
Public Overrides Function GetReservedCursor(ByVal o As Object) As Cursor Return MyBase.GetReservedCursor(o)End FunctionEnd Class
Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles MenuItem1.Click Dim ckbx As New myCkBox() FpSpread1.ActiveSheet.Cells(0, 0).CellType = ckbxEnd Sub
Spread Windows Forms Developer’s Guide 395
Copyright © GrapeCity, Inc. All rights reserved.
Customizing Interaction in Cells
YoucancustomizevariousaspectsofuserinteractionintheSpreadcomponent.Thetasksthatrelatetocustomizingtheuserinteractionwiththespreadsheetinclude:
UsingEditModeandFocusUsingDragOperationstoFillCellsUsingVisibleIndicatorsintheCellUsingConditionalFormattingofCellsUsingValidationinCells(on-linedocumentation)ManagingFormulasinCellsUsingtheAdditionalSpreadControls
Youcancustomizewhatyouallowtheusertodo.Thereareseveralfeaturesthatarecoveredinvarioustopicsinthissection,buttheyaresummarizedinonetopicforeasyreferenceinAllowingUserFunctionality.
Youcanalsodeterminehowtheuserinteractsbasedonthecelltype.RefertoCustomizingInteractionwithCellTypes.
Youcanalsodeterminehowtheuserinteractswiththekeyboard.RefertoManagingKeyboardInteraction.
Using Edit Mode and Focus
Importantaspectsofworkingwithcells,andwithuserinteractionatacelllevel,includetheuseofeditmodeandfocus.Thefollowingtopicsdescribehowyoucancustomizeinteractionincludingeditmodeandfocus:
UnderstandingEditModeinaCellLockingaCellAllowingtheDisplayofButtonsinaCellCustomizingtheFocusIndicatorforaCell
Understanding Edit Mode in a Cell
Typically,whentheenduserdouble-clicksinthecell,theeditorcontrolismadeavailableandtheusercantypeinthecell.Thisabilitytoeditinacelliscallededitmode.Severalpropertiesandmethodscancustomizetheuseofeditmode.
Whenthecellisineditmode,theactivecelltypicallydisplaysaflashingI-beamcursor,asshowninthefigurebelow.Whenthecellisnotineditmode,theactivecelltypicallydisplaysafocusrectangle,alsoasshown.
Cellineditmode Cellselectedbutnotineditmode
Acellenterseditmode(editmodeisturnedon)when
theuserstartstypinginthecelltheuserdouble-clicksthecelltheEditMode('EditModeProperty'intheon-linedocumentation)propertyissettotrue
Acellleaveseditmode(editmodeisturnedoff)when
theuserpressestheEnterkeytheusermakesanothercelltheactivecell
Spread Windows Forms Developer’s Guide 396
Copyright © GrapeCity, Inc. All rights reserved.
theapplicationlosesthefocustheEditMode('EditModeProperty'intheon-linedocumentation)propertyissettofalse
Whenacellenterseditmode,bydefaultthecursorispositionedattheendoftheexistingtextinthecell.YoucanchangeittoselecttheexistingtextinthecellbysettingtheEditModeReplace('EditModeReplaceProperty'intheon-linedocumentation)property.
Ifyouprefer,youcanspecifythatacellisalwaysineditmodewhenitbecomestheactivecellusingtheEditModePermanent('EditModePermanentProperty'intheon-linedocumentation)property.
Whenacellenterseditmode,theEditModeOn('EditModeOnEvent'intheon-linedocumentation)eventoccurs;whenacellleaveseditmode,theEditModeOff('EditModeOffEvent'intheon-linedocumentation)eventoccurs.
YoucansetthepositionofthecursorintheeditcontrolwhenitreceivesthefocusbyusingtheSuperEditBase.EditModeCursorPositionproperty.
YoucanstartandstopeditmodebyusingtheStartCellEditing('StartCellEditingMethod'intheon-linedocumentation)andStopCellEditing('StopCellEditingMethod'intheon-linedocumentation)methods.
YoucankeepthecellalignmentwheneditingwiththeAllowEditorVerticalAlign('AllowEditorVerticalAlignProperty'intheon-linedocumentation)property.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. InthePropertieswindow,selecttheEditModePermanentorEditModeReplaceproperties.
UsingtheSpreadDesigner
1. SelecttheSettingsmenu.2. SelecttheEditoption(SpreadSettingssection).3. ChecktheCellsAlwaysinEditModeoptionforEditModePermanentorEditingReplacesExistingText
forEditModeReplace.4. UsetheFilemenu,thenApplyandExittosavethechanges.
Locking a Cell
Youcanlockacellorrangeofcellsandmakeitunavailableforeditingbytheenduser.Youcanmaketheappearanceoflockedcellsdifferentsothatthelockedcellsarenoticeablebytheuser.
YoucanlockcellsusingtheLocked('LockedProperty'intheon-linedocumentation)propertyintheCell('CellClass'intheon-linedocumentation),Column('ColumnClass'intheon-linedocumentation),Row('RowClass'intheon-linedocumentation),orAlternatingRow('AlternatingRowClass'intheon-linedocumentation)objects.YoucanalsosettheLocked('LockedProperty'intheon-linedocumentation)propertyfortheStyleInfo('StyleInfoClass'intheon-linedocumentation)objectandapplythatstyletothecellsyouwantlocked.YoualsoneedtosettheProtect('ProtectProperty'intheon-linedocumentation)propertyoftheSheetView('SheetViewClass'intheon-linedocumentation)objecttolockthecells.TheLockedpropertymarksthecellstobelocked,andtheProtectpropertysetswhethertolockthosecells.Forcellsmarkedaslockedtobelockedfromuserinput,theProtect('ProtectProperty'intheon-linedocumentation)propertyofthesheetmustbesettoTrue,whichisitsdefaultvalue.IfitissettoFalse,theusercanstillinteractwiththecells.
Anotherwaytolockcellsistomakethemtextcells(usingtheTextCellType('TextCellTypeClass'intheon-linedocumentation))andsettheReadOnlyproperty.Thismakesthecellsnon-editable.
Youcanalsospecifyadifferentcolor(forbackgroundorfortext)orfontinlockedcellsusingtheLockBackColor('LockBackColorProperty'intheon-linedocumentation),LockForeColor('LockForeColorProperty'in
Spread Windows Forms Developer’s Guide 397
Copyright © GrapeCity, Inc. All rights reserved.
theon-linedocumentation),andLockFont('LockFontProperty'intheon-linedocumentation)propertiesoftheSheetView('SheetViewClass'intheon-linedocumentation),Appearance('AppearanceClass'intheon-linedocumentation),Cell('CellClass'intheon-linedocumentation),Column('ColumnClass'intheon-linedocumentation),Row('RowClass'intheon-linedocumentation),NamedStyle('NamedStyleClass'intheon-linedocumentation),orStyleInfo('StyleInfoClass'intheon-linedocumentation)objects.
Lockingacelldoesnotlockanyshapes(floatingobjects)overthatcell.Aprotectedsheetonlymeansthatallthecellsinthatsheetmarkedaslockedarelocked;itdoesnotapplytoshapesoverthatsheet.Forlockingshapes,refertoCustomizingDrawing.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. InthePropertieswindowontherightsideoftheSheetViewCollectionEditor,selecttheCellspropertyfor
thesheet.5. ClickthebuttontodisplaytheCell,Column,andRowEditor.6. Intheeditor,selectthecellstomarkaslocked.7. SelecttheLockedpropertyandsetthevaluetoTrue.8. Ifyouwanttoapplythischange,clickApply.9. ClickOKtoclosetheCell,Column,andRoweditor.10. InthePropertieswindowontherightsideoftheSheetViewCollectionEditor,intheBehaviorgroup,
selecttheProtectpropertyandsetittoTrueifyouwantthecellstobelockedfromuserinput.11. ClickOKtoclosetheSheetViewCollectionEditor.
UsingCode
1. SettheLocked('LockedProperty'intheon-linedocumentation)propertyfortheCell('CellClass'intheon-linedocumentation)object(orRow('RowClass'intheon-linedocumentation)orColumn('ColumnClass'intheon-linedocumentation)objectforallthecellsinthatroworcolumn)tomarksomecellsaslocked.
2. SettheProtect('ProtectProperty'intheon-linedocumentation)propertyforthesheet(SheetView('SheetViewClass'intheon-linedocumentation)object)toTrueifyouwantthecellsthataremarkedaslockedinthatsheettobelockedfromuserinput.
Example
MakingsurethattheProtect('ProtectProperty'intheon-linedocumentation)propertyistrueforthesheet,youcanlockspecifiedcolumnsofcellsandthenunlocksomeofthecellsinonerow,asshowninthefollowingexample.
C#fpSpread1.ActiveSheet.Protect = true;fpSpread1.ActiveSheet.LockBackColor = Color.LightCyan;fpSpread1.ActiveSheet.LockForeColor = Color.Green;FarPoint.Win.Spread.Column columnobj;columnobj = fpSpread1.ActiveSheet.Columns[0, 3];columnobj.Locked = true;FarPoint.Win.Spread.Cell cellobj;cellobj = fpSpread1.ActiveSheet.Cells[1,1,1,2];cellobj.Locked = false;fpSpread1.ActiveSheet.Cells[1,0,1,4].Text = "First Five";
Spread Windows Forms Developer’s Guide 398
Copyright © GrapeCity, Inc. All rights reserved.
VBFpSpread1.ActiveSheet.Protect = TrueFpSpread1.ActiveSheet.LockBackColor = Color.LightCyanFpSpread1.ActiveSheet.LockForeColor = Color.GreenDim columnobj As FarPoint.Win.Spread.Columncolumnobj = fpSpread1.ActiveSheet.Columns(0, 3)columnobj.Locked = TrueDim cellobj As FarPoint.Win.Spread.Cellcellobj = fpSpread1.ActiveSheet.Cells(1,1,1,2)cellobj.Locked = FalseFpSpread1.ActiveSheet.Cells(1,0,1,4).Text = "First Five"
UsingaShortcut
1. SettheLocked('LockedProperty'intheon-linedocumentation)propertyfortheCellsshortcut(orRowsorColumnsshortcutforallthecellsinthatroworcolumn)tomarksomecellsaslocked.
2. SettheProtect('ProtectProperty'intheon-linedocumentation)propertyfortheSheetsshortcuttoTrueifyouwantthecellsthataremarkedaslockedinthatsheettobelockedfromuserinput.
Example
MakingsurethattheProtectpropertyisTrueforthesheet,youcanlockspecificcolumnsofcellsandthenunlocksomeofthecellsinonerow,asshowninthefollowingexample.
C#fpSpread1.ActiveSheet.Protect = true;fpSpread1.ActiveSheet.LockBackColor = Color.LightCyan;fpSpread1.ActiveSheet.LockForeColor = Color.Green;fpSpread1.ActiveSheet.Columns[0, 3].Locked = true;fpSpread1.ActiveSheet.Cells[1,1,1,2].Locked = false;
VBFpSpread1.ActiveSheet.Protect = TrueFpSpread1.ActiveSheet.LockBackColor = Color.LightCyanFpSpread1.ActiveSheet.LockForeColor = Color.GreenFpSpread1.ActiveSheet.Columns(0, 3).Locked = TrueFpSpread1.ActiveSheet.Cells(1,1,1,2).Locked = False
UsingtheSpreadDesigner
1. Intheworkarea,selectthecellorcellsforwhichyouwanttolockthecellseitherbydraggingoverarangeofcellsorselectingroworcolumnheaders(forentirerowsorcolumns).(AnotherwayofdoingthisistoselecttheCellsproperty,clickonthebuttontocalluptheCell,Column,andRoweditor,andselectthecellsinthateditor.)
2. Inthepropertieslist(intheMiscgroup),selecttheLockedpropertyandchooseTrue.3. Clickthesheetnametabforthesheetthatcontainsthecells.Fromthepropertieslist(intheBehaviorcategory),
selecttheProtectpropertybuttontodisplaytheSheetViewCollectionEditor.4. InthePropertieswindowintheSheetViewCollectionEditor,intheBehaviorgroup,selecttheProtect
propertyandsetittoTrueifyouwantthecellstobelockedfromuserinput.5. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Spread Windows Forms Developer’s Guide 399
Copyright © GrapeCity, Inc. All rights reserved.
Allowing the Display of Buttons in a Cell
Youcanalloworrestrictthedisplayofbuttonsincellsthatarethespecificgraphicalcelltypesthatallowbuttons.UsetheFpSpreadButtonDrawMode('ButtonDrawModeProperty'intheon-linedocumentation)propertytosetthelimitsonwherebuttonscanbedisplayed.Theserefertoprimarybuttons,suchasthosefoundinthesecelltypes:
buttoncells(ButtonCellType('ButtonCellTypeClass'intheon-linedocumentation))checkboxcells(CheckBoxCellType('CheckBoxCellTypeClass'intheon-linedocumentation))hyperlinkcells,(HyperLinkCellType('HyperLinkCellTypeClass'intheon-linedocumentation))multiple-optionbuttoncells(MultiOptionCellType('MultiOptionCellTypeClass'intheon-linedocumentation))
Secondarybuttonsrefertothosebuttonsinthecellthatarepartofthecontrolthatallowyoutochangevaluesinthecell,suchasthespinbuttonsorthedrop-downarrowinacombobox.
Formoredetailsonpossiblesettings,refertotheButtonDrawModes('ButtonDrawModesEnumeration'intheon-linedocumentation)enumeration.
Fordetailsonsettingthedisplayofprimaryandsecondarybuttonsaspartofacell’sappearance,seetheAppearance('AppearanceClass'intheon-linedocumentation)classDrawPrimaryButton('DrawPrimaryButtonProperty'intheon-linedocumentation)propertyandDrawSecondaryButton('DrawSecondaryButtonProperty'intheon-linedocumentation)property.
YoucanalsomakeuseoftheFpSpreadButtonClicked('ButtonClickedEvent'intheon-linedocumentation)event.
Formoreinformationaboutcelltypesthatallowbuttonstobedrawninacell,refertoWorkingwithGraphicalCellTypes.Formoreinformationaboutcelltypesthatcandisplayspinbuttons,seeDisplayingSpinButtons.
Customizing the Focus Indicator for a Cell
Thefocusrectangleindicatestotheendusertheselectedandactivecell.Bydefault,whenacellisselectedthecellhasasolidfocusrectangleasshowninthefigurebelow.Ifanentirecolumn(orrow)isselected,thecolumn(orrow)ishighlighted,alsoasshown.Thecolumnandrowheaderoftheactivecellalsohaveadifferentbackgroundcolor.
Focusindicatorforselectedindividualcell Focusindicatorforselectedcolumn
YoucancustomizethefocusindicatorfortheactivecellbyusingtheFocusRenderer('FocusRendererProperty'intheon-linedocumentation)propertyoftheSpreadcomponent(whichusestheIFocusIndicatorRenderer('IFocusIndicatorRendererInterface'intheon-linedocumentation)interface).Foranimatedindicators,youneedtheIAnimatedFocusIndicatorRenderer('IAnimatedFocusIndicatorRendererInterface'intheon-linedocumentation)interface.Youcanalsochangetheselectedbackgroundcoloroftheactivecellheaders.
Thistablesummarizedthetypesoffocusindicatorsandtheclassesthatcorrespondtothem.
Type ClassDefault DefaultFocusIndicatorRenderer('DefaultFocusIndicatorRendererClass'intheon-line
documentation)
Spread Windows Forms Developer’s Guide 400
Copyright © GrapeCity, Inc. All rights reserved.
Animated AnimatedDefaultFocusIndicatorRenderer('AnimatedDefaultFocusIndicatorRendererClass'intheon-linedocumentation)
CustomLine
CustomFocusIndicatorRenderer('CustomFocusIndicatorRendererClass'intheon-linedocumentation)
Editing EditingFocusIndicatorRenderer('EditingFocusIndicatorRendererClass'intheon-linedocumentation)
Enhanced EnhancedFocusIndicatorRenderer('EnhancedFocusIndicatorRendererClass'intheon-linedocumentation)
Image ImageFocusIndicatorRenderer('ImageFocusIndicatorRendererClass'intheon-linedocumentation)
MarqueeLine
MarqueeFocusIndicatorRenderer('MarqueeFocusIndicatorRendererClass'intheon-linedocumentation)
SolidLine
SolidFocusIndicatorRenderer('SolidFocusIndicatorRendererClass'intheon-linedocumentation)
Flat FlatFocusIndicatorRenderer('FlatFocusIndicatorRendererClass'intheon-linedocumentation)
TheDefaultFocusIndicatorRenderer('DefaultFocusIndicatorRendererClass'intheon-linedocumentation)isthebaseclassfortheothers.TheImageFocusIndicatorRenderer('ImageFocusIndicatorRendererClass'intheon-linedocumentation)allowsyoutouseanimageasthefocusindicator.TheSolidFocusIndicatorRenderer('SolidFocusIndicatorRendererClass'intheon-linedocumentation)allowsyoutocustomizeasolidborderaroundtheselectedcellasafocusindicator.
IntheSpreadDesigner,youcancustomizethefocusindicatorwiththeFocusIndicatorEditor.FormoreinformationaboutusingtheSpreadDesigner,refertotheFocusIndicatorEditor(on-linedocumentation)topicintheSpreadDesignerGuide.
UsingCode
UsetheIFocusIndicatorRenderer('IFocusIndicatorRendererInterface'intheon-linedocumentation)interfacetocreatecustomindicatorsfortheactivecell.
Example
Thisexamplecreatesacustomfocusindicatorfortheactivecell.
C#FarPoint.Win.Spread.SolidFocusIndicatorRenderer sfir =new FarPoint.Win.Spread.SolidFocusIndicatorRenderer(Color.Blue, 2);fpSpread1.FocusRenderer = sfir;// Create a custom indicator.public class MyIndicator : FarPoint.Win.Spread.IFocusIndicatorRenderer{public void Paint(System.Drawing.Graphics g, int x, int y, int width, int height, bool left, bool top, bool right, bool bottom){SolidBrush r = new SolidBrush(System.Drawing.Color.Red);SolidBrush b = new SolidBrush(System.Drawing.Color.Blue);SolidBrush gr = new SolidBrush(System.Drawing.Color.DarkGreen);g.FillRectangle(r, x, y, 1, height);g.FillRectangle(gr, x, y, width, 1);g.FillRectangle(r, x + width - 1, y, 1, height);g.FillRectangle(b, x, y + height - 1, width, 1);
Spread Windows Forms Developer’s Guide 401
Copyright © GrapeCity, Inc. All rights reserved.
}}
fpSpread1.FocusRenderer = new MyIndicator();
VBDim sfir As New FarPoint.Win.Spread.SolidFocusIndicatorRenderer(Color.Blue, 2)FpSpread1.FocusRenderer = sfir' Create a custom indicatorPublic Class MyIndicatorImplements FarPoint.Win.Spread.IFocusIndicatorRendererPublic Sub Paint(ByVal g As System.Drawing.Graphics, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal left As Boolean, ByVal top As Boolean, ByVal right As Boolean, ByVal bottom As Boolean) Implements FarPoint.Win.Spread.IFocusIndicatorRenderer.PaintDim r As New SolidBrush(Color.Red)Dim b As New SolidBrush(Color.Blue)Dim gr As New SolidBrush(Color.DarkGreen)g.FillRectangle(r, x, y, 1, height)g.FillRectangle(gr, x, y, width, 1)g.FillRectangle(r, x + width - 1, y, 1, height)g.FillRectangle(b, x, y + height - 1, width, 1)End SubEnd Class
FpSpread1.FocusRenderer = New MyIndicator()
UsingtheSpreadDesigner
1. SelecttheFormatmenuoption.2. ChoosetheFocusIndicatorEditormenu.3. MakechangestothedialogandselectOK.
UsingCode
UsetheSelectedBackgroundColor('SelectedBackgroundColorProperty'intheon-linedocumentation)propertyoftheEnhancedColumnHeaderRenderer(orrow)tosettheheaderbackcoloroftheactivecell.
Example
Thisexamplechangestheheaderbackgroundcolorfortheactivecell.
C#FarPoint.Win.Spread.CellType.EnhancedColumnHeaderRenderer testing = new FarPoint.Win.Spread.CellType.EnhancedColumnHeaderRenderer();testing.SelectedBackgroundColor = Color.MediumTurquoise;FarPoint.Win.Spread.CellType.EnhancedRowHeaderRenderer testing1 = new FarPoint.Win.Spread.CellType.EnhancedRowHeaderRenderer();testing1.SelectedBackgroundColor = Color.MediumTurquoise;fpSpread1.Sheets[0].ColumnHeader.DefaultStyle.Renderer = testing;fpSpread1.Sheets[0].RowHeader.DefaultStyle.Renderer = testing1;
VB
Spread Windows Forms Developer’s Guide 402
Copyright © GrapeCity, Inc. All rights reserved.
Dim testing as New FarPoint.Win.Spread.CellType.EnhancedColumnHeaderRenderertesting.SelectedBackgroundColor = Color.MediumTurquoiseDim testing1 as New FarPoint.Win.Spread.CellType.EnhancedRowHeaderRenderertesting1.SelectedBackgroundColor = Color.MediumTurquoiseFpSpread1.Sheets(0).ColumnHeader.DefaultStyle.Renderer = testingFpSpread1.Sheets(0).RowHeader.DefaultStyle.Renderer = testing1
Using Drag Operations to Fill Cells
Youcanfillcellswithanyofseveraloperationsthatinvolvedraggingoversomecells.Thedragoperations,whichcancopyandmovethecontentaswellastheformatting,include:
FillingCellswithDragandDropFillingCellswithDragandFillFillingCellswithDragandMove
Filling Cells with Drag and Drop
Youcanallowtheendusertodrag-and-dropdatafromonerangeofcellstoanother.YoucanspecifywhethertheusercanselectacellorrangeofcellsanddraganddropthemtoanewlocationinthesamespreadsheetoranotherspreadsheetintheSpreadcomponent.Whenthemousebuttonisreleasedandtherangeofcellsisdropped,theDragDropBlock('DragDropBlockEvent'intheon-linedocumentation)eventoccurs.
Formoreinformation,refertotheAllowDragDrop('AllowDragDropProperty'intheon-linedocumentation)propertyintheFpSpread('FpSpreadClass'intheon-linedocumentation)class.Formoreinformationoneventarguments,refertoDragDropBlock('DragDropBlockEvent'intheon-linedocumentation)event,DragDropBlockEventArgs('DragDropBlockEventArgsClass'intheon-linedocumentation),andDragDropBlockCompletedEventArgs('DragDropBlockCompletedEventArgsClass'intheon-linedocumentation).
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. Select(intheBehaviorcategory)theAllowDragDropproperty.3. SelectTruefromthedrop-downlisttoallowdrag-and-dropfeature,orselectFalsetoprohibitit.
UsingaShortcut
Allowthedrag-and-dropfeaturebysettingtheAllowDragDrop('AllowDragDropProperty'intheon-linedocumentation)propertyfortheFpSpread('FpSpreadClass'intheon-linedocumentation)component.
Example
Thisexamplecodesetsthecomponenttoallowthedrag-dropfeature.
C#fpSpread1.AllowDragDrop = true;
VBFpSpread1.AllowDragDrop = True
UsingCode
Spread Windows Forms Developer’s Guide 403
Copyright © GrapeCity, Inc. All rights reserved.
Allowthedrag-and-dropfeaturebysettingtheAllowDragDrop('AllowDragDropProperty'intheon-linedocumentation)propertyoftheFpSpread('FpSpreadClass'intheon-linedocumentation)component.
Example
Thisexamplecodesetsthechildsheettoallowthedrag-dropfeature.
C#FarPoint.Win.Spread.SpreadView sv = fpSpread1.GetRootWorkbook();sv.AllowDragDrop = true;
VBDim sv As FarPoint.Win.Spread.SpreadView = FpSpread1.GetRootWorkbooksv.AllowDragDrop = True
UsingtheSpreadDesigner
1. FromtheSettingsmenu,selectGeneral(SpreadSettingssection).2. IntheGeneraltab,selectthesettingsforthedraganddroppropertiesasneeded.3. ClickOK.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
or
1. SelecttheSpreadcomponent(orselectSpreadfromthepull-downmenu).2. Inthepropertylistforthecomponent(intheBehaviorcategory),selecttheAllowDragDropproperty.3. Clickthedrop-downarrowtodisplaythechoicesandselectTrue.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Filling Cells with Drag and Fill
Youcanalsoallowtheendusertodrag-and-filldatafromonecellorarangeofcellstoanothercellorrangeofcells.Withacellorrangeofcellsselected,youcanfillothercellseitherinarow(orrowsifmorethanonecolumnisselected)oracolumn(orcolumnsifmorethanonerowisselected).
Inordertofillcellswithdragandfill,theAllowDragFill('AllowDragFillProperty'intheon-linedocumentation)propertyintheFpSpread('FpSpreadClass'intheon-linedocumentation)classmustbesettotrue.Inordertoshowthedragfillbuttonandthedragfillcontextmenu,theEnableDragFillMenu('EnableDragFillMenuProperty'intheon-linedocumentation)propertymustbesettotrue.
YoucanalsospecifythetypeoffillyouwantbyusingtheRangeDragFillMode('RangeDragFillModeProperty'intheon-linedocumentation)propertythatallowsyoutochoosefromthefollowingoptionsinthedragfilldropdowncontextmenuiconthatappearsonyourscreen:
1. CopyCells2. FillSeries3. FillFormattingOnly4. FillWithoutFormatting
TheCopyCellsoptioncopiesthedatatotheselectedrange.TheFillSeriesoptionincrementsordecrementsthevaluesbasedontheseries.Dragdownortotherighttoincrementthevalues.Draguportothelefttodecrementthevalues.Spreadusesthedatamodeltodeterminewhetherthedatacanbeincrementedwhenusingtheseriesfill.Thedisplayedvalueshaveahigherprioritywiththebuilt-incelltypeswhenusingtheseriesfill.TheFillFormattingOnlyoptionand
Spread Windows Forms Developer’s Guide 404
Copyright © GrapeCity, Inc. All rights reserved.
theFillWithoutFormattingoptionallowsyoutofillcellswithorwithoutthesameformattingasintheoriginallyselectedcell.
TheAutoFilloptionsthatareavailableintheDragFillcontextmenudependsonthetypeofselecteddataandtheDragFillDataOnly('DragFillDataOnlyProperty'intheon-linedocumentation)property.
Theexampleshownbelowdepictsthedragandfilloperationthatusesthecopyoptiontofillseveralcellsinacolumn.
Spread Windows Forms Developer’s Guide 405
Copyright © GrapeCity, Inc. All rights reserved.
Thefollowingexampleusesthefillseriesoption.
YoucancustomizethedirectionofthefillusingtheFillDirection('FillDirectionEnumeration'intheon-linedocumentation)enumeration.
Formoreinformationoneventarguments,refertoDragFillBlock('DragFillBlockEvent'intheon-linedocumentation)event,DragFillBlockEventArgs('DragFillBlockEventArgsClass'intheon-linedocumentation),andDragFillBlockCompletedEventArgs('DragFillBlockCompletedEventArgsClass'intheon-linedocumentation).
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. Select(intheBehaviorcategory)theAllowDragFillproperty.3. SelectTruefromthedrop-downlisttoallowdrag-and-fillfeature,orselectFalsetoprohibitit.4. SelecttheEnableDragFillMenuproperty.5. SelectTruefromthedrop-downlisttoallowthedragfillbuttonanddragfillcontextmenu,orselectFalsetoprohibitit.
UsingaShortcut
Allowthedrag-and-fillfeaturebysettingtheAllowDragFill('AllowDragFillProperty'intheon-linedocumentation)propertyintheFpSpread('FpSpreadClass'intheon-linedocumentation)component.
AllowthedragfillbuttonanddragfillcontextmenubysettingtheEnableDragFillMenu('EnableDragFillMenuProperty'intheon-linedocumentation)propertyintheFpSpread('FpSpreadClass'intheon-linedocumentation)component.
Example
Thisexamplecodesetsthecomponenttoallowthedrag-fillfeature,dragfillbuttonandthedragfillcontextmenu.
C#fpSpread1.AllowDragFill = true;fpSpread1.EnableDragFillMenu = true;
Spread Windows Forms Developer’s Guide 406
Copyright © GrapeCity, Inc. All rights reserved.
VBFpSpread1.AllowDragFill = TruefpSpread1.EnableDragFillMenu = True
UsingCode
AllowthedragfillfeaturebysettingtheAllowDragFill('AllowDragFillProperty'intheon-linedocumentation)propertyintheFpSpread('FpSpreadClass'intheon-linedocumentation)component.
AllowthedragfillbuttonanddragfillcontextmenubysettingtheEnableDragFillMenu('EnableDragFillMenuProperty'intheon-linedocumentation)propertyintheFpSpread('FpSpreadClass'intheon-linedocumentation)component.
Example
Thisexamplecodesetsthechildsheettoallowthedragfillfeature,dragfillbuttonandthedragfillcontextmenu.
C#// To enable Drag Fill operationfpSpread1.ActiveSheet.Reset(); fpSpread1.DragFillDataOnly = false;fpSpread1.AllowDragFill = true;fpSpread1.EnableDragFillMenu = true;this.fpSpread1.ActiveSheet.Cells[0, 0].Value = "A001";this.fpSpread1.ActiveSheet.Cells[0, 1].Value = DateTime.Today;this.fpSpread1.ActiveSheet.Cells[0, 3].Text = "Monday";
VB' To enable Drag Fill operationfpSpread1.ActiveSheet.Reset()fpSpread1.DragFillDataOnly = FalsefpSpread1.AllowDragFill = TruefpSpread1.EnableDragFillMenu = TrueMe.fpSpread1.ActiveSheet.Cells(0, 0).Value = "A001"Me.fpSpread1.ActiveSheet.Cells(0, 1).Value = DateTime.TodayMe.fpSpread1.ActiveSheet.Cells(0, 3).Text = "Monday"
UsingtheSpreadDesigner
1. SelecttheSpreadcomponent(orselectSpreadfromthepull-downmenu).2. Inthepropertylistforthecomponent(intheBehaviorcategory),selecttheAllowDragFillproperty.3. Clickthedrop-downarrowtodisplaythechoicesandselectTrue.4. Inthepropertylistforthecomponent,selecttheEnableDragFillMenuproperty.5. Clickthedrop-downarrowtodisplaythechoicesandselectTrue.6. FromtheFilemenu,chooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Note:IftheDragFillDataOnlypropertyissettofalseandtheselecteddatacanbefilledasseries,alltheoptionswillappearinthecontextmenu.IftheRangeDragFillModepropertyissettoSeries,thenthecontextmenuwillshowonlytheFillSeriesoptionandifitissettoCopy,thenthecontextmenuwillshowonlytheCopyCellsoption.Iftheselecteddatacannotbefilledasseries,thecontextmenuwillshowonlythreeoptions:CopyCells,FillFormatting
Spread Windows Forms Developer’s Guide 407
Copyright © GrapeCity, Inc. All rights reserved.
Only,FillWithoutFormatting.
IftheDragFillDataOnlypropertyissettotrueandtheselecteddatacanbefilledasseries,thecontextmenuwillshowonlytwooptions:CopyCellsandFillSeries.IftheRangeDragFillModepropertyissettoSeries,thenthecontextmenuwillshowonlytheFillSeriesoptionandifitissettoCopy,thenthecontextmenuwillshowonlytheCopyCellsoption.Iftheselecteddatacannotbefilledasseries,thecontextmenuwillshowonlyoneoption:CopyCells.
Filling Cells with Drag and Move
Youcandragandmoveentirerowsorcolumnsofcellswithinagivensheet.
Formoreinformation,refertotheAllowingtheUsertoMoveRowsorColumns.
Formoreinformationoneventarguments,refertoDragMoveEventArgs('DragMoveEventArgsClass'intheon-linedocumentation)andDragMoveCompletedEventArgs('DragMoveCompletedEventArgsClass'intheon-linedocumentation).
Using Visible Indicators in the Cell
Youcancustomizetheuserinteractionwithindividualcells(orarangeofcells).Tocustomizethisaspectofuserinteraction,youcanperformthefollowingtasks:
DisplayingTextTipsinaCellAddingaNotetoaCellPreventingaCellfromReceivingFocusReturningInformationforaClickedCellDisplayingErrorIconsinCellsorRows
Aswithmostspreadsheets,Spreaddoesnotallowin-celleditingofthecellsintherowandcolumnheaders.
Formoreinformationaboutcellsandsheetinteractions,refertothefollowingtopics:
Description RefertoForinformationonaddingaformulatoacell PlacingaFormulainCells
Forinformationonallowingausertoenteraformulainacell AllowingtheUsertoEnterFormulas
Forinformationonhowtochangetheappearanceofcells CustomizingtheAppearanceofaCell
Forinformationonsettingthecelltype CustomizingInteractionwithCellTypes
Forinformationaboutcustomizingfocusindicators CustomizingtheFocusIndicatorforaCell
Forinformationoncustomizingtheinteractionatasheetlevel CustomizingInteractionwithaSheet
Displaying Text Tips in a Cell
Forcellsthataretoosmalltodisplayallthetextinthecell,youcanallowtheendusertoseethecontentsinatexttip.Youcansetthepolicyandlocationfortexttipsforacellorrangeofcells.Texttipscanbedisplayedfordatacellsorheadercells.Whenthepointerisoversuchacell,thetexttipdisplays.
Spread Windows Forms Developer’s Guide 408
Copyright © GrapeCity, Inc. All rights reserved.
Todisplayatexttipoveracomboboxcell,youwouldneedtoturnchangethedefaultbehavior.Bydefault,thecomboboxcellcapturesthemousewhenmovingoverthecell,soitcangointoeditmodeonthefirstclickanddrop-downthelist.Youcaneitherturnoffthisbehavior,bysettingtheEditable('EditableProperty'intheon-linedocumentation)propertytoTrueoryoucancreateacustomcelltypeandoverridetheIsReservedLocationmethodtoreturnnothingforthepartsofthecellthatyouwantthetexttiptoshowoverandreturnaninstanceofthecelltypeinthepartsofthecellforwhichyouwanttheclicktoopenthelist.
FormoreinformationrefertotheTextTipAppearance('TextTipAppearanceProperty'intheon-linedocumentation)property,TextTipDelay('TextTipDelayProperty'intheon-linedocumentation)property,andTextTipPolicy('TextTipPolicyProperty'intheon-linedocumentation)property.
ReferalsototheTextTipFetchEventArgs('TextTipFetchEventArgsClass'intheon-linedocumentation)classandtheTextTipFetch('TextTipFetchEvent'intheon-linedocumentation)eventandOnTextTipFetch('OnTextTipFetchMethod'intheon-linedocumentation)method.
Forinformationonscrollbartips,refertothesectiononsettingscrollbartipsinCustomizingtheScrollBarsoftheComponent.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. Select(intheBehaviorgroup)theTextTipPolicyproperty.3. Clickthedrop-downarrowtodisplaythechoicesandchooseavalue.4. Ifyouwanttosetthedelay,selecttheTextTipDelaypropertyandtypeinavalue.
UsingCode
1. SettheTextTipPolicy('TextTipPolicyProperty'intheon-linedocumentation)propertyfortheSpreadcomponent.
2. Ifyouwanttosetadelay,settheTextTipDelay('TextTipDelayProperty'intheon-linedocumentation)property.
Example
Thisexamplecreatesanewcontrol,setswhethertodisplaytexttips,thelocationofthetips,andhowlongtowaitbeforethetexttipisshown.
C#FarPoint.Win.Spread.FpSpread fpSpread1 = new FarPoint.Win.Spread.FpSpread();FarPoint.Win.Spread.SheetView shv = new FarPoint.Win.Spread.SheetView();fpSpread1.Location = new Point(10, 10);fpSpread1.Height = 200;fpSpread1.Width = 400;Controls.Add(fpSpread1);fpSpread1.Sheets.Add(shv);fpSpread1.ActiveSheet.SetValue(0, 0, "TestTextTip");fpSpread1.TextTipPolicy = FarPoint.Win.Spread.TextTipPolicy.Floating;fpSpread1.TextTipDelay = 1000;MessageBox.Show("Place the pointer over the text to see the text tip.", "", MessageBoxButtons.OK);
Spread Windows Forms Developer’s Guide 409
Copyright © GrapeCity, Inc. All rights reserved.
VBDim FpSpread1 As New FarPoint.Win.Spread.FpSpread()Dim shv As New FarPoint.Win.Spread.SheetView()FpSpread1.Location = New Point(10, 10)FpSpread1.Height = 200FpSpread1.Width = 400Controls.Add(fpSpread1)FpSpread1.Sheets.Add(shv)FpSpread1.ActiveSheet.SetValue(0, 0, "TestTextTip")FpSpread1.TextTipPolicy = FarPoint.Win.Spread.TextTipPolicy.FloatingFpSpread1.TextTipDelay = 1000MessageBox.Show("Place the pointer over the text to see the text tip.", "", MessageBoxButtons.OK)
UsingtheSpreadDesigner
1. SelecttheSpreadcomponent(orselectSpreadfromthepull-downmenu).2. Inthepropertylist,intheBehaviorcategory,selecttheTextTipPolicyproperty.3. Clickthedrop-downarrowtodisplaythechoicesandchooseavalue.4. Ifyouwanttosetthedelay,selecttheTextTipDelaypropertyandtypeinavalue.5. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Adding a Note to a Cell
Youcanaddanotetoacellorrangeofcells.Thenotemaycontaintextsuchasacomment,aquestion,ordocumentationdescribingtheoriginofthecell'svalue.Eachcellwithanoteattacheddisplaysacellnoteindicator(bydefaultasmallredsquare)intheupperrightcornerofthecell.Whenthepointerisoveracellindicatorofacellthathasanote,thenotetextdisplaysinaboxnexttothecell.Alternatively,youcansetthecellnotestoalwaysbedisplayed,notjustwhenthepointermovesovertheindicator.Forcellnotesthataresetaspopupnotes,theyaredisplayedinasimilarmannerastexttips.Whenthepointerisoverthecellnoteindicator,thecellnotetextappears.Thisisillustratedinthefollowingfigure.
Theredsquareintheupperrightcornerofthecellindicatesthatanoteisavailableforthatcell.Anexampleisshowninthefollowingfigure.YoucanusetheCellNoteIndicatorVisible('CellNoteIndicatorVisibleProperty'intheon-linedocumentation)propertytohidethecellnoteindicatorwhenthepointerisoverthecellnoteindicator.YoucanusetheNoteIndicatorPosition('NoteIndicatorPositionProperty'intheon-linedocumentation)propertyforthecelltosetthelocationofthenote.
Spread Windows Forms Developer’s Guide 410
Copyright © GrapeCity, Inc. All rights reserved.
CustomizingtheCellNoteBehavior
Youcanallownotestoremaindisplayed,asiftheywerestickynotes.Inthiscasetheyappearinarectanglenexttothecellwithanexpandablelinethatattachesthenotetothecell,allowingthenotetobemovedbytheuser.Anexampleofastickynotethathasbeenselectedisshowninthefollowingfigure.ThecellNoteStyle('NoteStyleProperty'intheon-linedocumentation)propertymustusetheNoteStyle('NoteStyleEnumeration'intheon-linedocumentation)enumerationtoallowthis.Thestickynoteinthiscaseisashapethatcanbemoved.
Tomovethenote,presstheleftmousebuttonwhenthepointerisonthenotetoselectit,dragittothedestination,andreleasethemousebuttontoplaceit.Thelinefromthecellnoteindicatortothestickynotestretchestoaccommodateanyplacementofthenote.
Youcanallowtheusertoeditcellnotesifthenotesarealwaysshown.Toallowtheusertoeditit,settheAllowNoteEdit('AllowNoteEditProperty'intheon-linedocumentation)propertyforthesheet,whichsetsallstickynotesonthatsheettobeeditablebytheuser.
Thecellnotecancontainanextrabitofhumanreadableinformationfortheenduser;youcanalsoallowtheusertoattachtheirowninformationincellnotes.Theinformationcanbewhateverisusefultotheenduser.Forexample,theendusermightusethecellnotetoindicatetheoriginalsourceofthecellvalue(cellnote="ValueasobtainedfromanarticleintheJulyissueofourcorporatemagazine").
Youcanfurthercustomizetheuseofnotes:
automaticallysizecellnotesbasedoncontentscustomizelocationsofcellnotesmakestickynotessotheystaywhereplacedcustomizethenoteindicator(seesectionbelow)printcellnotes
Thereareadditionalclassesthatcanbeusedtocustomizetheappearanceofthecellnote.UsetheStickyNoteStyleInfoclassfornotes.
UnderstandingLimitations
Therearesomelimitationstotheuseanddisplayofcellnotes:
ThenotedoesnotdisplaywhentheNoteStyle('NoteStyleProperty'intheon-linedocumentation)propertyofthecellobjectissettohidden.ThenotedoesnotdisplayincertaincelltypeswhentheIsReservedLocationmethodforthatcelltypeissettotrue.Thismayoccurinacheckboxcell,orinacomboboxcellthatisnoteditable,orwhenapointerisoveralinkinahyperlinkcell.Thecellnoteindicatordoesnotappearwhenthecellisineditmode.Thecellnoteofananchorcellisdisplayedinacellspan,butthecellnotesofanyothercellinthespanarenotdisplayed.Usecautioninchoosingaredcolorasthebackgroundforacellthatcouldcontainaredcellnote.Thecellnoteindicatorcouldbeinvisibleagainstaredbackground.
CustomizingtheCellNoteIndicator
Spread Windows Forms Developer’s Guide 411
Copyright © GrapeCity, Inc. All rights reserved.
Youcanchangethesizeandthecolorofthecellnoteindicator.Thedefaultsizeofthecellnoteindicatorisa3x3squarebutyoucanmodifythewidthortheheightofthenoteindicatortoanypositiveintegervalue.Thedefaultcolorofthecellnoteindicatorisredbutyoucanassignanycolorvaluetoit.Thefollowingfigureshowstheindicatorusingdefaultvaluesandacustomindicatorusingcustomvalues.ThecustomvaluesaresetusingtheNoteIndicatorColor('NoteIndicatorColorProperty'intheon-linedocumentation)andNoteIndicatorSize('NoteIndicatorSizeProperty'intheon-linedocumentation)properties.
Formoreinformationonnotes,refertotheNote('NoteProperty'intheon-linedocumentation)propertyintheCell('CellClass'intheon-linedocumentation)class.
Forinformationaboutprintingcellnotes,refertoPrintingaSheetwithCellNotes.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetinwhichthecellsappear.5. Inthepropertieslist,selecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.
6. Selectthecellsforwhichyouwanttosetthenote.7. Inthepropertieslist,selecttheNotepropertyandtypethenotetext.8. ClickOKtoclosetheCell,Column,andRowEditor.9. ClickOKtoclosetheSheetViewCollectionEditor.
UsingaShortcut
1. SettheNotepropertyforthecellsorrangeofcellsinthesheetoftheSpreadcomponent.2. Setthepropertiesforcustomizingthenote,includingthenoteindicatorandnotepositionanddisplay.
Example
Thisexamplecodesetsaneditablecellnoteforarangeofcellsandsetsthecolorofthecellnoteindicatortogreen(fromthedefaultred).
C#fpSpread1.Sheets[0].AllowNoteEdit = true;fpSpread1.Sheets[0].Cells[1, 1, 3, 3].Note = "test";fpSpread1.Sheets[0].Cells[1, 1, 3, 3].NoteIndicatorColor = Color.Green;fpSpread1.Sheets[0].Cells[1, 1, 3, 3].NoteStyle = FarPoint.Win.Spread.NoteStyle.StickyNote;
Spread Windows Forms Developer’s Guide 412
Copyright © GrapeCity, Inc. All rights reserved.
VBFpSpread1.Sheets(0).AllowNoteEdit = TrueFpSpread1.Sheets(0).Cells(1, 1, 3, 3).Note = "test"FpSpread1.Sheets(0).Cells(1, 1, 3, 3).NoteIndicatorColor = Color.GreenFpSpread1.Sheets(0).Cells(1, 1, 3, 3).NoteStyle = FarPoint.Win.Spread.NoteStyle.StickyNote
Example
Thisexamplecodedefinesarangeofcellsandthensetsthenoteforthatrange.
C#FarPoint.Win.Spread.Cell range1;range1 = fpSpread1.ActiveSheet.Cells[1, 1, 3, 3];range1.Value = "Value Here";range1.Note = "This is the note that describes the value.";
VBDim range1 As FarPoint.Win.Spread.Cellrange1 = FpSpread1.ActiveSheet.Cells(1, 1, 3, 3)range1.Value = "Value Here"range1.Note = "This is the note that describes the value."
UsingtheSpreadDesigner
1. Intheworkarea,selectthecellorcellsforwhichyouwanttosetthenotestodisplay.2. Inthepropertieslist(intheMiscgroup),selecttheNotepropertyandtypeinthetextofthenote.
(OrselecttheCellspropertyandclickonthebuttontocalluptheCell,Column,andRoweditorandselectthecellsinthateditor.)
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Preventing a Cell from Receiving Focus
Youcanpreventcellsfromreceivingfocus,andthusnotallowtheendusertoclickinthatcell.YoucontrolfocussettingsthataredefinedbykeyboardinputandmouseoperationbysettingtheCanFocus('CanFocusProperty'intheon-linedocumentation)propertyinthecell.Youcanalsosetthispropertyinthecolumnsandrowsshortcutobjectsandyoucansetitinastylethatisappliedtoagroupofcells.
Returning Information for a Clicked Cell
YoucangetrowandcolumnindexinformationforcellsthatareclickedbyaccessingtheCellClick('CellClickEvent'intheon-linedocumentation)eventparametereintheCellClickEventArgs('CellClickEventArgsClass'intheon-linedocumentation)class.Youcangetx-andy-coordinatesaswellfromthisparameter.YoucanimplementaMouseDowneventandfromthex-andy-coordinatesyoucanobtainrowandcolumnindexinformationoftheclickedcell.WiththeGetCellFromPixel('GetCellFromPixelMethod'intheon-linedocumentation)methodintheFpSpread('FpSpreadClass'intheon-linedocumentation)class,youcangettargetcellinformationintheCellRange('CellRangeClass'intheon-linedocumentation)classformat.Youcanobtainrowandcolumninformationfromrespectivemembers.
Youcanobtaincellinformationsuchaspositionsandsizesthathavebeenspecifiedbyrowandcolumnindexes.WhentheGetCellRectangle('GetCellRectangleMethod'intheon-linedocumentation)methodintheFpSpread
Spread Windows Forms Developer’s Guide 413
Copyright © GrapeCity, Inc. All rights reserved.
classiscalled,specifythetargetrowandcolumnindexes.Thecellcoordinateinformationisreturnedinthe.NETframeworkRectangleformat.
Forheaders,youcangetrowandcolumnindexinformationofclickedheadercellsbyaccessingCellClickeventparametereintheCellClickEventArgsclass.Youcandetectwhethertheheadershavebeenclicked.Youcangetx-andy-coordinatesaswellfromthisparameter.YoucanimplementaMouseDowneventandfromthex-andy-coordinatesyoucanobtainrowandcolumnindexinformationoftheclickedheadercell.
WiththeGetColumnHeaderCellFromPixel('GetColumnHeaderCellFromPixelMethod'intheon-linedocumentation)methodintheSpreadView('SpreadViewClass'intheon-linedocumentation)class,youcangettargetcellinformationintheCellRangeclassformatforcolumncells.Youcanobtainrowandcolumninformationincolumnheadersfromrespectivemembers.Inthecaseofrowheadercells,calltheGetRowHeaderCellFromPixel('GetRowHeaderCellFromPixelMethod'intheon-linedocumentation)method.
Displaying Error Icons in Cells or Rows
Youcandisplayerroriconsincellsorrows.
UsetheShowCellErrors('ShowCellErrorsProperty'intheon-linedocumentation)orShowRowErrors('ShowRowErrorsProperty'intheon-linedocumentation)propertytospecifywhetheryouwishtodisplayanerroriconoracellnoteindicator.SettheErrorText('ErrorTextProperty'intheon-linedocumentation)propertyfortheCell('CellClass'intheon-linedocumentation)classorRow('RowClass'intheon-linedocumentation)classtospecifythecellorrowtodisplaytheerroriconin.SetthevalueoftheErrorTextpropertyto"CellError"todisplaytheerroriconforacellor"RowError"tospecifytheerroriconforarow.Thefollowingimagedisplaystheerroricon.
YoucandisplayacellnoteindicatorinsteadoftheerroriconbysettingShowCellErrorsorShowRowErrorstofalse.ThetextyouspecifywiththeErrorTextpropertyisthendisplayedinthecellnote.
UsingCode
1. SettheShowCellErrors('ShowCellErrorsProperty'intheon-linedocumentation)orShowRowErrors('ShowRowErrorsProperty'intheon-linedocumentation)property.
2. SettheErrorText('ErrorTextProperty'intheon-linedocumentation)propertyfortheCell('CellClass'intheon-linedocumentation)orRow('RowClass'intheon-linedocumentation)object.
Example
Thisexampledisplaysanerroriconinthelockedcell.
CSfpSpread1.ShowCellErrors = true;fpSpread1.Sheets[0].Cells[1, 1].ErrorText = "CellError";fpSpread1.Sheets[0].Cells[1, 1].Locked = true;
VBFpSpread1.ShowCellErrors = TrueFpSpread1.Sheets(0).Cells(1, 1).ErrorText = "CellError"FpSpread1.Sheets(0).Cells(1, 1).Locked = True
Spread Windows Forms Developer’s Guide 414
Copyright © GrapeCity, Inc. All rights reserved.
Using Conditional Formatting of Cells
Youcancustomizetheuserinteractionwithindividualcells(orarangeofcells).Youcanuserulesorconditionaloperatorsintheconditionalformat.
Tocustomizethisaspectofuserinteraction,youcanperformthefollowingtasks:
CreatingConditionalFormattingwithRulesSettingupConditionalFormattingofaCell
Creating Conditional Formatting with Rules
Youcansetthevisualappearanceofcellsusingrules.Thefollowingclassesareavailablewhencreatingconditionalformattingwithrules:
AverageConditionalFormattingRuleClass(on-linedocumentation)BetweenValuesConditionalFormattingRuleClass(on-linedocumentation)BlankConditionalFormattingRuleClass(on-linedocumentation)DatabarConditionalFormattingRuleClass(on-linedocumentation)FormulaConditionalFormattingRuleClass(on-linedocumentation)ErrorConditionalFormattingRuleClass(on-linedocumentation)IconSetConditionalFormattingRuleClass(on-linedocumentation)PrePaintConditionalFormattingRuleClass(on-linedocumentation)PrePaintTextConditionalFormattingRuleClass(on-linedocumentation)TextConditionalFormattingRuleClass(on-linedocumentation)ThreeColorScaleConditionalFormattingRuleClass(on-linedocumentation)TimePeriodConditionalFormattingRuleClass(on-linedocumentation)TopRankedValuesConditionalFormattingRuleClass(on-linedocumentation)TwoColorScaleConditionalFormattingRuleClass(on-linedocumentation)UnaryComparisonConditionalFormattingRuleClass(on-linedocumentation)UniqueOrDuplicatedConditionalFormattingRuleClass(on-linedocumentation)
Theaveragerulechecksforvaluesaboveorundertheaverage.Thecellvaluerulecomparesvalues.Thedaterulecomparesdates.Theformularuleallowsyoutouseformulaswhencheckingthecondition.
Thescaleruleusesaslidingcolorscale.Forexampleif1isyellowand50isgreen,then25wouldbelightgreen.
Thespecifictextrulesearchesfortextstrings.Thetop10rulechecksforvaluesinthetoporbottomoftherange.Theuniquerulecheckstoseeifthevalueistheonlyoneofthatvalueintherange(iftheduplicateoptionisfalse).Theduplicaterulechecksforduplicatevalues.
Thedatabarruledisplaysabarinthecellbasedonthecellvalueintherange.Theiconsetruledisplaysiconsbasedonthevalues.
YoucanaddruleswiththeSetConditionalFormatting('SetConditionalFormattingMethod'intheon-linedocumentation)methodortheConditionalFormatting('ConditionalFormattingClass'intheon-linedocumentation)class.
Thefollowingtopicsprovideadditionalinformationaboutspecificconditionalformattingrules.
ColorScaleRulesDataBarRuleHighlightingRulesIconSetRule
Spread Windows Forms Developer’s Guide 415
Copyright © GrapeCity, Inc. All rights reserved.
Top,Bottom,orAverageRules
Color Scale Rules
Colorscalesarevisualguidesthathelpyouunderstanddatadistributionandvariation.Atwo-colorscalecomparesarangeofcellsbyusingagradationoftwocolors.Theshadeofthecolorrepresentshigherorlowervalues.Forexample,inagreenandredcolorscale,youcanspecifythathighervaluecellsareclosertoagreencolorandlowervaluecellsareclosertoaredcolor.Youcanspecifythevaluetype,value,andcolorfortheminimumandmaximumproperties.
Athree-colorscalecomparesarangeofcellsbyusingagradationofthreecolors.Theshadeofthecolorrepresentshigher,middle,orlowervalues.Forexample,inagreen,yellow,andredcolorscale,youcanspecifythathighervaluecellshaveagreencolor,middlevaluecellshaveayellowcolor,andlowervaluecellshavearedcolor.Youcanspecifythevaluetype,value,andcolorfortheminimum,middle,andmaximumproperties.
Thefollowingimageusesthethreecolorrule.TheA2cellisagradationofthemiddleandlowcolorvalues.
UsingCode
SetthepropertiesoftheTwoColorScaleConditionalFormattingRule('TwoColorScaleConditionalFormattingRuleClass'intheon-linedocumentation)classortheThreeColorScaleConditionalFormattingRule('ThreeColorScaleConditionalFormattingRuleClass'intheon-linedocumentation)classandthenapplytheformatting.
Example
ThisexamplecodecreatesathreecolorruleandusestheSetConditionalFormatting('SetConditionalFormattingMethod'intheon-linedocumentation)methodtoapplytherule.
C#private void Form1_Load(object sender, EventArgs e) { fpSpread1.Sheets[0].Cells[0, 0].Value = 3; fpSpread1.Sheets[0].Cells[1, 0].Value = 2; fpSpread1.Sheets[0].Cells[1, 1].Value = 10; fpSpread1.Sheets[0].Cells[0, 2].Value = 1; }
private void button1_Click(object sender, EventArgs e) {FarPoint.Win.Spread.Model.CellRange celRange1 = new FarPoint.Win.Spread.Model.CellRange(0, 0, 3, 3);FarPoint.Win.Spread.ThreeColorScaleConditionalFormattingRule rule = new FarPoint.Win.Spread.ThreeColorScaleConditionalFormattingRule(Color.Aqua, Color.Bisque, Color.BlueViolet);fpSpread1.Sheets[0].SetConditionalFormatting(new FarPoint.Win.Spread.Model.CellRange[] { celRange1 }, rule); }
Spread Windows Forms Developer’s Guide 416
Copyright © GrapeCity, Inc. All rights reserved.
VBPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load FpSpread1.Sheets(0).Cells(0, 0).Value = 3 FpSpread1.Sheets(0).Cells(1, 0).Value = 2 FpSpread1.Sheets(0).Cells(1, 1).Value = 10 FpSpread1.Sheets(0).Cells(0, 2).Value = 1 End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim celRange1 As New FarPoint.Win.Spread.Model.CellRange(0, 0, 3, 3) Dim rule As New FarPoint.Win.Spread.ThreeColorScaleConditionalFormattingRule(Color.Aqua, Color.Bisque, Color.BlueViolet) FpSpread1.Sheets(0).SetConditionalFormatting(New FarPoint.Win.Spread.Model.CellRange() {celRange1}, rule) End Sub
UsingtheSpreadDesigner
1. Intheworkarea,selectthecellorcellsforwhichyouwanttosettheconditionalformat.2. UndertheHomemenu,selecttheConditionalFormattingiconintheStylesection,thenselecttheColorScalesoption,andthenchoosethecolorset.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Data Bar Rule
Thedatabarruleusesabarthatisdisplayedasthebackgroundforeachcell.Thelengthofthebarcorrespondstothesizeofthedatarelativetotheotherdataintheworksheet.Thelongerthebar,thegreaterthevalueinthecell.
Thefollowingimagedisplaysdatabarsinacellrange:
Youcanspecifythevaluetypeandthevaluetocompareintheconditionalformat.
ValueType
Description
Percent Theminimumvalueintherangeofcellsthattheconditionalformattingruleappliestoplusxpercentofthedifferencebetweenthemaximumandminimumvaluesintherangeofcellsthattheconditionalformattingruleappliesto.Forexample,iftheminimumandmaximumvaluesintherangeare1and10respectively,andxis10,thenthevalueis1.9.
HighestValue
Themaximumvalueintherangeofcellsthattheconditionalformattingruleappliesto.
Spread Windows Forms Developer’s Guide 417
Copyright © GrapeCity, Inc. All rights reserved.
LowestValue
Theminimumvalueintherangeofcellsthattheconditionalformattingruleappliesto.
Formula Theresultoftheformuladeterminestheminimumormaximumvalueofthecellrangethattheruleappliesto.Iftheresultisnotnumeric,itistreatedaszero.
Percentile Theresultofthefunctionpercentileappliedtotherangewithx.
Automatic Thesmallerorlargerortheminimumormaximumvalueintherangeofcellsthattheconditionalformatappliesto.
Number Number,date,ortimevalueintherangeofcellsthattheconditionalformattingruleappliesto.
Validpercentilesarefrom0(zero)to100.Apercentilecannotbeusediftherangeofcellscontainsmorethan8,191datapoints.Useapercentilewhenyouwanttovisualizeagroupofhighvalues(suchasthetop20thpercentile)inonedatabarandlowvalues(suchasthebottom20thpercentile)inanotherdatabar.Thisisusefulifyouhaveextremevaluesthatmightskewthevisualizationofyourdata.
Validpercentvaluesarefrom0(zero)to100.Percentvaluesshouldnotuseapercentsign.Useapercentagewhenyouwanttovisualizeallvaluesproportionallybecausethedistributionofvaluesisproportional.
Startformulaswithanequalsign(=).Invalidformulasresultinnoformattingapplied.
Theminimumandmaximumtypescanbedifferent.TheMaximum('MaximumProperty'intheon-linedocumentation)propertyshouldnotbesettoaConditionalFormattingValuevaluesuchasConditionalFormattingValueType.MinorConditionalFormattingValueType.AutoMin.Anexceptionwilloccurinthiscase.TheMinimum('MinimumProperty'intheon-linedocumentation)propertyshouldnotbesettoaConditionalFormattingValuevaluesuchasConditionalFormattingValueType.MaxorConditionalFormattingValueType.AutoMax.Anexceptionwilloccurinthiscase.
Youcanalsospecifyborders,colors,andanaxis.
UsingCode
Setthepropertiesofthedatabarruleclassandthenapplytheformatting.
Example
ThisexamplecodecreatesadatabarruleandusestheSetConditionalFormatting('SetConditionalFormattingMethod'intheon-linedocumentation)methodtoapplytherule.
C#private void Form1_Load(object sender, EventArgs e) { fpSpread1.Sheets[0].Cells[0, 0].Value = 3; fpSpread1.Sheets[0].Cells[1, 0].Value = 2; fpSpread1.Sheets[0].Cells[2, 0].Value = 10; fpSpread1.Sheets[0].Cells[3, 0].Value = 1; }
private void button1_Click(object sender, EventArgs e) { FarPoint.Win.Spread.DatabarConditionalFormattingRule d = new FarPoint.Win.Spread.DatabarConditionalFormattingRule(); d.BorderColor = Color.Red; d.ShowBorder = true; d.Minimum = new FarPoint.Win.Spread.ConditionalFormattingValue(0, FarPoint.Win.Spread.ConditionalFormattingValueType.Number); d.Maximum = new FarPoint.Win.Spread.ConditionalFormattingValue(15,
Spread Windows Forms Developer’s Guide 418
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Spread.ConditionalFormattingValueType.Max); fpSpread1.ActiveSheet.SetConditionalFormatting(0, 0, 4, 1, d); }
VBPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load FpSpread1.Sheets(0).Cells(0, 0).Value = 3 FpSpread1.Sheets(0).Cells(1, 0).Value = 2 FpSpread1.Sheets(0).Cells(2, 0).Value = 10 FpSpread1.Sheets(0).Cells(3, 0).Value = 1 End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim d As New FarPoint.Win.Spread.DatabarConditionalFormattingRule() d.BorderColor = Color.Red d.ShowBorder = True d.Minimum = New FarPoint.Win.Spread.ConditionalFormattingValue(0, FarPoint.Win.Spread.ConditionalFormattingValueType.Number) d.Maximum = New FarPoint.Win.Spread.ConditionalFormattingValue(15, FarPoint.Win.Spread.ConditionalFormattingValueType.Max) FpSpread1.ActiveSheet.SetConditionalFormatting(0, 0, 4, 1, d) End Sub
UsingtheSpreadDesigner
1. Intheworkarea,selectthecellorcellsforwhichyouwanttosettheconditionalformat.2. UndertheHomemenu,selecttheConditionalFormattingiconintheStylesection,thenselecttheDataBarsoption,andthenchoosethecolorset.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Highlighting Rules
Youcanusethisruletohighlightdatathatmeetsoneofthefollowingconditions:
isgreaterthanavalueislessthanavalueisbetweenahighandlowvalueisequaltoavaluecontainsaspecificvalueisadatethatoccursinaparticularrangeiseitheruniqueorduplicatedelsewhereintheworksheet
Afteryouchooseoneoftheoptionsabove,enteravalueorformulaagainstwhicheachcelliscompared.Ifthecelldatasatisfiesthatcriteria,thentheformattingisapplied.
Youcanselectapredefinedhighlightstyleorcreateacustomhighlightstyle.Thefollowingrulesarehighlightstylerules:
BetweenValuesConditionalFormattingRule('BetweenValuesConditionalFormattingRuleClass'intheon-linedocumentation)BlankConditionalFormattingRule('BlankConditionalFormattingRuleClass'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 419
Copyright © GrapeCity, Inc. All rights reserved.
ErrorConditionalFormattingRule('ErrorConditionalFormattingRuleClass'intheon-linedocumentation)FormulaConditionalFormattingRule('FormulaConditionalFormattingRuleClass'intheon-linedocumentation)TextConditionalFormattingRule('TextConditionalFormattingRuleClass'intheon-linedocumentation)TimePeriodConditionalFormattingRule('TimePeriodConditionalFormattingRuleClass'intheon-linedocumentation)UnaryComparisonConditionalFormattingRule('UnaryComparisonConditionalFormattingRuleClass'intheon-linedocumentation)UniqueOrDuplicatedConditionalFormattingRule('UniqueOrDuplicatedConditionalFormattingRuleClass'intheon-linedocumentation)
Thisfigureillustratesthefollowingexample.
UsingCode
1. Setthepropertiesoftheruleclass.2. Applytheformatting.
Example
ThisexamplecodecreatesthebetweenvaluesruleandusestheSetConditionalFormatting('SetConditionalFormattingMethod'intheon-linedocumentation)methodtoapplytherule.
C#private void Form1_Load(object sender, EventArgs e) { fpSpread1.Sheets[0].Cells[0, 0].Value = 3; fpSpread1.Sheets[0].Cells[1, 0].Value = 2; fpSpread1.Sheets[0].Cells[1, 1].Value = 5; fpSpread1.Sheets[0].Cells[0, 2].Value = 1; }
private void button1_Click(object sender, EventArgs e) { FarPoint.Win.Spread.BetweenValuesConditionalFormattingRule between = new FarPoint.Win.Spread.BetweenValuesConditionalFormattingRule(true, 10, false, 20, false); between.FirstValue = 10; between.SecondValue = 20; between.IsNotBetween = true; between.BackColor = Color.Bisque; fpSpread1.ActiveSheet.SetConditionalFormatting(1, 1, between); }
VBPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Spread Windows Forms Developer’s Guide 420
Copyright © GrapeCity, Inc. All rights reserved.
Handles MyBase.Load FpSpread1.Sheets(0).Cells(0, 0).Value = 3 FpSpread1.Sheets(0).Cells(1, 0).Value = 2 FpSpread1.Sheets(0).Cells(1, 1).Value = 5 FpSpread1.Sheets(0).Cells(0, 2).Value = 1 End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim between As New FarPoint.Win.Spread.BetweenValuesConditionalFormattingRule(True, 10, False, 20, False) between.FirstValue = 10 between.SecondValue = 20 between.IsNotBetween = True between.BackColor = Color.Bisque FpSpread1.ActiveSheet.SetConditionalFormatting(1, 1, between) End Sub
UsingtheSpreadDesigner
1. Intheworkarea,selectthecellorcellsforwhichyouwanttosettheconditionalformat.
2. UndertheHomemenu,selecttheConditionalFormattingiconintheStylesection,thenselecttheHighlightCellsRulesoption,andthenchoosethecondition.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Icon Set Rule
Youcansetrulesthatdisplaycertainiconswhenacellvalueisgreaterthan,equalto,orlessthanavalue.
Youcanusebuilt-iniconsetsfortherule.YoucanalsospecifyindividualiconstouseintheiconsetwiththeIconRuleSet('IconRuleSetProperty'intheon-linedocumentation)propertyandtheIconSetConditionalFormattingRule('IconSetConditionalFormattingRuleClass'intheon-linedocumentation)class.YoucanusecustomiconswiththeAddIcon('AddIconMethod'intheon-linedocumentation)methodandtheCustomIconContainer('CustomIconContainerProperty'intheon-linedocumentation)property.
Thefollowingfigureillustratescellsthatdisplaythebuilt-inicons.
UsingCode
1. Setthepropertiesoftheiconsetruleclass.2. Applytheformatting.
Example
ThisexamplecodecreatesaniconsetruleandusestheSetConditionalFormatting('SetConditionalFormattingMethod'intheon-linedocumentation)methodtoapplytherule.
C#private void Form1_Load(object sender, EventArgs e) { fpSpread1.Sheets[0].Cells[0, 0].Value = 8; fpSpread1.Sheets[0].Cells[1, 0].Value = 5; fpSpread1.Sheets[0].Cells[2, 0].Value = 10; fpSpread1.Sheets[0].Cells[3, 0].Value = 1; }
private void button1_Click(object sender, EventArgs e) {FarPoint.Win.Spread.Model.CellRange celRange1 = new FarPoint.Win.Spread.Model.CellRange(0, 0, 4, 1);FarPoint.Win.Spread.IconSetConditionalFormattingRule rule = new FarPoint.Win.Spread.IconSetConditionalFormattingRule(FarPoint.Win.Spread.ConditionalFormattingIconSetStyle.ThreeRimmedTrafficLights
Spread Windows Forms Developer’s Guide 421
Copyright © GrapeCity, Inc. All rights reserved.
); fpSpread1.Sheets[0].SetConditionalFormatting(new FarPoint.Win.Spread.Model.CellRange[] { celRange1 }, rule); }
VBPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load FpSpread1.Sheets(0).Cells(0, 0).Value = 8 FpSpread1.Sheets(0).Cells(1, 0).Value = 5 FpSpread1.Sheets(0).Cells(2, 0).Value = 10 FpSpread1.Sheets(0).Cells(3, 0).Value = 1 End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim celRange1 As New FarPoint.Win.Spread.Model.CellRange(0, 0, 4, 1) Dim rule As New FarPoint.Win.Spread.IconSetConditionalFormattingRule(FarPoint.Win.Spread.ConditionalFormattingIconSetStyle.ThreeRimmedTrafficLights) FpSpread1.Sheets(0).SetConditionalFormatting(New FarPoint.Win.Spread.Model.CellRange() {celRange1}, rule) End Sub
UsingtheSpreadDesigner
1. Intheworkarea,selectthecellorcellsforwhichyouwanttosettheconditionalformat.2. UndertheHomemenu,selecttheConditionalFormattingiconintheStylesection,thenselecttheIconSetsoption,andthenchoosetheiconset.3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Top, Bottom, or Average Rules
Thetoporbottomrulesapplyformattingtocellswhosevaluesfallinthetoporbottompercent.Thetoprankedrulespecifiesthetoporbottomvalues.Theaverageruleappliestothegreaterorlesseraveragevalueoftheentirerange.
Thefollowingfigureshowsatoprulethatsetsthestylefortheaboveaveragevalueintherangeofvalues;thecodetocreatetheexampleisprovidedintheexample.
Thefollowingoptionsareavailable:
top10top10%bottom10bottom10%aboveaveragebelowaverage
UsingCode
1. Setthepropertiesoftheruleclass.2. Applytheformatting.
Example
ThisexamplecodecreatesanaverageruleandusestheSetConditionalFormatting('SetConditionalFormattingMethod'intheon-linedocumentation)methodtoapplytherule.
C#private void Form1_Load(object sender, EventArgs e) { fpSpread1.Sheets[0].Cells[0, 0].Value = 3; fpSpread1.Sheets[0].Cells[1, 0].Value = 2;
Spread Windows Forms Developer’s Guide 422
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.Sheets[0].Cells[1, 1].Value = 10; fpSpread1.Sheets[0].Cells[0, 2].Value = 1; } private void button1_Click(object sender, EventArgs e) { //Average CF FarPoint.Win.Spread.AverageConditionalFormattingRule average = new FarPoint.Win.Spread.AverageConditionalFormattingRule(true, true); average.IsAbove = true; average.IsIncludeEquals = true; average.StandardDeviation = 2; average.FontStyle = new FarPoint.Win.Spread.SpreadFontStyle(FarPoint.Win.Spread.RegularBoldItalicFontStyle.Bold); fpSpread1.ActiveSheet.SetConditionalFormatting(1, 1, average); }
VBPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load FpSpread1.Sheets(0).Cells(0, 0).Value = 3 FpSpread1.Sheets(0).Cells(1, 0).Value = 2 FpSpread1.Sheets(0).Cells(1, 1).Value = 10 FpSpread1.Sheets(0).Cells(0, 2).Value = 1 End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Average CF Dim average As New FarPoint.Win.Spread.AverageConditionalFormattingRule(True, True) average.IsAbove = True average.IsIncludeEquals = True average.StandardDeviation = 2 average.FontStyle = New FarPoint.Win.Spread.SpreadFontStyle(FarPoint.Win.Spread.RegularBoldItalicFontStyle.Bold) FpSpread1.ActiveSheet.SetConditionalFormatting(1, 1, average) End Sub
UsingtheSpreadDesigner
1. Intheworkarea,selectthecellorcellsforwhichyouwanttosettheconditionalformat.
2. UndertheHomemenu,selecttheConditionalFormattingiconintheStylesection,thenselecttheTop/BottomRulesoption,andthenchoosethecondition.
3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Setting up Conditional Formatting of a Cell
Youcansetupconditionalformatswithincellsthatdeterminetheformattingofthecellbasedontheoutcomeofaconditionalstatement.Youcanuseanamedstyletospecifyvariousformattingoptionssuchasbordersandcolorstoapplyiftheconditionstatementisvalid,thatis,iftheoperationissatisfied.
Forexample,youmaywanttochangethebackgroundcolorofacellbasedonthevalueofthecell.Ifthevalueisbelow100thenthebackgroundcolorwouldbechangedtored.Theconditionstatementis"lessthan100"andconsistsofacomparisonoperator"lessthan"andacondition,inthiscaseasingleconstant"100".Theconditioncanbeaconstant(expressedasastring)oranexpression.Someconditionstatementshavetwoconditionsandanoperator:forinstance,if
Spread Windows Forms Developer’s Guide 423
Copyright © GrapeCity, Inc. All rights reserved.
thecellvalueisbetween0and100,thenchangethebackgroundcolor.Inthiscase,thecomparisonoperatoris"between"andthefirstconditionis0andthelastconditionis100.Foracompletelistofoperations,refertotheComparisonOperator('ComparisonOperatorEnumeration'intheon-linedocumentation)enumeration.Foralistofthetypesofexpressions,refertotheCalcEngine.Expressionobject.Formoreinformationaboutthepossiblestylesettings,refertoCreatingandApplyingaStyleforCells.
Iftwoconditionalformatsaresettothesamecell,thesecondconditionalformattakeseffect.
TheconditionalformattingcanbedoneusingtheConditionalFormat('ConditionalFormatClass'intheon-linedocumentation)classandanyofthesemembersoftheSheetView('SpreadViewClass'intheon-linedocumentation)class:
GetConditionalFormatsmethodSetConditionalFormatmethodsClearConditionalFormatsmethod
WhenyouusetheGetConditionalFormatmethods,theconditions,operator,andstyleinformationarereturnedasaConditionalFormatobject.Thefirstconditioncanbeeitherastringorexpression(FirstConditionorFirstConditionExpression.)Similarly,thelastconditioncanbeastringorexpression(LastConditionorLastConditionExpression).Ifonlyoneconditionisset,itisintheFirstConditionandtheLastConditionisnull.TheComparisonOperatoristhecomparisonoperatorfortheconditionalformat.ThestylesettingstoapplytothecellwhentheconditionstatementistruearesetasaNamedStyleobject.
Refertothefollowingcodeexamplestoseehowtosetconditionalformattingforarangeofcellsthatwouldresultindifferentbackgroundcolors,forinstance,asshowninthefollowingfigure.
Forsomecelltypesthatallowinputofmultipledatatypes,suchasgeneralcelltype,conditionalformattingworkswhetheryoutypeinnumbersorstrings.Forexample,ifyouhaveconditionalformattingsetforvaluesbetweenvariousrangessuchas10to20and20to30,thentyping16resultsintheformattingfortherange10to20.Ifyouthentype16m,thecelltreatsthislikeastringandsince"16m"isbetweenstrings"10"and"20",theconditionalformattingstillapplies.
YoucanalsousethesemembersoftheIConditionalFormatSupport('IConditionalFormatSupportInterface'intheon-linedocumentation)interface:
ConditionalFormatIsRowUsed('ConditionalFormatIsRowUsedMethod'intheon-linedocumentation)methodConditionalFormatNextNonEmptyColumnInRow('ConditionalFormatNextNonEmptyColumnInRowMethod'intheon-linedocumentation)method
UsetheClearConditionalFormatsmethodtoclearonlytheconditionalformatsofacellwithoutaffectingtheotherformattingorthecontentsofthecell.
UsetheModel.DefaultSheetStyleModel.ConditionalFormatIsRowUsedmethodtodeterminewhetherarowinthestylemodelcontainsstylesettings.
UsetheModel.DefaultSheetStyleModel.ConditionalFormatNextNonEmptyColumnInRowmethodtoreturntheindexofthenextnon-emptycolumninarowinthemodel.UsetheModel.DefaultSheetStyleModel.GetValidConditionalFormatmethodtoreturnthestyleinformationforthefirstvalidconditionforthecellatthespecifiedrowandcolumninthemodel.
UsingCode
1. Definestyles.2. Setaconditionalformatforacell.
Spread Windows Forms Developer’s Guide 424
Copyright © GrapeCity, Inc. All rights reserved.
Example
Thisexamplecodesetstheconditionalformatforacellbasedonthenumericvalueofthedata.Itchangesthecoloringofthecellbasedonthevalueoftemperaturedata.Toseehowitworks,typeanumberincellB2,theneitherchangecellsorleaveeditmodetoseetheformattingapplied.
C#FarPoint.Win.Spread.NamedStyle styleCold = new FarPoint.Win.Spread.NamedStyle();FarPoint.Win.Spread.NamedStyle styleCool = new FarPoint.Win.Spread.NamedStyle();FarPoint.Win.Spread.NamedStyle styleMild = new FarPoint.Win.Spread.NamedStyle();FarPoint.Win.Spread.NamedStyle styleWarm = new FarPoint.Win.Spread.NamedStyle();FarPoint.Win.Spread.NamedStyle styleHot = new FarPoint.Win.Spread.NamedStyle();
styleCold.BackColor = Color.Blue;styleCold.ForeColor = Color.White;styleCool.BackColor = Color.Cyan;styleMild.BackColor = Color.Lime;styleWarm.BackColor = Color.Yellow;styleHot.BackColor = Color.Red;
for (int col = 0; col < 6; col++){ fpSpread1.ActiveSheet.SetConditionalFormat(0, col, styleCold, FarPoint.Win.Spread.ComparisonOperator.LessThanOrEqualTo, "32"); fpSpread1.ActiveSheet.SetConditionalFormat(0, col, styleCool, FarPoint.Win.Spread.ComparisonOperator.Between, "32", "55"); fpSpread1.ActiveSheet.SetConditionalFormat(0, col, styleMild, FarPoint.Win.Spread.ComparisonOperator.Between, "55", "75"); fpSpread1.ActiveSheet.SetConditionalFormat(0, col, styleWarm, FarPoint.Win.Spread.ComparisonOperator.Between, "75", "85"); fpSpread1.ActiveSheet.SetConditionalFormat(0, col, styleHot, FarPoint.Win.Spread.ComparisonOperator.GreaterThan, "85");}
VBDim styleCold As New FarPoint.Win.Spread.NamedStyle()Dim styleCool As New FarPoint.Win.Spread.NamedStyle()Dim styleMild As New FarPoint.Win.Spread.NamedStyle()Dim styleWarm As New FarPoint.Win.Spread.NamedStyle()Dim styleHot As New FarPoint.Win.Spread.NamedStyle()
styleCold.BackColor = Color.BluestyleCold.ForeColor = Color.WhitestyleCool.BackColor = Color.CyanstyleMild.BackColor = Color.LimestyleWarm.BackColor = Color.YellowstyleHot.BackColor = Color.Red
For col As Integer = 0 To 5 fpSpread1.ActiveSheet.SetConditionalFormat(0, col, styleCold, FarPoint.Win.Spread.ComparisonOperator.LessThanOrEqualTo, "32") fpSpread1.ActiveSheet.SetConditionalFormat(0, col, styleCool, FarPoint.Win.Spread.ComparisonOperator.Between, "32", "55") fpSpread1.ActiveSheet.SetConditionalFormat(0, col, styleMild, FarPoint.Win.Spread.ComparisonOperator.Between, "55", "75")
Spread Windows Forms Developer’s Guide 425
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.ActiveSheet.SetConditionalFormat(0, col, styleWarm, FarPoint.Win.Spread.ComparisonOperator.Between, "75", "85") fpSpread1.ActiveSheet.SetConditionalFormat(0, col, styleHot, FarPoint.Win.Spread.ComparisonOperator.GreaterThan, "85")Next col
Managing Formulas in Cells
Youcansetupandperformcalculationsusingformulasincells.Thismayinvolvethesetasks:
PlacingaFormulainCellsSpecifyingaCellReferenceinaFormulaSpecifyingaSheetReferenceinaFormulaSpecifyinganExternalReferenceinaFormula(on-linedocumentation)UsingaCircularReferenceinaFormulaNestingFunctionsinaFormulaRecalculatingandUpdatingFormulasAutomaticallyFindingaValueUsingGoalSeekAllowingtheUsertoEnterFormulasCreatingandUsingaCustomNameCreatingandUsingaCustomFunctionUsingtheArrayFormula(on-linedocumentation)
FormoreinformationonenteringformulasusingtheSpreadDesigner,refertoEnteringaFormulainSpreadDesigner(on-linedocumentation).
Forinformationonthefloatingformulabar,whereuserscantypeinformulasandselectcellsdynamically,refertoSettinguptheFormulaTextBox.
Foranoverviewofformulasanddetailsonthefunctionsandoperatorsthatcanbeusedtocreateaformula,refertotheFormulaReference.
ForinformationontheCalcEngineassembly,whichisresponsiblefortheformulacalculations,refertotheFarPoint.CalcEngine('FarPoint.CalcEngineAssembly'intheon-linedocumentation).
Placing a Formula in Cells
Youcanaddaformulatoacellorrangeofcells.Youcanalsoaddaformulatoallthecellsinaroworcolumn.Theformulaisastringwiththeexpressionoftheformula,typicallycontainingacombinationoffunctions,operators,andconstants.
WhenassigningaformulatotheRow('RowClass'intheon-linedocumentation)classorColumn('ColumnClass'intheon-linedocumentation)class,youareassigningadefaultformulaforthatroworcolumn.Inotherwords,theformulaisusedforeverycellintheroworcolumn(assumingthattheformulaisnotoverriddenatthecelllevel).Foraformulainaroworcolumn,Spreadusesthefirstcellintheroworcolumnasthebaselocation.TheformulaevaluatestoadifferentresultforeachcellincolumnAifyouuserelativeaddressing.IfyouwanteachcellincolumnAtoevaluatetothesumofthevaluesinC2andD2(andnotthevalueintheCandDcolumnsforeachrow)thenyouwouldneedtousetheformula$C$2+$D$2,whichusesabsoluteaddress.Forexamplesofformulasthatusecellreferences,refertoSpecifyingaCellReferenceinaFormula.
YoucanaddaformulabyspecifyingtheFormulapropertyfortheobjectorbyenteringitintheSpreadDesigner.Theproceduresforusingcodearegivenbelow.ForinstructionsonusingSpreadDesignertoenteraformula,refertoEnteringaFormulainSpreadDesigner(on-linedocumentation).Youcanallowenduserstoenterformulasbyallowingthemtotypetheequalssignandthentheformula;refertoAllowingtheUsertoEnterFormulas.
Spread Windows Forms Developer’s Guide 426
Copyright © GrapeCity, Inc. All rights reserved.
Becarefulofthetypeofcellinwhichthedataisfound,andwhetheryouusetheTextorValuepropertywhenassigningdatathatisusedinaformula.WhenyouassigncelldatausingtheTextproperty,thespreadsheetusesthecelltypetoparseanassignedstringintotheneededdatatype.Forexample,anumbercelltypeparsesastringintoadoubledatatype.WhenyouassignthecelldatausingtheValueproperty,thespreadsheetacceptstheassignedobjectasisandnoparsingoccurs,soifyousetitwithastring,itremainsastring.Somenumericfunctions(forexample,SUM)ignorenon-numericvaluesinacellrange.Forexample,ifthecellrangeA1:A3containsthevalues{1,"2",3},thentheformulaSUM(A1:A3)evaluatesto4becausetheSUMfunctionignoresthestring"2".Besurethatyousetthevaluecorrectlyforanycellsusedinthecalculationofaformulaandthatyousetthemwiththecorrectdatatype.
Astringconstantinaformulacancontainspecialcharacterssuchasthenewlinecharacter(thatis,'\n').Makesurethatyouenclosethestringconstantinquotesinthetextrepresentationoftheformula.ThefollowingC#codecreatesamultiple-linetextcellandassignsaformulathatcontainsastringconstantthatcontainsanewlinecharacter.
C#TextCellType ct = new TextCellType();ct.Multiline = true;fpspread1.Sheets[0].Cells[0,0].Formula = "\"line1\nline2\"";
UsingaShortcut
Addaformulatoacell,row,orcolumnbyspecifyingtheFormulapropertyforthatcell,row,orcolumn.
Example
Thisexampleshowshowtospecifyaformulathatfindstheproductoffivetimesthevalueinthefirstcell,andputstheresultinanothercell.Thenitfindsthesumofarangeofcells(A1throughA4)andputstheresultineverycellofthefourthcolumn.
C#FpSpread1.ActiveSheet.Cells[2, 0].Formula = "PRODUCT(A1,5)";FpSpread1.ActiveSheet.Columns[3].Formula = "SUM(A1:A4)";
VBFpSpread1.ActiveSheet.Cells(2, 0).Formula = "PRODUCT(A1,5)"FpSpread1.ActiveSheet.Columns(3).Formula = "SUM(A1:A4)"
UsingCode
1. Specifythecell,row,orcolumn.2. Addaformulatothecell,row,orcolumn.
Example
Thisexampleshowshowtospecifyaformulathatsumstwocells,doublesit,andputstheresultinathirdcell.
C#FarPoint.Win.Spread.Cell mycell;mycell = fpSpread1.Cells[2, 0];mycell.Formula = "SUM(A1:A2) * 2";
VBDim mycell As FarPoint.Win.Spread.Cell
Spread Windows Forms Developer’s Guide 427
Copyright © GrapeCity, Inc. All rights reserved.
mycell = FpSpread1.ActiveSheet.Cells(2, 0)mycell.Formula = "SUM(A1:A2) * 2"
UsingtheFormulaEditor
Atdesigntime,youcanenterformulasincellsusingeithertheFormulabarortheFormulaEditor,bothofwhichareavailablefromtheSpreadDesigner.TheFormulaEditorisalsoavailablefromthePropertiesWindow.Formoreinformation,refertoEnteringaFormulainSpreadDesigner(on-linedocumentation).Fordetailsonthefunctionsandoperatorsthatcanbeusedtocreateaformula,refertotheFormulaReference.
1. Selectthesheettabofthesheetthatcontainsthecellsinwhichtoplaceformulas.2. Selectthecellorcellsinthesheet.3. IntheFormulaproperty,clickthearrowbutton.ThisopenstheFormulaEditor.4. IntheFormulaEditor,youmaytypeintheformulaintheeditbox.Toassistinenteringfunctionsinthe
formula,youcandouble-clickonafunctionnametohaveitappearintheeditbox.Functionsareorganizedbycategory.Youcanalsotypeoperatorsandconstantstoconstructyourformula.
5. Whendone,clickApply.ClickOKtoclosetheeditor.6. IfyouwereworkingfromwithintheSpreadDesigner,fromtheFilemenuchooseApplyandExittoapplyyour
changestothecomponentandexitSpreadDesigner.
Specifying a Cell Reference in a Formula
Besidesvalues,operators,andfunctions,aformulacancontainreferencestovaluesinothercells.Forexample,tofindthesumofthevaluesintwocells,theformulacanrefertothecellcoordinatesbyrowandcolumn.Youcanuseanabsolutecellreference(withtheactualcoordinatesoftherowandcolumn)orarelativecellreference(withthecoordinatesrelativetothecurrentcell).YouchoosewhichtypeofcellreferenceforthesheetbyusingtheReferenceStyle('ReferenceStyleProperty'intheon-linedocumentation)property.Fordetailsonthewaytospecifythereferencestyle,refertotheReferenceStyle('ReferenceStyleProperty'intheon-linedocumentation)propertyoftheSheetView('SheetViewClass'intheon-linedocumentation)class,andtheReferenceStyle('ReferenceStyleEnumeration'intheon-linedocumentation)enumeration.
Ifyouhavechangedthecellreferencestyletoastylethatcannotrepresenttheformula,theSpreadcomponentprovidestheformulawithquestionmarksasplaceholdersforcellreferencesthatcannotberepresented.
Thefollowingtablecontainsexamplesofvalidformulasusingreferences:
Function DescriptionSUM(A1:A10) Sumsrows1through10inthefirstcolumn
PI()*C6 PItimesthevalueincellC6
(A1+B1)*C1 Addsthevaluesinthefirsttwocellsandmultipliestheresultbythevalueinthethirdcell
IF(A1>5,A1*2,A1*3)
IfthecontentsofcellA1aregreaterthan5,thenmultiplythecontentsofcellA1by2,elsemultiplythecontentsofcellA1by3
IfyouhavedefinedrelativecellreferencesusedinaformulaincellB1asRC[-1]+R[-1]C,theformulaisinterpretedasaddthevalueinthecelltotheleft(A1)tothevalueinthecellabove("B0").Thecomponenttreatsthevalueinthecell"B0"asanemptycell.IfyouchangethecellreferencestyletotheA1style,theformulabecomesA1+B?,becausetheA1stylecannotrepresentcell"B0".However,thecomponentstillevaluatestheformulaasitwouldusingtheR1C1referencestyle.
Note:AlthoughmostofSpreaduseszero-basedreferencestorowsandcolumns,inthecreationofformulasyoumustuseone-basedreferences.Thecolumnandrownumbersstartatone(1),notzero(0).
Spread Windows Forms Developer’s Guide 428
Copyright © GrapeCity, Inc. All rights reserved.
RangeReference
Spreaddoesnotsupportrangereferenceswherethestartrowandendrowconsistofdifferentreferencetypes(forexample,oneabsolutecoordinateandonerelativecoordinate).
Eitherbothrowcoordinatesmustbeabsoluteorbothrowcoordinatesmustberelative.Forexample:
Reference WhetherSupportedR1C[-1]:R5C[-1] supported(absoluterow:absoluterow)
R1C[-1]:RC[-1] notsupported(absoluterow:relativerow)
RC[-1]:R5C[-1] notsupported(relativerow:absoluterow)
R[-5]c[-1]:RC[-1] supported(relativerow:relativerow)
Developyourformulassothateitherbothrowcoordinatesareabsolute,
for(inti=0;i<n;i++)
fpspread1.Sheets[0].Cells[i,column].Formula="SUM(R1C[-1]:R"+(i+1).ToString()+"C[-1])"
orbothrowcoordinatesarerelative,
for(inti=0;i<n;i++)
fpspread1.Sheets[0].Cells[i,column].Formula="SUM(R["+(-i).ToString()+"]C[-1]:RC[-1])"
Thesamerestrictionsapplytostartcolumnandendcolumncoordinates.
Formoreinformationoncellreferencestyles,refertotheFormulaReference.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindowselecttheSheetspropertyandclickonthebuttontoopentheSheetViewCollectioneditor.
2. SelectthesheetfromtheMemberlist.3. Inthepropertieslist(intheCalculationcategory),selecttheReferenceStyleproperty.4. Clickthedrop-downarrowtodisplaythechoicesandselectthevalue,eitherA1orR1C1.
UsingCode
SpecifythereferencestylebysettingtheReferenceStyle('ReferenceStyleProperty'intheon-linedocumentation)propertyorusethedefaultReferenceStylevalue.
Example
Thisexamplesetsthereferencestyle.
C#fpSpread1.Sheets[0].ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.A1;fpSpread1.Sheets[0].Cells[2, 2].Formula = "SUM(A1:A6)";
VBFpSpread1.Sheets(0).ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.A1FpSpread1.Sheets(0).Cells(2, 2).Formula = "SUM(A1:A6)"
UsingtheSpreadDesigner
Spread Windows Forms Developer’s Guide 429
Copyright © GrapeCity, Inc. All rights reserved.
1. Selectthesheettabnameforthesheet.2. Inthepropertylist(intheCalculationcategory),selecttheReferenceStyleproperty.3. Clickthedrop-downarrowtodisplaythechoicesandselectthevalue,eitherA1orR1C1.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Specifying a Sheet Reference in a Formula
Aformulacancontainreferencestoothersheets.Whenareferencetoacellincludesareferencetoacellonanothersheet,thisiscalledcross-sheetreferencing.Anexampleofcross-sheetreferencinginaformulathatusestheadditionoperatorwouldbe:
(FirstRoundData!A2+SecondRoundData!A2)
Note:AlthoughmostofSpreaduseszero-basedreferencestorowsandcolumns,inthecreationofformulasyoumustuseone-basedreferences.Thecolumnandrownumbersstartatone(1),notzero(0).
Anotherexamplewouldbekeepingarunningtotalofcellsofonesheetonaseparatesheet.UsetheFormulapropertytoputaformulaononesheetthatreferencesthecellsyouwantaddedfromanothersheet,asshowninthefollowingcode.
FpSpread1.Sheets(1).Cells(0,0).Formula = "SUM(Sheet1!A1:Sheet1:A100)"
ThenusetheReferenceStyle('ReferenceStyleProperty'intheon-linedocumentation)propertytosetthereferencestyle.
Youcanhaveformulasthatreferenceotherworksheetsoryoucanhaveautomaticcalculationsattheworksheetlevel(appliestoallsheets).Youcannothaveboth.WhenEnableCrossSheetReference('EnableCrossSheetReferenceProperty'intheon-linedocumentation)isTrue(whichisthedefaultsetting),theentireworkbookactsasasinglecalculationunitwithallworksheetssharingthesamecalculationsettings(autocalculations,iterations,customfunctions,customnames,etc).Changingacalculationsettingaffectsallworksheets.Formulascanreferencecellsonotherworksheets.WhenEnableCrossSheetReferenceisFalse,eachworksheetfunctionsasaseparatecalculationunitwitheachworksheethavingitsowncalculationsettings(autocalculations,iterations,customfunctions,customnames,andsoon).Changingacalculationsettingaffectsasingleworksheet.ForthissettingofEnableCrossSheetReference('EnableCrossSheetReferenceProperty'intheon-linedocumentation),formulascanonlyreferencecellsonthesameworksheet.
Ifthesheetnamecontainsnonalpha-numericcharacters(forexample,aspace),thenenclosethesheetnameinsinglequotesintheformula.Forexample,supposesheetnameis"pageone"thentheformulawouldbeSUM('pageone'!$A$1:$A$5).
Ifthesheetnamecontainsthesinglequotecharacter,thenusetwosinglequotecharactersintheformula.Forexample,supposethesheetnameis"scott'spage"thentheformulawouldbeSUM('scott''spage'!$A$1:$A$5).
Ifthesheetnamecontainsacolon,thenusetwosinglequotesaroundthesheetname.Forexample("'Sheet:name'!$B$1:$F$1").
Formoreinformationoncross-sheetreferencing,refertotheFormulaReference.
UsingCode
Thefollowingexampleusesdefaultsheetnamesinaformula.
Example
Thisexamplesetstheformula.
C#
Spread Windows Forms Developer’s Guide 430
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.Sheets[0].Cells[0,0].Formula = "Sheet1!A3 + Sheet2!A2";
VBFpSpread1.Sheets(0).Cells(0,0).Formula = "Sheet1!A3 + Sheet2!A2"
Using a Circular Reference in a Formula
Youcanrefertoaformulainthecellthatcontainsthatformula;thistypeofreferenceiscalledacircularreference.Thisisdonetypicallytorecurseonafunctiontoapproachanoptimumvaluebyiteratingonthesamefunction.
Thistopicexplainsthefollowingtasks:
1. IterativeCalculationsinaFormula2. LocateCircularReferencesinaFormula
IterativeCalculationsinaFormula
Youcanselecthowmanytimesafunctioniteratesonitself(recurses)bysettingtherecalculationiterationcountpropertyusingtheMaximumIterations('MaximumIterationsProperty'intheon-linedocumentation)property.YoucansettheamountofchangeallowedwiththeMaximumChange('MaximumChangeProperty'intheon-linedocumentation)property.
Bydefault,iftheformula"=COLUMNS(A1:C5)"isincellC4,noresultisreturned.Inotherwords,ifboththelastcolumnandrowindexofthearrayaregreaterthanthecolumnandrowindexofthecellinwhichtheformularesides,theformulacannotbecalculated.Inthiscase,thecellC4isintherangeA1:C5.ThisisacircularreferenceinaformulaandsoSpreaddoesnotevaluatetheformulaunlessiterationsareturnedon.
Aswithmostspreadsheetproducts(includingExcelandOpenOffice),Spreadsolvescircularformulasviaiterations.Duringeachrecalculationcycle,aspecifiednumberofiterationsareperformed.Duringeachiteration,everycircularformulaisevaluatedexactlyonce.Theexactorderinwhichthecircularformulasareevaluatedduringagiveniterationcannotbeassumedbytheapplication.Aswithmostspreadsheetproducts(includingExcelandOpenOffice),circularformulasinSpreadareintendedtobeusedinscenarioswheretheiterationsconvergetothedesiredsolutionregardlessoftheorderofevaluationwithinagiveniteration.
ForinformationonusingtheFormulaEditortoenteraformulaatdesigntime,refertoEnteringaFormulainSpreadDesigner(on-linedocumentation).Fordetailsonthefunctionsandoperatorsthatcanbeusedtocreateaformula,refertotheFormulaReference.
UsingCode
1. Setthecelltypesforthecellswiththeformulas.2. SettherecalculationiterationcountbysettingtheMaximumIterations('MaximumIterationsProperty'intheon-linedocumentation)propertyforthesheet.
3. SpecifythemaximumamountofchangethatcanoccurwitheachiterationbysettingtheMaximumChange('MaximumChangeProperty'intheon-linedocumentation)propertyforthesheet.
4. Ifneeded,setthereferencestyleforthesheetwiththeReferenceStyle('ReferenceStyleProperty'intheon-linedocumentation)property.
5. Definetheformulaswiththecircularreference(s)inthecells.
Example
Thisexamplesetsformulas.
C#fpSpread1.ActiveSheet.Iteration = true;
Spread Windows Forms Developer’s Guide 431
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.ActiveSheet.SetValue(0, 1, 20);fpSpread1.ActiveSheet.MaximumChange = 5;fpSpread1.ActiveSheet.MaximumIterations = 5;fpSpread1.ActiveSheet.SetFormula(0, 2, "A1*3");fpSpread1.ActiveSheet.SetFormula(0, 0, "B1+C1");
VBFpSpread1.ActiveSheet.Iteration = TrueFpSpread1.ActiveSheet.SetValue(0, 1, 20)FpSpread1.ActiveSheet.MaximumChange = 5FpSpread1.ActiveSheet.MaximumIterations = 5FpSpread1.ActiveSheet.SetFormula(0, 0, "B1+C1")FpSpread1.ActiveSheet.SetFormula(0, 2, "A1*3")
LocateCircularReferencesinaFormula
InSpreadforWinforms,youcanusetheCircularFormula('CircularFormulaEvent'intheon-linedocumentation)eventtodetectcircularreferencesandeliminatetheminordertoavoidcalculationerrorsintheformulasusedinspreadsheets.
UsingCode
1. CreateanewCircularFormulaevent.2. Runaforlooptofindallcircularreferencesinthespreadsheet.3. Eliminatecircularreferencesfromthespreadsheet.
Example
Thisexampledetectscircularreferencesinaformula.
C#fpSpread1.CircularFormula += delegate (object sender1, CircularFormulaEventArgs e1) { for (int i = 0; i < e1.CircularCells.Count; i++) { Console.WriteLine("Circular formula detected at cell [{0:d}, {0:d}]!", e1.CircularCells[i].Row, e1.CircularCells[i].Column); } }; fpSpread1.ActiveSheet.Cells[3, 3].Formula = "A1"; fpSpread1.ActiveSheet.Cells[0, 0].Formula = "A2"; fpSpread1.ActiveSheet.Cells[1, 0].Formula = "D4";
VBfpSpread1.CircularFormula += Sub(sender1 As Object, e1 As CircularFormulaEventArgs) For i As Integer = 0 To e1.CircularCells.Count - 1 Debug.WriteLine("Circular formula detected at cell [{0:d}, {0:d}]!", e1.CircularCells(i).Row, e1.CircularCells(i).Column) NextfpSpread1.ActiveSheet.Cells(3, 3).Formula = "A1"fpSpread1.ActiveSheet.Cells(0, 0).Formula = "A2"fpSpread1.ActiveSheet.Cells(1, 0).Formula = "D4"
Spread Windows Forms Developer’s Guide 432
Copyright © GrapeCity, Inc. All rights reserved.
Nesting Functions in a Formula
Youcannestafunctionwithinanotherfunctioninaformula.
ForinformationonusingtheFormulaEditortoenteraformulaatdesigntime,refertoEnteringaFormulainSpreadDesigner(on-linedocumentation).Fordetailsonthefunctionsandoperatorsthatcanbeusedtocreateaformula,refertotheFormulaReference.
UsingCode
1. Ifneeded,setthereferencestyleforthesheetwiththeReferenceStyle('ReferenceStyleProperty'intheon-linedocumentation)property.
2. Useafunctionwithinanotherfunctioninaformula.
Example
Inthisexamplethesumofthevalueintwocells(foundbyusingtheSUMfunction)isembeddedinaPRODUCTformula.Firstthecelltypesaresetandthevaluesofthecellsareset.
C#fpSpread1.Sheets[0].Cells[3, 1].Formula = "PRODUCT(A1, SUM(A2,A3))";
VBFpSpread1.Sheets(0).Cells(3, 1).Formula = "PRODUCT(A1, SUM(A2,A3))"
Recalculating and Updating Formulas Automatically
Bydefault,thespreadsheetrecalculatesformulasinthespreadsheetwhenthecontentsofdependentcellschange.Youcanturnthisrecalculationoff.Youcanalsorecalculateanindividualcell.
Alsobydefault,thespreadsheetupdatesformulaswhenyouadd,insert,orremovecolumnsorrowsorwhenyoumoveorswapblocksofcells.Youcanturnofftheseautomaticformulaupdates,butgenerallyyouprobablywantthespreadsheettoupdateformulasinthesecases.Keepinmindhowturningoffautomaticformulaupdatingmightimpactthespreadsheetiftheusermovesdata,addsrowsorcolumns,orperformsotheractionsthataffectthelocationofdata.
Whenautomaticformulaupdatingison,thespreadsheetupdatesabsoluteandrelativecellreferences,asfollows:
Whenthespreadsheetisupdatingformulas,itupdatesabsolutecellreferenceswhenthecellreferencedbytheformulaispartoftheblockthathaschanged.Forexample,ifyouhaveaformulaincellC3thatreferencescellA1,whichusesanabsolutereference,andthenaddarowtothetopofthespreadsheet,younowwanttheformulatoreferencecellA2,becausecellA1isempty.Ifthespreadsheetdidnotupdatetheformula,yourformulawouldbereferencingdifferentdata.
Whenthespreadsheetisupdatingformulas,itupdatesrelativecellreferenceswhenthecellreferencedbytheformulaisnotpartoftheblockthathaschanged.Forexample,ifyouhaveaformulaincellC3thatreferencescellC1asarelativereference,itreferencescellC1asthecellthatistwocellsaboveit.Ifyouaddarowbetweenrow2androw3,cellC3isnowC4,andtherelativeaddressreferencescellC2,thecelltwocellsaboveit.Therefore,tousethesamedataintheformula,thespreadsheetupdatesthecellreferencetothecellthreecellsaboveit,C1.
UsetheAutoCalculation('AutoCalculationProperty'intheon-linedocumentation)propertytoturnonorofftheautomaticrecalculationofformulas.UsetheRecalculate('RecalculateMethod'intheon-linedocumentation)andRecalculateAll('RecalculateAllMethod'intheon-linedocumentation)methodsforrecalculatingformulas.
Spread Windows Forms Developer’s Guide 433
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
1. Ifneeded,setthereferencestyleforthesheetwiththeReferenceStyle('ReferenceStyleProperty'intheon-linedocumentation)property.
2. AddaformulatothecellwiththeSetFormula('SetFormulaMethod'intheon-linedocumentation)method.
3. SettheRecalculateAll('RecalculateAllMethod'intheon-linedocumentation)methodtorecalculate.
Example
Thisexamplerecalculatesalltheformulas.
C#fpSpread1.ActiveSheet.SetValue(0, 0, 20);fpSpread1.ActiveSheet.SetValue(0, 1, 10);fpSpread1.ActiveSheet.SetFormula(3, 0, "SUM(A1,B1)");fpSpread1.ActiveSheet.SetFormula(4, 0, "A1*B1");fpSpread1.ActiveSheet.SetValue(0, 1, 100);fpSpread1.ActiveSheet.RecalculateAll();
VBFpSpread1.ActiveSheet.SetValue(0, 0, 20)FpSpread1.ActiveSheet.SetValue(0, 1, 10)FpSpread1.ActiveSheet.SetFormula(3, 0, "SUM(A1,B1)")FpSpread1.ActiveSheet.SetFormula(4, 0, "A1*B1")FpSpread1.ActiveSheet.SetValue(0, 1, 100)FpSpread1.ActiveSheet.RecalculateAll()
Finding a Value Using GoalSeek
YoucanusetheGoalSeek('GoalSeekMethod'intheon-linedocumentation)methodtofindavaluethatwillproducethedesiredresultforaformula.Anapproximationisacceptable.Youcansetthestartingandintendedgoalofthecalculation.
UsingCode
UsetheGoalSeekmethodtofindtherequiredresult.
Example
Inthisexampletheformulaisincell(1,1).Theresultthatyouwanttoseeintheformulacellis32.ThevalueinC1iswhatisrequiredtogetaresultof32.
C#FpSpread1.Sheets[0].Cells[1, 1].Formula = "C1+D1";FpSpread1.Sheets[0].Cells[0, 3].Value = 2;FpSpread1.GoalSeek(0, 0, 2, 0, 1, 1, 32);<
VBFpSpread1.Sheets(0).Cells(1, 1).Formula = "C1+D1"FpSpread1.Sheets(0).Cells(0, 3).Value = 2FpSpread1.GoalSeek(0, 0, 2, 0, 1, 1, 32)
Spread Windows Forms Developer’s Guide 434
Copyright © GrapeCity, Inc. All rights reserved.
Allowing the User to Enter Formulas
Inmanyofthecelltypes,userscantypeinaformulabysimplystartingwithanequalssign(=).Youdonotneedtosetapropertytoallowthis.Howtheresultisdisplayeddependsonthecelltype.Forexample,anintegercelltypedisplaystheresultasaninteger,eveniftheresultoftheformulaisnotaninteger.Inthiscase,anumbermayappearrounded.Forcurrencyanddatecells,specificformattingcanbedefined.Formoreinformationonsettingvariouscelltypes,refertoWorkingwithEditableCellTypes.
Forinformationonthefloatingformulabar,whereuserscantypeinformulasandselectcellsdynamically,refertoSettinguptheFormulaTextBox.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow(intheBehaviorcategory),selecttheAllowUserFormulasproperty.
2. SelectTruefromthedrop-downlisttoallowuserstoenterformulas,orselectFalsetoprohibitthem.
UsingaShortcut
AllowtheusertoenterformulasbysettingtheAllowUserFormulas('AllowUserFormulasProperty'intheon-linedocumentation)propertyforthecomponentorthesheet.
Example
ThisexamplecodesetstheSpreadcomponenttoallowuserstoenterformulas.
C#fpSpread1.AllowUserFormulas = true;
VBFpSpread1.AllowUserFormulas = True
UsingCode
AllowtheusertoenterformulasbysettingtheAllowUserFormulas('AllowUserFormulasProperty'intheon-linedocumentation)propertyforthecomponentorthesheet.
Example
Thisexamplecodesetsthechildsheettoallowuserstoenterformulas.
C#FarPoint.Win.Spread.SpreadView sv = fpSpread1.GetRootWorkbook();sv.AllowUserFormulas = true;
VBDim sv As FarPoint.Win.Spread.SpreadView = FpSpread1.GetRootWorkbooksv.AllowUserFormulas = True
UsingtheSpreadDesigner
Spread Windows Forms Developer’s Guide 435
Copyright © GrapeCity, Inc. All rights reserved.
1. SelecttheSpreadcomponent(orselectSpreadfromthepull-downmenu).2. Inthepropertylistforthecomponent(intheBehaviorcategory),selecttheAllowUserFormulasproperty
andselectthevalueTrue.3. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Creating and Using a Custom Name
Custom,user-definednamesareidentifierstorepresentinformationinthespreadsheet,usedmostlyinformulas.Acustomnamecanrefertoacell,arangeofcells,acomputedvalue,oraformula.Youcandefineacustomnameandthenusethenameinformulas.Whentheformulaisevaluated,thecustomname'svalueisreferencedandevaluated.
Youcancreatesheetlevelorworkbooklevelcustomnames.Thescopeofthesheetlevelcustomnameislimitedtothesheetforwhichitwascreated.Thisallowsyoutousethesamenameonseveralsheets.Formulasinasheetwillignoresheetlevelcustomnamesonothersheets.
UsetheAddCustomName('AddCustomNameMethod'intheon-linedocumentation)methodintheSheetView('SheetViewClass'intheon-linedocumentation)classtoaddworkbookorsheetlevelcustomnames.ThesheetViewScopeparameterintheAddCustomNamemethodcanbesettotrueforasheetlevelcustomnameandfalseforaworkbooklevelcustomname.UsetheAddModelScopeCustomName('AddModelScopeCustomNameMethod'intheon-linedocumentation)methodtoaddsheetlevelcustomnames.
AvoidusingcustomnamesthatstartwithC#orR#patterns(#standsforanynumber).
UsingCode
DefinethecustomnameusingtheAddCustomName('AddCustomNameMethod'intheon-linedocumentation)methodfortheworkbookorsheet.
Example
ToaddacustomnameforacellspecifiedwithA1notation,usetheAddCustomName('AddCustomNameMethod'intheon-linedocumentation)methodasshowninthefollowingexample,whichcreatesaworkbooklevelcustomname.
C#FarPoint.Win.Spread.Model.DefaultSheetDataModel d = new FarPoint.Win.Spread.Model.DefaultSheetDataModel();d.AddCustomName("test", "$B$1", 0, 0);
VBDim d As FarPoint.Win.Spread.Model.DefaultSheetDataModel = New FarPoint.Win.Spread.Model.DefaultSheetDataModel()d.AddCustomName("test", "$B$1", 0, 0)
Toaddacustomnameforacomputedvalue,usetheAddCustomName('AddCustomNameMethod'intheon-linedocumentation)methodasshowninthiscode:
C#FarPoint.Win.Spread.Model.DefaultSheetDataModel d;d = (FarPoint.Win.Spread.Model.DefaultSheetDataModel)FpSpread1.Sheets[0].Models.Data;d.AddCustomName("alpha", "101", 0, 0);
Spread Windows Forms Developer’s Guide 436
Copyright © GrapeCity, Inc. All rights reserved.
VBDim d As FarPoint.Win.Spread.Model.DefaultSheetDataModeld = DirectCast(FpSpread1.Sheets(0).Models.Data, FarPoint.Win.Spread.Model.DefaultSheetDataModel)d.AddCustomName("alpha", "101", 0, 0)
Thefollowingexampleaddsanamethatisarangereference.
C#FarPoint.Win.Spread.Model.DefaultSheetDataModel d;d = (FarPoint.Win.Spread.Model.DefaultSheetDataModel)FpSpread1.Sheets[0].Models.Data;d.AddCustomName("Sales", "Sheet1!$F$20:$F$50", 0, 0);
VBDim d As New FarPoint.Win.Spread.Model.DefaultSheetDataModeld = DirectCast(FpSpread1.Sheets(0).Models.Data,FarPoint.Win.Spread.Model.DefaultSheetDataModel)d.AddCustomName("Sales", "Sheet1!$F$20:$F$50", 0, 0)
UsingtheSpreadDesigner
1. SelecttheDatamenuintheSpreadDesigner.2. SelecttheNameManagericon.3. UsetheNewbuttontoaddcustomnamesandclicktheClosebuttonwhenfinished.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Creating and Using a Custom Function
Ifyouhavefunctionsthatyouuseonaregularbasisthatarenotinthebuilt-infunctionsorifyouwishtocombinesomeofthebuilt-infunctionsintoasinglefunction,youcandosobydefiningyourowncustomfunctions.Theycanbecalledasyouwouldcallanyofthebuilt-infunctions.
Acustomfunctioncanhavethesamenameasabuilt-infunction.Thecustomfunctiontakespriorityoverthebuilt-infunction.Customfunctionsaredynamicallylinkedatevaluationtime.Thus,theapplicationcanredefineanexistingbuilt-infunction,ifthecustomfunctionusesthesamenameandisaddedbeforetheformulaisparsed.
IfaformulaattemptstocallacustomfunctionwithaparametercountoutsideoftherangeindicatedbytheMinArgs('MinArgsProperty'intheon-linedocumentation)andMaxArgs('MaxArgsProperty'intheon-linedocumentation)propertiesofthefunction,thentheEvaluate('EvaluateMethod'intheon-linedocumentation)methodofthefunctionisskippedandthe#VALUE!errorvalueisusedastheresult.
Also,ifaformulaattemptstocallacustomfunctionwithaparameterthatisanerrorvalue(forexample,#NUM!,#VALUE!,#REF!)andtheAcceptsError('AcceptsErrorMethod'intheon-linedocumentation)methodofthefunctionreturnsFalseforthatparameter,thentheEvaluatemethodofthefunctionisskippedandtheerrorvalueisusedastheresult.
Thecustomfunction'sEvaluate('EvaluateMethod'intheon-linedocumentation)methoddoesnotreceiveanyinformationregardingthelocation(orcontext)inwhichtheformulaisbeingevaluated.Ifyourcustomfunctionneedstherowandcolumninwhichitisbeingevaluatedthenyoumustaddextraparameterstoyourcustomfunctionandmanuallypasstherowandcolumncoordinatesintheextraparameters.
UsingCode
1. Definethecustomfunction(s).
Spread Windows Forms Developer’s Guide 437
Copyright © GrapeCity, Inc. All rights reserved.
2. Registerthefunction(s)inthesheet.3. Usethecustomfunction(s).
Example
Thefirststepistocreatethecustomfunctions.Inthisexample,wecreatethreefunctions:acubemathematicalfunction,anXORlogicalfunction,andanullstringfunction.Thefollowingcodeimplementsthecustomfunctions.
TheCUBEcustomfunctionraisesanumbertothethirdpower.Thatis,CUBE(x)isequivalenttoPOWER(x3).
C#public class CubeFunctionInfo : FarPoint.CalcEngine.FunctionInfo{public override string Name { get { return "CUBE"; } }public override int MinArgs { get { return 1; } }public override int MaxArgs { get { return 1; } }public override object Evaluate (object[] args){double num = FarPoint.CalcEngine.CalcConvert.ToDouble(args[0]);return num * num * num;}}
TheXORcustomfunctionperformsanexclusiveORoperationontwoBooleanvalues.Thisissimilartothe"^"operatorinCortheXoroperatorinVB.
C#public class XorFunctionInfo : FunctionInfo{public override string Name { get { return "XOR"; } }public override int MinArgs { get { return 2; } }public override int MaxArgs { get { return 2; } }public override object Evaluate (object[] args){bool arg0 = CalcConvert.ToBool(args[0]);bool arg1 = CalcConvert.ToBool(args[1]);return (arg0 || arg1) && (arg0 != arg1);}}
TheNULLfunctionreturnstheconstantvaluenullsimilartohowtheFALSE()functionreturnstheconstantvaluefalse.
C#public class NullFunctionInfo : FunctionInfo{public override string Name { get { return "NULL"; } }public override int MinArgs { get { return 0; } }public override int MaxArgs { get { return 0; } }public override object Evaluate (object[] args){return null;}}
Thefollowingcoderegistersthecustomfunctions.
Spread Windows Forms Developer’s Guide 438
Copyright © GrapeCity, Inc. All rights reserved.
C#fpSpread1.ActiveSheet.AddCustomFunction(new CubeFunctionInfo());fpSpread1.ActiveSheet.AddCustomFunction(new XorFunctionInfo());fpSpread1.ActiveSheet.AddCustomFunction(new NullFunctionInfo());
Thefollowingcodeusesthecustomsinformulas.
C#fpSpread1.ActiveSheet.SetFormula(0, 0, "CUBE(5)");fpSpread1.ActiveSheet.SetFormula(1, 0, "XOR(FALSE,FALSE)");fpSpread1.ActiveSheet.SetFormula(1, 1, "XOR(TRUE,FALSE)");fpSpread1.ActiveSheet.SetFormula(1, 2, "XOR(FALSE,TRUE)");fpSpread1.ActiveSheet.SetFormula(1, 3, "XOR(TRUE,TRUE)");fpSpread1.ActiveSheet.SetFormula(2, 0, "CHOOSE(1,100,NULL(),300)");fpSpread1.ActiveSheet.SetFormula(2, 1, "CHOOSE(2,100,NULL(),300)");fpSpread1.ActiveSheet.SetFormula(2, 2, "CHOOSE(3,100,NULL(),300)");
ParametersinCustomFunctions
Bydefault,parametersarepassedbyvalue.Asingleemptycellispassedasnull(NothinginVisualBasic).Asinglenon-emptycellispassedasaboxedprimitive(forexample,double,boolean,string,andsoon).AcellrangeispassedasaninstanceoftheCalcArray('CalcArrayClass'intheon-linedocumentation)class.TheCalcArray('CalcArrayClass'intheon-linedocumentation)classhasRowCountandColumnCountpropertiesfordeterminingthenumberofrowsandcolumnsinthetwodimensionalarray.TheCalcArrayclasshasaGetValue('GetValueMethod'intheon-linedocumentation)methodforgettingasinglevaluefromofthearray.TherowandcolumnindexestotheGetValuemethodarezerobased.
Ifyouwantaparameterpassedbyreference,thenyoumustoverridetheAcceptsReference('AcceptsReferenceMethod'intheon-linedocumentation)methodintheFunctionInfo('FunctionInfoClass'intheon-linedocumentation)class.WhentheAcceptsReferencemethodreturnsTrueforaparameter,asinglecelloracellrangeispassedasaninstanceoftheCalcReference('CalcReferenceClass'intheon-linedocumentation)class.TheCalcReference('CalcReferenceClass'intheon-linedocumentation)classhasRowandColumnpropertiesfordeterminingthefirstrowandcolumninthereference.TheCalcReferenceclasshasRowCountandColumnCountpropertiesfordeterminingthenumberofrowsandcolumnsinthereference.TheCalcArrayclasshasaGetValuemethodforgettingasinglevaluefromthereference.TherowandcolumnindexesfortheGetValuemethodstartattherowandcolumn.
Example
Inthisexample,afunctioncountsthenumberofcellsinarangethatarelessthanagivencriteria.
C#class CountIfLessThanFunctionInfo : FunctionInfo { public override string Name { get { return "COUNTIFLESSTHAN"; } } public override int MinArgs { get { return 2; } } public override int MaxArgs { get { return 2; }
Spread Windows Forms Developer’s Guide 439
Copyright © GrapeCity, Inc. All rights reserved.
} public override bool AcceptsReference(int i) { return i == 0; } public override object Evaluate(object[] args) { CalcReference range = args[0] as CalcReference; double criteria = CalcConvert.ToDouble(args[1]); double count = 0.0; if (range == null) return CalcError.Value; for (int i = range.Row; i < range.Row + range.RowCount; i++) { for (int j = range.Column; j < range.Column + range.ColumnCount; j++) double cellValue = CalcConvert.ToDouble(range.GetValue(i, j)); if (cellValue < criteria) count++; } } return count; }}
Using the Additional Spread Controls
YoucanextendthefunctionalityprovidedinSpreadtoendusersthroughothercontrolsontheform.TheFormulaProviderextendstheformulaandfunctioncapabilitytoothercontrolsontheform.TheFormulaTextBoxcanbeusedtomakeformulabarsorothereditcontrolsinyourapplication.TheNameBoxcanbeusedtoaddcustomnamesintheapplication.Thesecontrolsextendspreadsheetcapabilitytootherpartsofyourapplication.
SettinguptheFormulaTextBoxSettinguptheFormulaProviderSettinguptheNameBox
Formoreinformationonformulas,refertoManagingFormulasinCellsandtheFormulaReference.
Setting up the Formula Text Box
Youcansetupafloatingformulabarthatenduserscanusetoaddformulas.Theformulabarissimilartotheformulaeditoravailabletothedeveloperandhastheappearanceofatextbox.Theformulabarprovidesalistofcalculationfunctions.Italsoprovidesavisualmethodofselectingcellrangesfortheformula.
Spread Windows Forms Developer’s Guide 440
Copyright © GrapeCity, Inc. All rights reserved.
Refertothefollowingexampletoseehowtocreatetheformulatextbox.
SettinguptheFormulaTextBox
Tosetuptheformulabaratruntime,usetheFormulaTextBox('FormulaTextBoxClass'intheon-linedocumentation)class.YoucanalsodrawtheformulatextboxontheformandassignittoSpreadatdesigntime.SelecttheformulatextboxiconintheToolboxanddragittotheform.SelecttheformulatextboxverbandattachittoSpread.
TheAllowUserFormulas('AllowUserFormulasProperty'intheon-linedocumentation)propertyallowstheusertotypeformulasinthecellintheSpreadcontrol.
IfyousettheAllowUserFormulaspropertytoTrue,thentheformulasthataretypedinacellshowupintheformulabar.
UsingtheFormulaTextBox
Tousetheformulatextbox,typetheequalsign(=)andthenstarttypingthenameoftheformula.Thisbringsupalistoffunctionsthatstartwiththatletter.Youcanthentypetheleftparenthesisandeitherselectablockofcellsbydraggingthemouseoverthatrangeortypecellvaluesbyabsoluteorrelativereference.ThefigurebelowshowstheselectionofarangeofcellsfromA1toB3.
Formoreinformationonformulas,refertoManagingFormulasinCellsandtheFormulaReference.
UsingCode
Createtheformulaeditorandattachittothecontrol.
Spread Windows Forms Developer’s Guide 441
Copyright © GrapeCity, Inc. All rights reserved.
Example
Thisexamplecodecreatesthefloatingformulabar.
C#FarPoint.Win.Spread.FormulaTextBox editor = new FarPoint.Win.Spread.FormulaTextBox();editor.Location = new Point(0, 0);editor.Size = new Size(80, 20);this.Controls.Add(editor);editor.Attach(fpSpread1);// This line will disconnect the formula bar from the control// editor.Detach();
VBDim editor As New FarPoint.Win.Spread.FormulaTextBoxeditor.Location = New Point(0, 0)editor.Size = New Size(80, 20)Controls.Add(editor)editor.Attach(FpSpread1)‘ This line will disconnect the formula bar from the control‘ editor.Detach()
Setting up the Formula Provider
Youcanaddaformulaprovidercontroltotheform.Theprovidercontrolallowsyoutoaddvaluesfromothercontrolsusingformulasandputtheresultinacontrolontheform.Customformulafunctionscanbeused(AddCustomFunctionInfo('AddCustomFunctionInfoMethod'intheon-linedocumentation)method)aswellascustomnames(AddQueryValueName('AddQueryValueNameMethod'intheon-linedocumentation)method).TheprovidercontrolcanbeaddedtotheToolbox.Findtheformulaprovidercontrolinthelistof.NETcontrolsthatcanbeaddedtotheToolboxandselectit.
SettinguptheFormulaProviderControl
Double-clicktheformulaprovidercontrolafterselectingitfromtheToolbox.
Twodesignpropertieswillbeaddedtoeachcontrolontheform.TheFormulaonFormulaProviderpropertyisthepropertyforsettingaformula.TheFormulaTriggerEventonFormulaProviderpropertyallowsyoutodeterminewhicheventwillcausetheformulatoupdate.
UsingtheFormulaProvider
Thefollowingbasicexampleshowshowtousetheformulaprovideratdesigntime.Thisexampleusestwotextboxcontrolsandtheformulaprovider.Thesecondtextboxdisplaysthevaluefromthefirsttextbox.Theformulaforthesecondtextbox(FormulaonFormulaProviderproperty)hasbeensettobeequaltothefirsttextbox.Thetriggerevent(FormulaTriggerEvent)hasbeensettotheTextChangedevent.
Spread Windows Forms Developer’s Guide 442
Copyright © GrapeCity, Inc. All rights reserved.
Formoreinformationonformulas,refertoManagingFormulasinCellsandtheFormulaReference.
UsingCode
AddtheformulaproviderandtwotextboxcontrolstotheformandsettheSetFormula('SetFormulaMethod'intheon-linedocumentation)andSetFormulaTriggerEvent('SetFormulaTriggerEventMethod'intheon-linedocumentation)methodsfortheformulaprovider.
Example
Thisexamplegetsthetypeddatafromtextbox1andputsitintextbox2.
C#FormulaProvider1.SetFormula(TextBox2, "=TextBox1");FormulaProvider1.SetFormulaTriggerEvent(TextBox1, "TextChanged");
VBFormulaProvider1.SetFormula(TextBox2, "=TextBox1")FormulaProvider1.SetFormulaTriggerEvent(TextBox1, "TextChanged")
Spread Windows Forms Developer’s Guide 443
Copyright © GrapeCity, Inc. All rights reserved.
Setting up the Name Box
Youcanusethenameboxcontroltodisplayorcreatecustomnamesatruntime.Customnamesthatarecreatedbythenameboxcanonlyrefertoacellorarangeofcells.
SettinguptheNameBox
SelectthenameboxcontrolfromtheToolboxanddrawitontheformorusetheNameBox('NameBoxClass'intheon-linedocumentation)classtocreatethecontrolatruntime.ThenattachthecontroltoSpread.ThefollowingimagedisplaystheNameBoxcontrolinthetoolbox.
UsingtheNameBox
Tocreateacustomname,selectacellorrangeofcellsintheSpreadcontrol,typeacustomnameinthenameboxcontrol,andthenpresstheequalkeytocreatethecustomname.
Usethedrop-downlistinthenameboxcontroltodisplaythecustomnames.Youcanselectoneofthenamestoseethecellorcellrangethatthenamerefersto.
UsingCode
Createthenameboxandattachittothecontrol.
Example
Thisexamplecodecreatesanameboxcontrolandacustomname.
C#fpSpread1.ActiveSheet.AddCustomName("Alpha", "A1:B1", 0, 0);
FarPoint.Win.Spread.NameBox namebox1 = new FarPoint.Win.Spread.NameBox();namebox1.Location = new Point(0, 0);namebox1.Size = new Size(80, 20);
Spread Windows Forms Developer’s Guide 444
Copyright © GrapeCity, Inc. All rights reserved.
this.Controls.Add(namebox1);namebox1.Attach(fpSpread1);
VBFpSpread1.ActiveSheet.AddCustomName("Alpha", "A1:B1", 0, 0)
Dim namebox1 As New FarPoint.Win.Spread.NameBox()namebox1.Location = New Point(0, 0)namebox1.Size = New Size(80, 20)Controls.Add(namebox1)namebox1.Attach(FpSpread1)
Spread Windows Forms Developer’s Guide 445
Copyright © GrapeCity, Inc. All rights reserved.
Managing Data Binding
YoucanbindtheSpreadcomponenttoadataset,suchasdatainadatabase,ortoanythingthatthe.NETframeworkallows,suchasanIListobject.YoucanworkwithdatabindingSpreadwithdataorothercontrolsbythesetasks:
BindingtoDataBindingSpreadtoanExternalDataSetBindingaCellRangeinSpreadtoanExternalDataSourceBindingaCellRangeinSpreadasaDataSourcetoanExternalControlCustomizingColumnandFieldBindingBindingaComboBoxtoaDataReader
AddingtoBoundDataAddingaRowtoaBoundSheetAddinganUnboundRowtoaBoundSheetAddinganUnboundColumntoaBoundSheet
CustomizingDataBindingCustomizingColumnHeadersforBoundSheetsCustomizingCellTypesforBoundSheetsWorkingwithHierarchicalDataDisplayCreatingaHierarchicalDisplayManuallyCreatingCustomHierarchyIcons
Ifyouwouldliketostepthroughanexample,seeoneofthebrieftutorials:
Tutorial:BindingtoaCorporateDatabase(VisualStudio2013)(on-linedocumentation)Tutorial:BindingtoaCorporateDatabase(OlderVisualStudio)
Binding to Data
YoucanbindtheSpreadcomponenttoadataset,suchasdatainadatabase,ortoanythingthatthe.NETframeworkallows,suchasanIListobject.
ThetasksyoucanperformtobindSpreadtodataorothercontrolsare:
BindingSpreadtoanExternalDataSetBindingaCellRangeinSpreadtoanExternalDataSourceBindingaCellRangeinSpreadasaDataSourcetoanExternalControlCustomizingColumnandFieldBindingBindingaComboBoxtoaDataReader
Binding Spread to an External Data Set
YoucanbindtheSpreadcomponenttoadataset.Whenyoubindthecomponentusingthedefaultsettings,datafromthedatasetisreadintothecolumnsandrowsofthesheettowhichyoubindthedata.Columnsareassociatedwithfields,androwsrepresenteachrecordinthedataset.
Youcanalsobindasheet,column,orcellrange.
ThefollowinginstructionsprovidethecodenecessarytobindtheSpreadcomponenttoadataset.Foratutorialthatcanintroduceyoutotheprocedurefordatabinding,refertotheTutorial:BindingtoaCorporateDatabase(VisualStudio2013)(on-linedocumentation).
Formoreinformation,refertotheAddRowToDataSource('AddRowToDataSourceMethod'intheon-line
Spread Windows Forms Developer’s Guide 446
Copyright © GrapeCity, Inc. All rights reserved.
documentation)andBindDataColumn('BindDataColumnMethod'intheon-linedocumentation)methods.
Ifyouwanttore-orderthecolumnsinadataset,movearoundthecolumnsintheSpreadafterthebind.UsetheBindDataColumn('BindDataColumnMethod'intheon-linedocumentation)methodintheSheetView('SheetViewClass'intheon-linedocumentation)classtodothis.
Therearemanyalternativewaystosetupdatabinding.TolearnmoreaboutdatabindinginVisualStudio.NET,consulttheVisualStudio.NETdocumentation.
UsingthePropertiesWindow
1. Createyourdataset.2. InthePropertieswindowselecttheSpreadcomponent.
Tosetthedatasourceforthecomponent,settheDataSourceproperty.Tosetthedatasourceforthesheet,
a. SelecttheSheetspropertyfortheSpreadcomponent.b. ClickthebuttontodisplaytheSheetViewCollectionEditor.c. Selectthesheetforwhichtosetthedatasource.d. SettheDataSourcepropertyforthatsheet.
UsingCode
1. Createyourdataset.2. SettheFpSpreadDataSource('DataSourceProperty'intheon-linedocumentation)orSheetViewDataSource('DataSourceProperty'intheon-linedocumentation)propertyequaltothedataset.
Example
ThisexamplecodebindstheSpreadcomponenttoadatasetnamed"dbDataSet".
C#// Bind the component to the data set.fpSpread1.Sheets[0].AutoGenerateColumns = false;fpSpread1.Sheets[0].DataSource = dbDataSet;fpSpread1.Sheets[0].ColumnCount = 2;fpSpread1.Sheets[0].BindDataColumn(0, "ID");fpSpread1.Sheets[0].BindDataColumn(1, "Description");
VB' Bind the component to the data set.FpSpread1.Sheets(0).AutoGenerateColumns = FalseFpSpread1.Sheets(0).DataSource = dbDataSetFpSpread1.Sheets(0).ColumnCount = 2FpSpread1.Sheets(0).BindDataColumn(0, "ID")FpSpread1.Sheets(0).BindDataColumn(1, "Description")
Binding a Cell Range in Spread to an External Data Source
YoucanbindacellrangeinSpreadtoanexternaldatasource.Todothis,usetheSpreadDataBindingAdpater('SpreadDataBindingAdapterClass'intheon-linedocumentation)classtocreateaconnectionbetweentheSpreadcomponentandthedatasourceandusetheMapperInfo('MapperInfoClass'intheon-line
Spread Windows Forms Developer’s Guide 447
Copyright © GrapeCity, Inc. All rights reserved.
documentation)classtomapthecellrangetotherangeinthedatasource.
Ifyouaddorremoveacolumnfromthedatasourcewhenboundtoacellrange,theSpreadcomponentdoesnotautomaticallyupdate.
ThedatasourceandthecellrangeintheSpreadarecontrolledbytheMapperInfo('MapperInfoClass'intheon-linedocumentation)class.Theysynchronizewitheachotherviarowsynchronization.Iftheuseraddsorremovesanyrowinthecellrange,itwillaffectthedatasourceandviceversa.Iftheuseraddsanewrowrightbelowtheexistingboundcellrange,thecellrangewillexpandonerowandmaketheMapperInfo('MapperInfoClass'intheon-linedocumentation)classanddatasourceexpandandviceversa.Ifthenewrowisaddedoutsideoftheboundarea,thenitisnotaddedtotheboundrange.
BydefaulttheSpreadcomponenttriestomatchthedatatypeoftheexternaldatasourcetothecelltypeofSpread.YoucansetDataAutoCellTypes('DataAutoCellTypesProperty'intheon-linedocumentation)toFalsetopreventthis.Thefollowingtableshowsthedefaultcelltypethatisusedbasedonthetypeofdata.
DataType CellTypeBoolean Checkboxcell
DateTime Datetimecell
Double,Single,Decimal Numbercell
Int16,Int32,andsoon Numbercell
String Textcell
Other Generalcell
Formoreinformation,refertotheSpreadDataBindingAdpater('SpreadDataBindingAdapterClass'intheon-linedocumentation)classandtheMapperInfo('MapperInfoClass'intheon-linedocumentation)classintheAPIreference.
UsingCode
1. Createyourdataset.2. CreateanewSpreadDataBindingAdapterobject.3. SettheSpreadobjecttotheadapter.4. Setthesheetname.5. CreatetheMapperInfoobjectandlinkittotheadapter.6. SettheFillSpreadDataByDataSourcemethod.
Example
Thisexamplecodebindsasinglecellrangetoadatasource.Theexamplerequiresthatyoucreateadatasourceobjectnamed"dt".
C#FarPoint.Win.Spread.Data.SpreadDataBindingAdapter data = new FarPoint.Win.Spread.Data.SpreadDataBindingAdapter();
Spread Windows Forms Developer’s Guide 448
Copyright © GrapeCity, Inc. All rights reserved.
// Assign the datasource to a data tabledata.DataSource = dt;data.Spread = fpSpread1;data.SheetName = "Sheet1";data.MapperInfo = new FarPoint.Win.Spread.Data.MapperInfo(3, 2, 1, 1);data.FillSpreadDataByDataSource();
VB' Create an adapter.Dim data As New FarPoint.Win.Spread.Data.SpreadDataBindingAdapter' Assign the datasource to a data tabledata.DataSource = dtdata.Spread = FpSpread1data.SheetName = "Sheet1"data.MapperInfo = New FarPoint.Win.Spread.Data.MapperInfo(3, 2, 1, 1)data.FillSpreadDataByDataSource()
Binding a Cell Range in Spread as a Data Source to an External Control
YoucanbindarangeofcellsinSpreadasadatasourceforanexternalcontrolsuchasaDataGridcontrol.Thefollowingdiagramshowstheobjectsinvolved.
Thesearetheobjectsinvolved:
SpreadDataView('SpreadDataViewClass'intheon-linedocumentation)SpreadDataRowView('SpreadDataViewClass'intheon-linedocumentation)ISpreadDataViewDataFormatter('ISpreadDataViewDataFormatterInterface'intheon-linedocumentation)ISpreadDataViewMapper('ISpreadDataViewMapperInterface'intheon-linedocumentation)DefaultSpreadDataViewDataFormatter('DefaultSpreadDataViewDataFormatterClass'intheon-linedocumentation)DefaultSpreadDataViewMapper('DefaultSpreadDataViewMapperClass'intheon-linedocumentation)
CreatingaCustomFormatter
YoucancreateacustomformatterclassbyinheritingfromISpreadDataViewDataFormatter('ISpreadDataViewDataFormatterInterface'intheon-linedocumentation).
Spread Windows Forms Developer’s Guide 449
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
1. Createtheclass.2. Assigntheclasstothedataview.
Example
Thisexamplecodecreatesacustomclass.
C#public class MySpreadDataViewDataFormatter : ISpreadDataViewDataFormatter{private SpreadDataColumn column;private SheetView sheetView;public SheetView SheetView;{get { return sheetView; }set { sheetView = value; }}public MySpreadDataViewDataFormatter(SpreadDataColumn ownerColumn,SheetView sheetView){if (ownerColumn == null){throw new ArgumentNullException("ownerColumn");}column = ownerColumn;this.SheetView = sheetView;}public object GetCellValue(Cell cell){object ret = null;try{ret = this.SheetView.GetValue(cell.Row.Index, cell.Column.Index);ret += ": Customized format";}catch{ret = " No value";}return ret;}public void SetCellValue(Cell cell, object value){this.SheetView.SetValue(cell.Row.Index, cell.Column.Index, value + ": Customized format");}}// Assign new formatterdataSet = BuildDataSet(5,5);this.spreadDataBindingAdapter1.Spread = this.fpSpread1;this.spreadDataBindingAdapter1.SheetName = this.fpSpread1.ActiveSheet.SheetName;this.spreadDataBindingAdapter1.DataSource = dataSet.Tables[0];spreadDataBindingAdapter1.MapperInfo = new MapperInfo(1, 2, 3, 4);MySpreadDataViewDataFormatter testFormatter = new MySpreadDataViewDataFormatter(this.spreadDataBindingAdapter1.SpreadDataView.Columns[2], fpSpread1.ActiveSheet);
Spread Windows Forms Developer’s Guide 450
Copyright © GrapeCity, Inc. All rights reserved.
this.spreadDataBindingAdapter1.SpreadDataView.Columns[2].Formatter = testFormatter;this.spreadDataBindingAdapter1.FillSpreadDataByDataSource();
CreatingaCustomMapper
YoucancreateacustommapperclassbyinheritingfromISpreadDataViewMapper('ISpreadDataViewMapperInterface'intheon-linedocumentation).
UsingCode
1. Createtheclass.2. Assigntheclasstothedataview.
Example
Thisexamplecodecreatesacustomclass.
C#public class MySpreadDataViewMapper : ISpreadDataViewMapper{...}//Assign customized Mapper for SpreadDataViewdataSet = BuildDataSet(5,5);this.spreadDataBindingAdapter1.Spread = this.fpSpread1;this.spreadDataBindingAdapter1.SheetName = this.fpSpread1.ActiveSheet.SheetName;this.spreadDataBindingAdapter1.DataSource = dataSet.Tables[0];MySpreadDataViewMapper testMapper = new MySpreadDataViewMapper ();this.spreadDataBindingAdapter1.SpreadDataView.Mapper = testMapper;spreadDataBindingAdapter1.MapperInfo = new MapperInfo(1, 2, 3, 4);this.spreadDataBindingAdapter1.FillSpreadDataByDataSource();
VBPublic Class MySpreadDataViewMapperImplements FarPoint.Win.Spread.Data.ISpreadDataViewMapper...End ClassdataSet = BuildDataSet(5, 5)Me.spreadDataBindingAdapter1.Spread = Me.fpSpread1Me.spreadDataBindingAdapter1.SheetName = Me.fpSpread1.ActiveSheet.SheetNameMe.spreadDataBindingAdapter1.DataSource = dataSet.Tables(0)Dim testMapper As New MySpreadDataViewMapper()Me.spreadDataBindingAdapter1.SpreadDataView.Mapper = testMapperspreadDataBindingAdapter1.MapperInfo = New MapperInfo(1, 2, 3, 4)Me.spreadDataBindingAdapter1.FillSpreadDataByDataSource()
Customizing Column and Field Binding
Whenasheetisboundtoadataset,columnsareassignedtodatasetfieldssequentially.Thatis,thefirstdatafieldisassignedtocolumnA,thesecondtocolumnB,andsoon.Youcanchangetheassignmentstoassignanyfieldtoanycolumn.
Forboundspreadsheets,bydefaultthespreadsheetinheritsthewidthofthecolumnsfromthedatabase.Todetermine
Spread Windows Forms Developer’s Guide 451
Copyright © GrapeCity, Inc. All rights reserved.
yourowncustomwidths,youwouldeitherneedtosetyourwidthafterbindingtheSpreadorsetDataAutoSizeColumns('DataAutoSizeColumnsProperty'intheon-linedocumentation)toFalseandsetyourwidth.
IfyouhavemorethanoneSpreadboundtoasingledataset,youmaywanttosettheAutoGenerateColumns('AutoGenerateColumnsProperty'intheon-linedocumentation)propertyofthesheetineachSpreadtoFalse,soSpreaddoesnotbindallthecolumns.ThenyoucansettheDataField('DataFieldProperty'intheon-linedocumentation)propertyofthecolumnsineachoftheSpreadcontrolstothefieldnamefromthedataset.Then,onlythatcolumnofthedatasetisboundtotheSpread.
UsingthePropertiesWindow
1. Createyourdataset.2. InthePropertieswindow,selecttheSpreadcomponent.3. SelecttheDataSourceproperty(fortheSpreadcomponent)orselecttheSheetspropertyandsettheDataSourceproperty,andsetitequaltothedataset.
4. Ifyouhavenotalreadydoneso,selecttheSheetspropertyfortheSpreadcomponent.5. ClickthebuttontodisplaytheSheetViewCollectionEditor.6. Clickthesheetforwhichyouwanttochangethecolumnfields.7. Setthesheet’sAutoGenerateColumnspropertytoFalse,becauseyouwanttooverridetheauto-generatedcolumnandfieldmappings.
8. Inthepropertylist,selecttheCellspropertyandclickthebuttontodisplaytheCell,Column,andRowEditor.
9. Selectthecolumnforwhichyouwanttochangethecolumnfields.10. SettheDataFieldpropertytoselectoneoftheavailablefields,orleaveitblanktomakethecolumnanunbound
column.11. ClickOKtoclosetheCell,Column,andRowEditor.12. ClickOKtoclosetheSheetViewCollectionEditor.
UsingaShortcut
1. Createyourdataset.2. SettheSheetAutoGenerateColumnpropertytofalse,becauseyouwanttooverridetheauto-generated
columnandfieldmappings.3. SettheFpSpreadobject'sorSheetobject'sDataSourcepropertyequaltothedataset.4. Foreachcolumninthesheetforwhichyouwanttomapafield,settheColumnobject'sDataFieldpropertyto
thefieldnameinthedataset.
Example
ThisexamplecodebindstheSpreadcomponenttoanexistingdataset,thensetsthefieldstouseinthefirstfourcolumns.
C#// Turn off automatic column and field mapping.fpSpread1.Sheets[0].AutoGenerateColumns = false;// Bind the component to the data set.fpSpread1.DataSource = dataSet1;// Set the fields for the columns.fpSpread1.Sheets[0].Columns[0].DataField = "Description";fpSpread1.Sheets[0].Columns[1].DataField = "ID";fpSpread1.Sheets[0].Columns[2].DataField = "LeadTime";fpSpread1.Sheets[0].Columns[3].DataField = "Price";
Spread Windows Forms Developer’s Guide 452
Copyright © GrapeCity, Inc. All rights reserved.
VB' Turn off automatic column and field mapping.FpSpread1.Sheets(0).AutoGenerateColumns = False' Bind the component to the data set.FpSpread1.DataSource = DataSet1' Set the fields for the columns.FpSpread1.Sheets(0).Columns(0).DataField = "Description"FpSpread1.Sheets(0).Columns(1).DataField = "ID"FpSpread1.Sheets(0).Columns(2).DataField = "LeadTime"FpSpread1.Sheets(0).Columns(3).DataField = "Price"
UsingCode
1. Createyourdataset.2. CreateanewSheetViewobject.3. SettheSheetViewobject'sAutoGenerateColumnpropertytoFalse,becauseyouwanttooverridetheauto-
generatedcolumnandfieldmappings.4. SettheSheetViewobject'sDataSourcepropertyequaltothedataset.5. Foreachcolumnforwhichyouwanttomapthefields,settheSheetViewobject'sColumnsobjectDataFieldpropertytospecifythefield.
6. AssigntheSheetViewobjecttoasheetinthecomponent.
Example
ThisexamplecodecreatesaboundSheetViewobjectandmapsfourfieldstofourcolumns,thenassignsittoasheetinaSpreadcomponent.
C#// Create a new SheetView object.FarPoint.Win.Spread.SheetView newsheet = new FarPoint.Win.Spread.SheetView();// Turn off automatic column and field mapping.newsheet.AutoGenerateColumns = false;// Bind the SheetView object to the data set.newsheet.DataSource = dataSet1;// Set the fields for the columns.newsheet.Columns[0].DataField = "Description";newsheet.Columns[1].DataField = "ID";newsheet.Columns[2].DataField = "LeadTime";newsheet.Columns[3].DataField = "Price";// Assign the SheetView object to the first sheet.fpSpread1.Sheets[0] = newsheet;
VB' Create a new SheetView object.Dim newsheet As New FarPoint.Win.Spread.SheetView()' Turn off automatic column and field mapping.newsheet.AutoGenerateColumns = False' Bind the SheetView object to the data set.newsheet.DataSource = DataSet1' Set the fields for the columns.newsheet.Columns(0).DataField = "Description"newsheet.Columns(1).DataField = "ID"
Spread Windows Forms Developer’s Guide 453
Copyright © GrapeCity, Inc. All rights reserved.
newsheet.Columns(2).DataField = "LeadTime"newsheet.Columns(3).DataField = "Price"' Assign the SheetView object to the first sheet.FpSpread1.Sheets(0) = newsheet
UsingtheSpreadDesigner
1. Createyourdataset.2. SettheFpSpreadobject'sorSheetobject'sDataSourcepropertyequaltothedataset.3. OpentheSpreadDesignerfortheSpreadcomponent.4. Selectthesheettabforthesheetforwhichyouwanttosetthecolumnfields.5. SettheAutoGenerateColumnpropertytoFalse,becauseyouwanttooverridetheauto-generatedcolumnandfieldmappings.
6. Selectthecolumnforwhichyouwanttosetthedatafield.7. SettheDataFieldpropertytothefieldyouwanttodisplayintheselectedcolumn.8. ContinuetoselectcolumnsandsettheirDataFieldpropertiesuntilyouhavesetallthecolumnsyouwant.You
canleavesomeofthecolumnsunboundifyouwanttodoso.9. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Binding a Combo Box to a DataReader
YoucanbindacomboboxtoaDataReader.ADataReaderletsyouaccessdatainaread-only,forward-onlywayfromadatasource.UsingaDataReaderisoftenaquickwayofreturningresults,asillustratedinthefollowingexampleforpopulatingresultsinacombobox.
Example
Thisexampleaddsdatatoacombocellfromadatasource.
C#/// Set up a connection to the database. The database name is an example.string dbpath = "c:\\reader.mdb";System.Data.OleDb.OleDbConnection dbConn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + dbpath);/// Open a connection and a SELECT command.dbConn.Open();System.Data.OleDb.OleDbCommand dbCommand = new System.Data.OleDb.OleDbCommand("SELECT * FROM Table1", dbConn);/// Open a DataReader on that connection and command.System.Data.OleDb.OleDbDataReader dr = dbCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);/// Loop through the rows returned by the reader.ArrayList al = new ArrayList();while (dr.Read()) { al.Add(dr("Data"));}/// Populate combo box with data converted to strings.string[] s;s = al.ToArray(typeof(string));FarPoint.Win.Spread.ComboBoxCellType cb = new FarPoint.Win.Spread.ComboBoxCellType();cb.Items = s;FpSpread1.ActiveSheetView.Cells(0, 0).CellType = cb;
Spread Windows Forms Developer’s Guide 454
Copyright © GrapeCity, Inc. All rights reserved.
/// Dispose connection.dbConn.Dispose();
VB' Set up a connection to the database. The database name is an example.Dim dbpath As String = "c:\reader.mdb"Dim dbConn As New System.Data.OleDb.OleDbConnection( _"Provider=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" & dbpath)' Open a connection and a SELECT command.dbConn.Open()Dim dbCommand As New System.Data.OleDb.OleDbCommand( _"SELECT * FROM Table1", dbConn)' Open a DataReader on that connection and command.Dim dr As System.Data.OleDb.OleDbDataReader = dbCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection)' Loop through the rows returned by the reader.Dim al As New ArrayList()While dr.Read() al.Add(dr("Data"))End While' Populate combo box with data converted to strings.Dim s As String()s = al.ToArray(GetType(String))Dim cb As New FarPoint.Win.Spread.ComboBoxCellTypecb.Items = sFpSpread1.ActiveSheetView.Cells(0, 0).CellType = cb' Dispose connection.dbConn.Dispose()
Adding to Bound Data
Youcanaddrowsorcolumnstobounddata.
Thetasksyoucanperformtoaddrowsorcolumnsinclude:
AddingaRowtoaBoundSheetAddinganUnboundRowtoaBoundSheetAddinganUnboundColumntoaBoundSheet
Adding a Row to a Bound Sheet
Onceyoubindasheettoadatasetyoumightwanttoaddanunboundrowtocontainadditionaldata.TherowcouldthenbeboundusingtheAddRowToDataSource('AddRowToDataSourceMethod'intheon-linedocumentation)method.
ThefollowingfigureshowsasheetinaSpreadcomponentthatcontainsdatafromadatasetandanunboundrowatthebottomthatcalculatestheaverages.
Spread Windows Forms Developer’s Guide 455
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
1. Createyourdataset.2. SettheFpSpreadobject'sDataSource('DataSourceProperty'intheon-linedocumentation)property
equaltothedataset.3. CalltheSheetViewobject'sAddUnboundRows('AddUnboundRowsMethod'intheon-linedocumentation)methodtospecifywheretoaddtheunboundrow.
4. Setpropertiesfortheunboundrow.5. SettheSheetViewobject'sAddRowToDataSource('AddRowToDataSourceMethod'intheon-linedocumentation)methodifyouwanttoaddtherowtothedatasource.
Example
ThisexamplecodecreatesaboundFpSpreadobjectandaddsanunboundrowtoit.
C#DataSet ds = new DataSet();DataTable emp = new DataTable("Name");emp.Columns.Add("LastName");emp.Columns.Add("GPA (Single)", typeof(decimal));emp.Columns.Add("GPA (Double)", typeof(decimal));emp.Rows.Add(new Object[] { "Shorter", "4.12", "4.12" });emp.Rows.Add(new Object[] { "Williams", "2.00", "2.00" });emp.Rows.Add(new Object[] { "Zacheius", "3.62", "3.62" });ds.Tables.Add(emp);fpSpread1.DataSource = ds;fpSpread1.ActiveSheet.AddUnboundRows(3, 1);fpSpread1.ActiveSheet.Cells[3, 0].Text = "Average";fpSpread1.ActiveSheet.Cells[3, 1].Formula = "AVERAGE(B1:B3)";fpSpread1.ActiveSheet.Cells[3, 2].Formula = "AVERAGE(C1:C3)";//fpSpread1.ActiveSheet.AddRowToDataSource(3, true);
VBDim ds = New DataSet()Dim emp As New DataTable("Name")emp.Columns.Add("LastName")emp.Columns.Add("GPA (Single)", GetType(Decimal))emp.Columns.Add("GPA (Double)", GetType(Decimal))emp.Rows.Add(New Object() {"Shorter", "4.12", "4.12"})emp.Rows.Add(New Object() {"Williams", "2.00", "2.00"})emp.Rows.Add(New Object() {"Zacheius", "3.62", "3.62"})ds.Tables.Add(emp)FpSpread1.DataSource = dsFpSpread1.ActiveSheet.AddUnboundRows(3, 1)FpSpread1.ActiveSheet.Cells(3, 0).Text = "Average"FpSpread1.ActiveSheet.Cells(3, 1).Formula = "AVERAGE(B1:B3)"FpSpread1.ActiveSheet.Cells(3, 2).Formula = "AVERAGE(C1:C3)"'FpSpread1.ActiveSheet.AddRowToDataSource(3, True)
Adding an Unbound Row to a Bound Sheet
Onceyoubindasheettoadatasetyoumightwanttoaddanunboundrowtocontainadditionaldata.
Spread Windows Forms Developer’s Guide 456
Copyright © GrapeCity, Inc. All rights reserved.
ThefollowingfigureshowsasheetinaSpreadcomponentthatcontainsdatafromadatasetandanunboundrowatthebottomthatcalculatestheaverages.
UsingaShortcut
1. Createyourdataset.2. SettheFpSpreadobject'sorSheetobject'sDataSource('DataSourceProperty'intheon-linedocumentation)propertyequaltothedataset.
3. CalltheSheetobject'sAddUnboundRows('AddUnboundRowsMethod'intheon-linedocumentation)methodtospecifywheretoaddtheunboundrow.
4. Setpropertiesfortheunboundrow.
Example
ThisexamplecodebindstheSpreadcomponenttoadatasetthenaddsanunboundrow.
C#// Bind the component to the data set.fpSpread1.DataSource = dbDataSet;// Add an unbound row.fpSpread1.Sheets[0].AddUnboundRows(20, 1);
VB' Bind the component to the data set.FpSpread1.DataSource = dbDataSet' Add an unbound row.FpSpread1.Sheets(0).AddUnboundRows(20, 1)
UsingCode
1. Createyourdataset.2. CreateanewSheetViewobject.3. SettheSheetViewobject'sDataSource('DataSourceProperty'intheon-linedocumentation)
propertyequaltothedataset.4. CalltheSheetViewobject'sAddUnboundRows('AddUnboundRowsMethod'intheon-linedocumentation)methodtospecifywheretoaddtheunboundrow.
5. Setpropertiesfortheunboundrow.6. AssigntheSheetViewobjecttoasheetinthecomponent.
Example
ThisexamplecodecreatesaboundSheetViewobjectandaddsanunboundrowtoit,thenassignsittoasheetina
Spread Windows Forms Developer’s Guide 457
Copyright © GrapeCity, Inc. All rights reserved.
Spreadcomponent.
C#// Create a new SheetView object.FarPoint.Win.Spread.SheetView newsheet = new FarPoint.Win.Spread.SheetView();// Bind the SheetView object to the data set.newsheet.DataSource = dataSet1;// Add an unbound row.newsheet.AddUnboundRows(20, 1);// Assign the SheetView object to the first sheet.fpSpread1.Sheets[0] = newsheet;
VB' Create a new SheetView object.Dim newsheet As New FarPoint.Win.Spread.SheetView()' Bind the SheetView object to the data set.newsheet.DataSource = DataSet1' Add an unbound row.newsheet.AddUnboundRows(20, 1)' Assign the SheetView object to the first sheet.FpSpread1.Sheets(0) = newsheet
Adding an Unbound Column to a Bound Sheet
Onceyoubindasheettoadatasetyoumightwanttoaddanunboundcolumntocontainadditionaldata.
YoucanaddanunboundcolumntotheSpreadcontrolbyincreasingtheColumnCount('ColumnCountProperty'intheon-linedocumentation)propertyafterthecontrolisbound.AnotheroptionistousetheDataField('DataFieldProperty'intheon-linedocumentation)propertytobindspecificcolumnsandleavetheDataField('DataFieldProperty'intheon-linedocumentation)propertyunsetforthecolumnsyoudonotwanttobind.
UsingCode
1. Createyourdataset.2. SettheFpSpreadobject'sorSheetobject'sDataSource('DataSourceProperty'intheon-linedocumentation)propertyequaltothedataset.
3. SettheColumnCount('ColumnCountProperty'intheon-linedocumentation)propertyforthesheet.
Example
ThisexamplecodebindstheSpreadcomponenttoadatasetandthensetsthecolumncount.
C#// Bind the component to the data set.fpSpread1.DataSource = dbDataSet;// If this datasource has 19 columns, set the count to 20.fpSpread1.Sheets[0].ColumnCount=20;
VB' Bind the component to the data set.FpSpread1.DataSource = dbDataSet' If this datasource has 19 columns, set the count to 20.
Spread Windows Forms Developer’s Guide 458
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.Sheets(0).ColumnCount=20
Customizing Data Binding
Youcancustomizethedisplayincludingheaders,celltypes,andhierarchicaldisplay.
Thetasksyoucanperformforcustomizingthedisplayofbounddatainclude:
CustomizingColumnHeadersforBoundSheetsCustomizingCellTypesforBoundSheetsWorkingwithHierarchicalDataDisplayCreatingaHierarchicalDisplayManuallyCreatingCustomHierarchyIcons
Customizing Column Headers for Bound Sheets
Bydefault,sheetsdisplaythefieldnamesinthecolumnheaderswhenboundtoadataset.Ifyouprefer,youcanchangethetexttodisplaycustomcolumnnames.
UsingthePropertiesWindow
1. Createyourdataset.2. InthePropertieswindow,selecttheSpreadcomponent.3. SelecttheDataSourceproperty(fortheSpreadcomponent)orselecttheSheetspropertyandsettheDataSourceproperty,andsetitequaltothedataset.
4. Ifyouhavenotalreadydoneso,selecttheSheetspropertyfortheSpreadcomponent.5. ClickthebuttontodisplaytheSheetViewCollectionEditor.6. Clickthesheetforwhichyouwanttochangethecolumnheadings.7. Ifyouareprovidingcustomtextforeverycolumnheader,settheDataAutoHeadingspropertytoFalsesothesheetdoesnotdisplaythefieldnamesfromthedatasetasthecolumnheadertext.
8. Inthepropertylist,selecttheCellspropertyandclickthebuttontodisplaytheCell,Column,andRowEditor.
9. Selectthecolumnforwhichyouwanttochangethecolumnheadings.10. SettheLabelpropertytothenewtextyouwantintheheading.11. Repeatsteps8and9foreachcolumnforwhichyouwanttosetthecolumnheading.12. ClickOKtoclosetheCell,Column,andRowEditor.13. ClickOKtoclosetheSheetViewCollectionEditor.
UsingaShortcut
1. Createyourdataset.2. SettheFpSpreadobject'sorSheetobject'sDataSourcepropertyequaltothedataset.3. Ifyouareprovidingcustomtextforeverycolumnheader,settheSheetobject'sDataAutoHeadingsproperty
toFalsesothesheetdoesnotdisplaythefieldnamesfromthedatasetasthecolumnheadertext.4. SettheTextpropertyoftheColumnHeadercellstospecifythecustomtext.
Example
ThisexamplecodebindstheSpreadcomponenttoadatasetthencustomizesthefirstcolumnheader.
Spread Windows Forms Developer’s Guide 459
Copyright © GrapeCity, Inc. All rights reserved.
C#// Bind the component to the data set.fpSpread1.DataSource = dbDataSet;// Set custom text in the first column header.fpSpread1.Sheets[0].ColumnHeader.Cells[0, 0].Text = "Student ID";
VB' Bind the component to the data set.FpSpread1.DataSource = dbDataSet' Set custom text in the first column header.FpSpread1.Sheets(0).ColumnHeader.Cells(0, 0).Text = "Student ID"
UsingCode
1. Createyourdataset.2. CreateanewSheetViewobject.3. SettheSheetViewobject'sDataSourcepropertyequaltothedataset.4. Ifyouareprovidingcustomtextforeverycolumnheader,settheSheetViewobject'sDataAutoHeadings
propertytoFalsesothesheetdoesnotdisplaythefieldnamesfromthedatasetasthecolumnheadertext.5. SettheTextpropertyforColumnHeadercellstospecifythecustomtext.6. AssigntheSheetViewobjecttoasheetinthecomponent.
Example
ThisexamplecodecreatesaboundSheetViewobjectandcustomizesthetextinthefirstcolumnheadercell,thenassignsittoasheetinaSpreadcomponent.
C#// Create a new SheetView object.FarPoint.Win.Spread.SheetView newsheet = new FarPoint.Win.Spread.SheetView();// Bind the SheetView object to the data set.newsheet.DataSource = dataSet1;// Change the column header text in the first header cell.newsheet.ColumnHeader.Cells[0, 0].Text = "Student ID";// Assign the SheetView object to the first sheet.fpSpread1.Sheets[0] = newsheet;
VB' Create a new SheetView object.Dim newsheet As New FarPoint.Win.Spread.SheetView()' Bind the SheetView object to the data set.newsheet.DataSource = DataSet1' Change the column header text in the first header cell.newsheet.ColumnHeader.Cells(0, 0).Text = "Student ID"' Assign the SheetView object to the first sheet.FpSpread1.Sheets(0) = newsheet
UsingtheSpreadDesigner
1. Createyourdataset.2. SettheFpSpreadobject'sorSheetobject'sDataSourcepropertyequaltothedataset.
Spread Windows Forms Developer’s Guide 460
Copyright © GrapeCity, Inc. All rights reserved.
3. OpentheSpreadDesignerfortheSpreadcomponent.4. Selectthesheettabforthesheetforwhichyouwanttosetthecustomheadertext.5. Ifyouareprovidingcustomtextforeverycolumnheader,settheDataAutoHeadingspropertytoFalsesothesheetdoesnotdisplaythefieldnamesfromthedatasetasthecolumnheadertext.
6. Selectthecolumnforwhichyouwanttosetcustomheadertext,thenright-clickandchooseHeaders.7. IntheHeaderEditor,double-clicktheheaderforwhichyouwanttodisplaycustomtext.8. Editthetexttobethecustomtextyouwant,andthenpressEntertostopediting.9. Whenyouhaveeditedalltheheadertextyouwanttoedit,clickOKtoclosetheHeaderEditor,thenclickYes
toapplyyourchangestotheselection.10. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing Cell Types for Bound Sheets
Bydefault,whentheSpreadcomponentorsheetisboundtoadataset,itsetsthecelltypesfortheboundrowsbasedonthedatainthedataset.Youcanturnoffthisautomaticcelltypeassignmentandassigncelltypesyourself.
UsingthePropertiesWindow
1. Createyourdataset.2. InthePropertieswindow,selecttheSpreadcomponent.3. SelecttheDataSourceproperty(fortheSpreadcomponent)orselecttheSheetspropertyandsettheDataSourceproperty,andsetitequaltothedataset.
4. Ifyouhavenotalreadydoneso,selecttheSheetspropertyfortheSpreadcomponent.5. ClickthebuttontodisplaytheSheetViewCollectionEditor.6. Clickthesheetforwhichyouwanttochangethecelltypes.7. SettheDataAutoCellTypespropertytoFalsesothesheetdoesnotautomaticallyassignthecelltypesforthecolumns.
8. Inthepropertylist,selecttheColumnspropertyandclickthebuttontodisplaytheCell,Column,andRowEditor.
9. Selectthecolumnforwhichyouwanttochangethecelltype.10. SettheCellTypepropertytothecelltypeyouwanttouseforthecolumn.11. Repeatsteps8and9foreachcolumnforwhichyouwanttosetthecelltype.12. ClickOKtoclosetheCell,Column,andRowEditor.13. ClickOKtoclosetheSheetViewCollectionEditor.
UsingaShortcut
1. Createyourdataset.2. SettheFpSpreadobject'sorSheetobject'sDataSource('DataSourceProperty'intheon-linedocumentation)propertyequaltothedataset.
3. SettheSheetobject’sDataAutoCellTypes('DataAutoCellTypesProperty'intheon-linedocumentation)propertytoFalsesothesheetdoesnotautomaticallyassignthecelltypesforthecolumns.
4. SettheColumnobject'sCellType('CellTypeProperty'intheon-linedocumentation)propertytospecifythecelltypeforeachcolumn.
Example
ThisexamplecodebindstheSpreadcomponenttoadatasetthenassignsthecelltypesforitsthreecolumns.
C#
Spread Windows Forms Developer’s Guide 461
Copyright © GrapeCity, Inc. All rights reserved.
// Bind the component to the data set.fpSpread1.DataSource = dbDataSet;// Turn off automatic cell type assignment.fpSpread1.Sheets[0].DataAutoCellTypes = false;// Set the first column as general cell type.FarPoint.Win.Spread.CellType.GeneralCellType generalct = new FarPoint.Win.Spread.CellType.GeneralCellType();fpSpread1.Sheets[0].Columns[0].CellType = generalct;// Set the second column as number cell type.FarPoint.Win.Spread.CellType.NumberCellType numberct = new FarPoint.Win.Spread.CellType.NumberCellType();fpSpread1.Sheets[0].Columns[1].CellType = numberct;// Set the third column as currency cell type.FarPoint.Win.Spread.CellType.CurrencyCellType currct = new FarPoint.Win.Spread.CellType.CurrencyCellType();fpSpread1.Sheets[0].Columns[2].CellType = currct;
VB' Bind the component to the data set.FpSpread1.DataSource = dbDataSet' Turn off automatic cell type assignment.FpSpread1.Sheets(0).DataAutoCellTypes = False' Set the first column as general cell type.Dim generalct As New FarPoint.Win.Spread.CellType.GeneralCellType()FpSpread1.Sheets(0).Columns(0).CellType = generalct' Set the second column as number cell type.Dim numberct As New FarPoint.Win.Spread.CellType.NumberCellType()FpSpread1.Sheets(0).Columns(1).CellType = numberct' Set the third column as currency cell type.Dim currct As New FarPoint.Win.Spread.CellType.CurrencyCellType()FpSpread1.Sheets(0).Columns(2).CellType = currct
UsingCode
1. Createyourdataset.2. CreateanewSheetViewobject.3. SettheSheetViewobject'sDataSourcepropertyequaltothedataset.4. Ifyouareprovidingcustomtextforeverycolumnheader,settheSheetViewobject'sDataAutoHeadings
propertytoFalsesothesheetdoesnotdisplaythefieldnamesfromthedatasetasthecolumnheadertext.5. SettheTextpropertyoftheColumnHeadercellstospecifythecustomtext.6. AssigntheSheetViewobjecttoasheetinthecomponent.
Example
ThisexamplecodecreatesaboundSheetViewobjectandcustomizesthetextinthefirstcolumnheadercell,thenassignsittoasheetinaSpreadcomponent.
C#// Create a new SheetView object.FarPoint.Win.Spread.SheetView newsheet = new FarPoint.Win.Spread.SheetView();// Bind the SheetView object to the data set.newsheet.DataSource = dataSet1;// Change the column header text in the first header cell.
Spread Windows Forms Developer’s Guide 462
Copyright © GrapeCity, Inc. All rights reserved.
newsheet.ColumnHeader.Cells[0, 0].Text = "Student ID";// Assign the SheetView object to the first sheet.fpSpread1.Sheets[0] = newsheet;
VB' Create a new SheetView object.Dim newsheet As New FarPoint.Win.Spread.SheetView()' Bind the SheetView object to the data set.newsheet.DataSource = DataSet1' Change the column header text in the first header cell.newsheet.ColumnHeader.Cells(0, 0).Text = "Student ID"' Assign the SheetView object to the first sheet.FpSpread1.Sheets(0) = newsheet
UsingtheSpreadDesigner
1. Createyourdataset.2. SettheFpSpreadobject'sorSheetobject'sDataSourcepropertyequaltothedataset.3. OpentheSpreadDesignerfortheSpreadcomponent.4. Selectthesheettabforthesheetforwhichyouwanttosetthecelltypes.5. SettheDataAutoCellTypespropertytoFalsesothesheetdoesnotautomaticallyassignthecelltypesforthecolumns.
6. Selectthecolumnforwhichyouwanttosetthecelltype.7. Inthepropertylist,settheCellTypepropertytothecelltypeyouwanttouseforthecolumn.8. Repeatsteps6and7foreachcolumnforwhichyouwanttosetthecelltype.9. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Working with Hierarchical Data Display
Sheetscandisplayrelationaldata,suchasfromarelationaldatabase,inhierarchicalviews.Thefollowingfigureshowsanexampleofsuchahierarchicalview,whichusesthedatabaseprovidedforthetutorials.Theusercanexpandorcollapsethelevelsofthehierarchybyclickingontheexpandandcollapsehierarchyicons(plusandminussigns).
Spread Windows Forms Developer’s Guide 463
Copyright © GrapeCity, Inc. All rights reserved.
Tosetuphierarchicaldatadisplay,youfirstcreateadatasettoholdtherelationaldata,thendefinetherelationsbetweenthedata,andfinally,settheSpreadcomponenttodisplaythedataasyouwant.Youcancustomizethecelltype,thecolors,theheaders,andotheraspectsoftheappearanceofthechildview.
Youcanbindtoahierarchicalcollection.
Ifyousetaskinforasheet,youmustapplythatskintotheparentsheetandallthechildsheets.Formoreinformationaboutskins,refertoApplyingaSkintoaSheet.
Youcansetthedisplayofthehierarchy,whichSpreadtreatsaschildviewsoftheoverallparentsheet.YoucangetinformationaboutchildviewsusingthesepropertiesoftheSheetView('SheetViewClass'intheon-linedocumentation)class.
ChildRelationCount('ChildRelationCountProperty'intheon-linedocumentation)GetChildDataModel('GetChildDataModelMethod'intheon-linedocumentation)GetChildRelation('GetChildRelationMethod'intheon-linedocumentation)GetChildSheets('GetChildSheetsMethod'intheon-linedocumentation)GetChildView('GetChildViewMethod'intheon-linedocumentation)GetChildVisible('GetChildVisibleMethod'intheon-linedocumentation)ParentRelationName('ParentRelationNameProperty'intheon-linedocumentation)
Youcancatchwhentheenduserisexpandingorcollapsingthechildview.Formoreinformation,seetheExpand('ExpandEvent'intheon-linedocumentation)eventandtheChildViewCreated('ChildViewCreatedEvent'intheon-linedocumentation)event.YoucandetermineiftherowisexpandableusingtheGetRowExpandable('GetRowExpandableMethod'intheon-linedocumentation)andSetRowExpandable('SetRowExpandableMethod'intheon-linedocumentation)methods,andiftherowisexpandedusingtheIsRowExpanded('IsRowExpandedMethod'intheon-linedocumentation)method.
IfyouneedtosetpropertiesonthechildSpreadView,thebestplacetoputcodetodothatisintheChildWorkbookCreatedevent.ThateventfireswhenachildSpreadViewhasbeencreated.TheChildViewCreatedeventfiresafterthechildSheetViewhasbeencreated,butthechildSpreadViewdoesnotgetcreateduntilafterward,anditdoesnotgetcreatedunlessthechildsheetisvisibleinthecomponent(sothatthelayoutcalculationsarefaster).
Ratherthandeletingchildsheetsfromaparentsheet,whenworkingwithbounddata,youwoulddeletetherelationinyourdatasourcetodeletethatchildsheetfromSpread.
Thefollowingsamplecodeassumesyouwanttoremovethefirstchildsheetreturned,inthisexample,alist(0):
CodeDim alist As ArrayList = FpSpread1.Sheets(0).GetChildSheets()Dim sv As FarPoint.Win.Spread.SheetView = alist(0)Dim ds As DataSet = CType(FpSpread1.DataSource, DataSet)ds.Relations.Remove(sv.ParentRelationName)
Formoreinformationaboutprintingahierarchicalsheet,refertoPrintingaChildViewofaHierarchicalDisplay.
ForasmallexampleseetheTutorial:BindingtoaCorporateDatabase(OlderVisualStudio).
UsingaShortcut
1. Createyourdataset.2. Setupthedatarelationsbetweenthedatacomingfromthedataset,forexample,betweentablescomingfroma
relationaldatabase.3. SettheDataSourcepropertyoftheFpSpreadortheSheetViewobjectequaltothedataset.4. ProvidecodeintheChildViewCreatedeventoftheSpreadcomponentfordisplayingtheparentandchild
viewsofthedata.
Spread Windows Forms Developer’s Guide 464
Copyright © GrapeCity, Inc. All rights reserved.
Example
ThisexamplecodebindstheSpreadcomponenttoadatasetthatcontainsmultiplerelatedtablesfromadatabase,andsetsupthecomponenttodisplayhierarchicalviews.Thiscodeexampleusesthedatabaseprovidedforthetutorials(databind.mdb).Ifyouperformedthedefaultinstallation,thedatabasefileisin\ProgramFiles\GrapeCity\Spread.NET11\Docs\WindowsForms\TutorialFiles.
VBPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Call subroutines to set up data and format the Spread component InitData() FormatSpread()End Sub
Private Sub InitData()Dim con As New OleDb.OleDbConnection()Dim cmd As New OleDb.OleDbCommand()Dim da As New OleDb.OleDbDataAdapter()Dim ds As New DataSet()Dim dt As DataTable
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\ProgramFiles (x86)\ComponentOne\Spread.NET 11\Docs\Windows Forms\TutorialFiles\databind.mdb"con.Open()With cmd.Connection = con.CommandType = CommandType.TableDirect.CommandText = "Categories"End Withda.SelectCommand = cmdda.Fill(ds, "Categories")cmd.CommandText = "Products"da.SelectCommand = cmdda.Fill(ds, "Products")cmd.CommandText = "Inventory Transactions"da.SelectCommand = cmdda.Fill(ds, "Inventory Transactions")ds.Relations.Add("Root", ds.Tables("Categories").Columns("CategoryID"), ds.Tables("Products").Columns("CategoryID"))ds.Relations.Add("Secondary", ds.Tables("Products").Columns("ProductID"), ds.Tables("Inventory Transactions").Columns("TransactionID"))FpSpread1.DataSource = dsEnd Sub
Private Sub FormatSpread()With FpSpread1.Sheets(0).ColumnHeader.Rows(0).Height = 30.Columns(0).Visible = FalseEnd WithEnd Sub
Private Sub FpSpread1_ChildViewCreated(ByVal sender As Object, ByVal e As FarPoint.Win.Spread.ChildViewCreatedEventArgs) HandlesFpSpread1.ChildViewCreatedDim dateType As New FarPoint.Win.Spread.CellType.DateTimeCellType()
Spread Windows Forms Developer’s Guide 465
Copyright © GrapeCity, Inc. All rights reserved.
If e.SheetView.ParentRelationName = "Root" ThenWith e.SheetView.DataAutoCellTypes = False.DataAutoSizeColumns = False.ColumnHeader.Rows(0).Height = 30.Columns(0).Visible = False.Columns(3).Visible = False.Columns(4).Visible = False.Columns(1).Width = 200.Columns(2).Width = 185.Columns(6).Width = 85.Columns(7).Width = 80.Columns(8).Width = 80.Columns(5).CellType = New FarPoint.Win.Spread.CellType.CurrencyCellType().Columns(7).CellType = New FarPoint.Win.Spread.CellType.CheckBoxCellType()End WithElseWith e.SheetView.DataAutoCellTypes = False.DataAutoSizeColumns = False.ColumnHeader.Rows(0).Height = 30.Columns(0).Visible = False.Columns(2).Visible = False.Columns(3).Visible = False.Columns(4).Visible = False.Columns(7).Visible = False.Columns(8).Visible = False.Columns(9).Visible = False.Columns(1).Width = 100.Columns(6).Width = 80.Columns(5).CellType = New FarPoint.Win.Spread.CellType.CurrencyCellType()dateType.DateTimeFormat = FarPoint.Win.Spread.CellType.DateTimeFormat.ShortDate.Columns(1).CellType = dateType'Add a total column.ColumnCount = .ColumnCount + 1.ColumnHeader.Cells(0, .ColumnCount - 1).Value = "Total".Columns(.ColumnCount - 1).CellType = New FarPoint.Win.Spread.CellType.CurrencyCellType().Columns(.ColumnCount - 1).Formula = "F1*G1"End WithEnd If
End Sub
UsingaShortcut
1. Createyourdataset.2. Setupthedatarelationsbetweenthedatacomingfromthedataset,forexample,betweentablescomingfroma
relationaldatabase.3. SettheFpSpreadobjectortheSheetobjectDataSourcepropertyequaltothedataset.4. ProvidecodeintheFpSpreadChildViewCreatedeventfordisplayingtheparentandchildviewsofthedata.
Example
ThisexamplecodebindstheSpreadcomponenttoahierarchicalcollection.
Spread Windows Forms Developer’s Guide 466
Copyright © GrapeCity, Inc. All rights reserved.
C#public class Score{private string classname;private string grade;public string ClassName{get { return classname; }set { classname = value; }}public string Grade{get { return grade; }set { grade = value; }}}
public class Student{private string name;private string id;private ArrayList score = new ArrayList();public string Name{get { return name; }set { name = value; }}public string Id{get { return id; }set { id = value; }}public ArrayList Score{get { return score; }}}
private void Form1_Load(object sender, System.EventArgs e){ArrayList list = new ArrayList();Student s = new Student();s.Name = "John Smith";s.Id = "100001";Score sc = new Score();sc.ClassName = "math";sc.Grade = "A";s.Score.Add(sc);sc = new Score();sc.ClassName = "English";sc.Grade = "A";s.Score.Add(sc);list.Add(s);s = new Student();s.Name = "David Black";s.Id = "100002";
Spread Windows Forms Developer’s Guide 467
Copyright © GrapeCity, Inc. All rights reserved.
sc = new Score();sc.ClassName = "math";sc.Grade = "B";s.Score.Add(sc);sc = new Score();sc.ClassName = "English";sc.Grade = "A";s.Score.Add(sc);list.Add(s);fpSpread1_Sheet1.DataSource = list;}
VBPublic Class ScorePrivate classn as StringPrivate grade As StringPublic Property ClassName() As StringGetReturn classnEnd GetSet(ByVal Value As String)classn = ValueEnd SetEnd Property
Public Property Grades() As StringGetReturn gradeEnd GetSet(ByVal Value As String)grade = ValueEnd SetEnd PropertyEnd Class
Public Class studentPrivate name As StringPrivate id As StringPrivate sco As ArrayList = New ArrayList()Public Property names() As StringGetReturn nameEnd GetSet(ByVal Value As String)name = ValueEnd SetEnd Property
Public Property ids() As StringGetReturn idEnd GetSet(ByVal Value As String)id = ValueEnd SetEnd Property
Spread Windows Forms Developer’s Guide 468
Copyright © GrapeCity, Inc. All rights reserved.
Public ReadOnly Property score() As ArrayListGetReturn scoEnd GetEnd PropertyEnd Class
'Form LoadDim list As ArrayList = New ArrayList()Dim s As student = New student()s.names = "John Smith"s.ids = "100001"Dim sc As Score = New Score()sc.ClassName = "math"sc.Grades = "A"s.Score.Add(sc)sc = New Score()sc.ClassName = "English"sc.Grades = "A"s.Score.Add(sc)list.Add(s)s = New student()s.names = "David Black"s.ids = "100002"sc = New Score()sc.ClassName = "math"sc.Grades = "B"s.Score.Add(sc)sc = New Score()sc.ClassName = "English"sc.Grades = "A"s.Score.Add(sc)list.Add(s)FpSpread1_Sheet1.DataSource = list
Creating a Hierarchical Display Manually
Youcanmanually(programmatically)createahierarchicaldisplayasshownintheexamplebelow.Theparentisthehigherlevelofthehierarchyandthechildisthelowerlevel.
Example
ThisexamplecreatestwocustomSheetViewobjects:oneastheparentandoneasthechild.Intheparentsheet,theexampleoverridestheChildRelationCount('ChildRelationCountProperty'intheon-linedocumentation)propertyandGetChildView('GetChildViewMethod'intheon-linedocumentation)andFindChildView('FindChildViewMethod'intheon-linedocumentation)methods.TheChildRelationCountishowmanyrelationsbetweenthisobjectandchildrenobjects(usuallythisisone).
TheGetChildViewisusedtogetthechildsheet.ItcallsFindChildViewtoseeifthesheetisalreadycreated.Ifitis,thenusethatsheet.Ifitisnot,createanewchildsheet.
TheSheetName('SheetNameProperty'intheon-linedocumentation)propertyofthechildSheetViewdetermineswhichparentrowitisassignedto.
OverridetheParentRowIndex('ParentRowIndexProperty'intheon-linedocumentation)propertyinthe
Spread Windows Forms Developer’s Guide 469
Copyright © GrapeCity, Inc. All rights reserved.
childSheetViewtoreturntherownumberthatchildisassignedto.TheSheetNameincreatingthissheetdeterminesthisnumber.
VB...Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load FpSpread1.Sheets.Clear() FpSpread1.Sheets.Add(New customSheet) FpSpread1.Sheets(0).RowCount = 10 Dim i As Integer For i = 0 To 9 If i <> 1 Then FpSpread1.Sheets(0).SetRowExpandable(i, False) End If Next iEnd SubEnd Class
Public Class customSheetInherits FarPoint.Win.Spread.SheetView
Public Overrides ReadOnly Property ChildRelationCount() As Integer Get Return 1 End Get End Property
Public Overrides Function GetChildView(ByVal row As Integer, ByVal relationIndex As Integer) As FarPoint.Win.Spread.SheetView Dim child As customChild = CType(FindChildView(row, 0), customChild) If Not (child Is Nothing) Then Return child child = New customChild child.RowCount = 5 child.Parent = Me child.SheetName = row.ToString ChildViews.Add(child) Return child End Function
Public Overrides Function FindChildView(ByVal row As Integer, ByVal relationIndex As Integer) As FarPoint.Win.Spread.SheetView Dim id As String = row.ToString Dim View As FarPoint.Win.Spread.SheetView For Each View In ChildViews If View.SheetName = id Then Return View Next Return Nothing End FunctionEnd Class
Public Class customChildInherits FarPoint.Win.Spread.SheetView Public Overrides ReadOnly Property ParentRowIndex() As Integer Get Return CInt(SheetName) End Get
Spread Windows Forms Developer’s Guide 470
Copyright © GrapeCity, Inc. All rights reserved.
End PropertyEnd Class
Creating Custom Hierarchy Icons
YoucancustomizetheiconsusedforexpandingandcollapsingthehierarchyinahierarchicaldisplaybyusingtheGetImage('GetImageMethod'intheon-linedocumentation)andSetImage('SetImageMethod'intheon-linedocumentation)methodsintheSpreadView('SpreadViewClass'intheon-linedocumentation)class,whichisdescribedinCustomizingtheUserInterfaceImages.
Anexampleofhowthedefaulthierarchyicons,asimpleplussignandminussign,appearisshownhere.
Formoreinformationaboutthehierarchicaldisplay,refertotheWorkingwithHierarchicalDataDisplay.
Tutorial: Binding to a Corporate Database (Older Visual Studio)
ThefollowingtutorialwalksyouthroughcreatingaprojectandbindingtheSpreadcontroltoadatabase.
Inthistutorial,themajorstepsare:
Step1:AddingSpreadtoaDataBindingProjectStep2:SettinguptheDatabaseConnectionStep3:SpecifyingtheDatatoUseStep4:CreatingtheDataSetStep5:BindingSpreadtotheDatabaseStep6:ImprovingtheDisplaybyChangingtheCellType
Step 1: Adding Spread to a Data Binding Project
1. StartanewVisualStudio.NETproject.2. Nametheprojectdatabind.3. Nametheformfileintheprojectbinding.cs(or.vb).4. AddtheFpSpreadcomponenttoyourproject,andthenplacethecomponentontheform.
IfyoudonotknowhowtoaddtheFpSpreadcomponenttotheproject,completethestepsinAddingaComponenttoaProject
Step 2: Setting up the Database Connection
Youmusttelltheprojectwhichdatabaseyouwanttouse.Inthisstep,youwilladdaOleDbConnectioncontroltoyourform,andtellitthenameofthedatabasetouse.
Spread Windows Forms Developer’s Guide 471
Copyright © GrapeCity, Inc. All rights reserved.
1. IftheToolboxisnotdisplayed,fromtheViewmenuchooseToolbox.2. ClicktheDatatabtodisplaytheavailabledatacontrols.3. Double-clicktheOleDbConnectioncontroltoaddittoyourform.
TheOleDbConnectioncontrolisaddedtoyourform,inanewareacreatedbelowthevisibleareaoftheform.Thedatacontrolsyoucreateinthistutorialwillallbeplacedinthisarea,insteadofinthevisibleareaoftheform.
4. PressF4todisplaythePropertieswindowfortheOleDbConnectioncontrol.5. InthePropertieswindow,changethenameofthecontroltodbConnect.6. InthePropertieswindow,clicktheConnectionStringproperty.7. Clickthedownarrowdisplayedontherightsideofthesettingarea,thenselectNewConnectionfromthedrop-downlist.TheDataLinkPropertiesdialogisdisplayed.
8. ClicktheProvidertab,andthenselectMicrosoftJet4.0OLEDBProviderfromthelist.9. ClickNext.10. NexttotheSelectorenteradatabasenamebox,clicktheBrowsebutton.11. BrowsetoC:\ProgramFiles(x86)\GrapeCity\Spread.NET11\Docs\WindowsForms\TutorialFiles\databind.mdb
andthenchooseOpen.12. ClicktheTestConnectionbutton.13. Ifyoudonotreceiveamessagestatingthe"Testconnectionsucceeded"retrysteps6through12.14. Ifyoureceivedthemessage"Testconnectionsucceeded,"yourconnectioniscomplete.ClickOKtoclosethe
DataLinkPropertiesdialog.
Step 3: Specifying the Data to Use
Nowthatyouhavespecifiedthedatabasetouse,youneedtoretrievetherecordsfromthedatabasetableyouwanttodisplayinyourSpreadcontrol.Todothis,youwillusetheOleDbDataAdaptercontrol.
1. IftheToolboxisnotdisplayed,fromtheViewmenuchooseToolbox.2. ClicktheDatatabtodisplaytheavailabledatacontrols.3. Double-clicktheOleDbDataAdaptercontroltoaddittoyourform.
TheOleDbDataAdaptercontrolisaddedintheareabelowthevisibleareaoftheform.TheDataAdapterConfigurationWizardappears.
4. ChooseNexttobegincompletingthewizard.5. IntheChooseYourDataConnectiondialog,underWhichdataconnectionshouldthedataadapteruse?selecttheconnectionyoucreatedinStep2fromthedrop-downlist.ThenchooseNext.
6. IntheChooseaQueryTypedialog,selectUseSQLstatementsandthenchooseNext.7. IntheGeneratetheSQLstatementsdialog,chooseQueryBuilder.TheAddTabledialogappearstoletyouspecifythetabletouseinthedatabase.
8. SelecttheProductstablefromthelistandchooseAdd,thenchooseClose.9. IntheQueryBuilderdialog,theProducttableappearsinawindow,withalistoftheavailablefieldsinthe
table.Selectthefollowingfields:LeadTimeProductDescriptionProductNameUnitPriceProductID
10. TheQueryBuildercreatesyourSQLqueryinthestatusbox.Yourdialogshouldlooklikethis:
Spread Windows Forms Developer’s Guide 472
Copyright © GrapeCity, Inc. All rights reserved.
11. ChooseOKtoclosetheQueryBuilderdialog,thenchooseNextinthewizard.12. Thewizardsummarizesyourchoices.ChooseFinishtocompletethewizard.13. PressF4todisplaythePropertieswindowfortheOleDbDataAdaptercontrol.14. InthePropertieswindow,changethenameofthecontroltodbAdapt.
Step 4: Creating the Data Set
Nowthatyouhavespecifiedthedatabaseandthedatatousefromthedatabase,youwillcreateadatasettocontainthedataforyourSpreadcontrol.
UsingCode
1. SelectthedbAdaptOleDBDataAdaptercontrolontheform.2. PressF4todisplaythePropertieswindowforthecontrol,ifitisnotalreadydisplayed.3. ClicktheGenerateDatasetverbatthebottomofthePropertieswindow.4. TheGenerateDatasetdialogappears.5. ClickOKtoclosetheGenerateDatasetdialog.Thenewdatasetcontrolisaddedtoyourform.
6. PressF4todisplaythePropertieswindowforthenewDataSetcontrol,ifitisnotalreadydisplayed.7. InthePropertieswindow,changethenameofthecontroltodbDataSet.8. Double-clickontheforminyourprojecttoopenthecodewindow.9. TypethefollowingcodeintheForm_Loadevent:
Spread Windows Forms Developer’s Guide 473
Copyright © GrapeCity, Inc. All rights reserved.
Example
C#DataSet ds;ds = dbDataSet;dbAdapt.Fill(ds);
VBDim ds As DataSetds = dbDataSetdbAdapt.Fill(ds)
Thisfillsthedatasetwiththedatafromthedatabaseyouspecified,usingthefieldsyouspecifiedwhensettinguptheOleDbDataAdaptercontrol.
Step 5: Binding Spread to the Database
Yourdatasetisready,nowyouneedtoprovidecodetobindtheSpreadcontroltothedataset.
1. PressF4todisplaythePropertieswindowfortheSpreadcontrol,ifitisnotalreadydisplayed.2. InthePropertieswindow,settheDataSourcepropertytothenameofyourdataset,dbDataSet.
NoticethatthecolumnheadersintheSpreadcontrolchangetobethefieldnamesfromtheProductstableinyourdatabase.
3. Saveyourproject.4. Runyourprojectandyoushouldseeaformthatlookssimilartothefollowing:
5. Ifyourformdoesnotlooksimilartothisform,adjustthesizeofyourSpreadcontrol,andre-checkthestepsyouhaveperformedsofar.
6. Stoptheproject.
Step 6: Improving the Display by Changing the Cell Type
Inthisstep,youwillchangethecelltypeforoneofthecolumnstobetterdisplaythedatafromthedatabase.
Runyourprojectandyoushouldseeaformthatlookssimilartothefollowing:
Spread Windows Forms Developer’s Guide 474
Copyright © GrapeCity, Inc. All rights reserved.
1. Double-clickontheformtoopenthecodewindow.2. SetthecelltypefortheUnitPricecolumnbyaddingthecodeinthefollowingexampleafterthecodeyouhave
alreadyadded:3. Saveyourproject.
Example
C#FarPoint.Win.Spread.CellType.CurrencyCellType CurrCell = new FarPoint.Win.Spread.CellType.CurrencyCellType();CurrCell.DecimalPlaces = 2;CurrCell.CurrencySymbol = "US$";fpSpread1.Sheets[0].Columns[3].CellType = CurrCell;
VBDim CurrCell As New FarPoint.Win.Spread.CellType.CurrencyCellType()CurrCell.DecimalPlaces = 2CurrCell.CurrencySymbol = "US$"FpSpread1.Sheets(0).Columns(3).CellType = CurrCell
YouhavemanageddatabindingtoacorporatedatabaseusingSpread.Youhavecompletedthistutorial.
ReviewthelistofstepsforTutorial:BindingtoaCorporateDatabase(OlderVisualStudio).
Spread Windows Forms Developer’s Guide 475
Copyright © GrapeCity, Inc. All rights reserved.
Managing Data on a Sheet
Youcanworkwithdatainthecellsinthedataareaofthespreadsheetinanumberofways:
PlacingandRetrievingDataValidatingUserInputRearrangingDataonaSheetRemovingDatafromaSheetImprovingPerformancebySuspendingtheLayout
Placing and Retrieving Data
Youcanplace(set)dataincellsusingavarietyofmethodsandretrieve(get)thedatausingacomplimentarysetofmethods.Formoreinformationreferto:
HandlingDataUsingSheetMethodsHandlingDataUsingCellPropertiesRepeatedlyFillingaRangeofCellswithCopiedCells
Forinformationontheeffectsofcelltypesonhowdataisdisplayedandmanaged,refertoUnderstandingHowCellTypesWork.
Handling Data Using Sheet Methods
Youcanplacedataincellsasformattedorunformattedstringsorasdataobjects.Thebestwaytoplacedataincellsdependsonwhetheryouwanttoaddstringdataordataobjects,andifyouwanttoadddatatoanindividualcellortoarangeofcells.
Ifyouareworkingwithdataprovidedbyauserinatextbox,forexample,youprobablywanttoaddthedataasstringdatathatisparsedbytheSpreadcomponent.Ifyouareaddingseveralvaluesandwanttoaddthemdirectlytothedatamodel,youcanaddthemasobjects.
Thefollowingtablesummarizesthewaysyoucanadddatausingmethodsatthesheetlevel.
DataDescription HowManyCells
Method
Asastringwithformatting(forexample"$1,234.56")
Individualcell GetText('GetTextMethod'intheon-linedocumentation)
SetText('SetTextMethod'intheon-linedocumentation)
Rangeofcells GetClip('GetClipMethod'intheon-linedocumentation)
SetClip('SetClipMethod'intheon-linedocumentation)
Asastringwithoutformatting(forexample"1234.45")
Individualcell GetValue('GetValueMethod'intheon-linedocumentation)
SetValue('SetValueMethod'intheon-linedocumentation)
Rangeofcells GetClipValue('GetClipValueMethod'intheon-
Spread Windows Forms Developer’s Guide 476
Copyright © GrapeCity, Inc. All rights reserved.
linedocumentation)
SetClipValue('SetClipValueMethod'intheon-linedocumentation)
Asadataobjectwithformatting Rangeofcells GetArray('GetArrayMethod'intheon-linedocumentation)
SetArray('SetArrayMethod'intheon-linedocumentation)
Whenyouworkwithformatteddata,thedataisparsedbythecelltypeformattedforthatcellandplacedinthedatamodel.Whenyouworkwithunformatteddata,thedatagoesdirectlyintothedatamodel.Ifyouadddatatothesheetthatisplaceddirectlyintothedatamodel,youmightwanttoparsethedatabecausethecomponentdoesnotdoso.Tounderstandtheeffectthatthecelltypehasonthisdata,refertothesummaryinUnderstandingHowCellTypesDisplayandFormatData.
Fordetailedinformationabouthowtoprovidethedataforeachcelltype,seethemembertopicsintheFarPoint.Win.Spread.CellType('FarPoint.Win.Spread.CellTypeNamespace'intheon-linedocumentation)namespace.
Toaddalargeamountofinformationtothecomponent,considercreatingandopeningexistingfiles,suchastextfilesorExcel-formattedfiles,asexplainedinOpeningExistingFiles.
Youcanalsoreturndatabysavingthedataorthedataandformattingtoatextfile,Excel-formattedfile,orSpreadXMLfile.Forinstructionsforsavingdatatothesefiletypes,seeSavingDatatoaFile.
UsingthePropertiesWindow
Toadddatatoacell,followtheseinstructions.Youcannotadddatatoarangeofcellsunlessyouwanttoaddthesamedatatoallthecellsintherangeyouselect.
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. Clickthesheetforwhichyouwanttoadddata.5. SelecttheCellspropertyandthenclickthebuttontodisplaytheCell,Column,andRowEditor.6. Selectthecellorrangeofcellstowhichyouwanttoadddata.7. Inthepropertylist,settheTextproperty.8. ClickOKtoclosetheCell,Column,andRowEditor.9. ClickOKtoclosetheSheetViewCollectionEditor.
UsingaShortcut
Togetorsetdatatoacellusingcode,PlaceformattedstringdatausingtheSheetsSetText('SetTextMethod'intheon-linedocumentation)methodorretrievedatausingtheGetText('GetTextMethod'intheon-linedocumentation)method.PlacedataasobjectsdirectlyintothedatamodelusingtheSheetsSetValue('SetValueMethod'intheon-linedocumentation)methodorretrievethedatadirectlyusingtheGetValue('GetValueMethod'intheon-linedocumentation)method.
Togetorsetdatatoarangeofcells,PlaceformattedstringdatausingtheSheetsSetClip('SetClipMethod'intheon-linedocumentation)methodorretrievethedatausingtheGetClip('GetClipMethod'intheon-linedocumentation)method.PlaceunformattedstringdatausingtheSheetsSetClipValue('SetClipValueMethod'inthe
Spread Windows Forms Developer’s Guide 477
Copyright © GrapeCity, Inc. All rights reserved.
on-linedocumentation)methodorretrievedatausingtheGetClipValue('GetClipValueMethod'intheon-linedocumentation)method.AdddataasobjectsdirectlyintothedatamodelusingtheSheetsSetArray('SetArrayMethod'intheon-linedocumentation)methodorretrievethedatausingtheGetArray('GetArrayMethod'intheon-linedocumentation)method.
Example
Thisexamplecodeaddsformatteddatatoarangeofcells.
C#// Add data to cells A1 through C3.fpSpread1.Sheets[0].SetClip(0, 0, 3, 3,"Sunday\tMonday\tTuesday\r\nWednesday\tThursday\tFriday\r\nSaturday\tSunday\tMonday");
VB' Add data to cells A1 through C3.FpSpread1.Sheets(0).SetClip(0, 0, 3, 3, "Sunday" + vbTab + "Monday" + vbTab + "Tuesday" + vbCrLf + "Wednesday" + vbTab + "Thursday" + vbTab + "Friday" + vbCrLf + "Saturday" + vbTab + "Sunday" + vbTab + "Monday")
UsingCode
Toadddatatoacellusingcode,AddformattedstringdatabycallingtheSheetViewobjectSetText('SetTextMethod'intheon-linedocumentation)methodorbycallingtheCellobjectText('TextProperty'intheon-linedocumentation)property.AdddataasobjectsdirectlyintothedatamodelbycallingtheSheetViewobjectSetValue('SetValueMethod'intheon-linedocumentation)methodorbycallingtheCellobjectValue('ValueProperty'intheon-linedocumentation)property.
Toadddatatoarangeofcells,AddformattedstringdatabycallingtheSheetViewobjectSetClip('SetClipMethod'intheon-linedocumentation)method.AddunformattedstringdatabycallingtheSheetViewobjectSetClipValue('SetClipValueMethod'intheon-linedocumentation)method.AdddataasobjectsdirectlyintothedatamodelbycallingtheSheetViewobjectSetArray('SetArrayMethod'intheon-linedocumentation)method.
Example
Thisexamplecodeaddsformatteddatatoarangeofcells.
C#// Create a new SheetView object.FarPoint.Win.Spread.SheetView newsheet=new FarPoint.Win.Spread.SheetView();// Add data to cells A1 through C3.newsheet.SetClip(0, 0, 3, 3, "Sunday\tMonday\tTuesday\r\nWednesday\tThursday\tFriday \r\nSaturday\tSunday\tMonday");// Assign the SheetView object to be the first sheet.fpSpread1.Sheets[0] = newsheet;
Spread Windows Forms Developer’s Guide 478
Copyright © GrapeCity, Inc. All rights reserved.
VB' Create a new SheetView object.Dim newsheet As New FarPoint.Win.Spread.SheetView()' Add data to cells A1 through C3.newsheet.SetClip(0, 0, 3, 3, "Sunday" + vbTab + "Monday" + vbTab + "Tuesday" + vbCrLf + "Wednesday" + vbTab + "Thursday" + vbTab + "Friday" + vbCrLf + "Saturday" + vbTab + "Sunday" + vbTab + "Monday")' Assign the SheetView object to be the first sheet.FpSpread1.Sheets(0) = newsheet
Handling Data Using Cell Properties
Thefollowingtablesummarizesthewaysyoucangetorsetdataincellsusingthepropertiesofthecell.
DataDescription CellPropertyAsastringwithformatting(forexample"$1,234.56") Text('TextProperty'intheon-linedocumentation)
Asastringwithoutformatting(forexample"1234.45")
Value('ValueProperty'intheon-linedocumentation)
Thereisnolimitationonthedatatypesofvaluesthatcanbestoredincells.CellvaluesareassignedandretrievedusingthegenericObjectdatatype.Primitivedatatypes(forexample,bool,int,double,etc.)areassignedandretrievedusingboxedprimitives.
TheC#andVisualBasic.NETlanguagesautomaticallyboxprimitives(thatis,convertprimitivetoobject)foryouasillustratedinthiscode.
UsingCode
UsetheValue('ValueProperty'intheon-linedocumentation)propertyorSetValue('SetValueMethod'intheon-linedocumentation)methodtoadddatatoacell.
Example
Thisexampleaddsdatatocells.
C#FpSpread1.Sheets[0].Cells[0, 3].Value = 123;FpSpread1.Sheets[0].SetValue(0, 6, "abc");
VBfpSpread1.Sheets(0).Cells(0, 3).Value = 123fpSpread1.Sheets(0).SetValue(0, 6, "abc")
Example
Youneedtomanuallyunboxprimitives(thatis,convertobjecttoprimitive)byusingacast:
C#int i = (int)spread.Sheets[0].Cells[0, 3].Value;string s = (string)spread.Sheets[0].GetValue(0, 6);
Spread Windows Forms Developer’s Guide 479
Copyright © GrapeCity, Inc. All rights reserved.
VBDim i As Integer = CInt(spread.Sheets(0).Cells(0, 3).Value)Dim s As String = CStr(spread.Sheets(0).GetValue(0, 6))
Note:Emptycellsreturnanullvalue(NothinginVB)thatcausesthecasttofail.Ifthereisapossibilitythatacellisemptyorcontainsavalueofunknowndatatypethenyourcodeshouldcheckthedatatypepriortoperformingthecastorshouldprovideanexceptionhandlertocatchtheexceptionthrownbythefailedcast.
Repeatedly Filling a Range of Cells with Copied Cells
Youcancopyarangeofcellsandfillanotherrangewiththosecells,copyingthedataandthecelltypewiththeFillRange('FillRangeMethod'intheon-linedocumentation)method.Forexample,ifyouhavea2x2range,youcanrepeat(fill)downthenextfivegroupsof2x2vertically.
TheparametersfortheFillRange('FillRangeMethod'intheon-linedocumentation)methodare:
startingcellrowandcolumnindexnumberofrowsandcolumnsintherangetocopynumberofeitherrows(ifleftorright)orcolumns(ifupordown)tocopythatrange(notthenumberoftimestorepeattheentirerange;thenumberofeitherrowsorcolumns)
UsingCode
1. Adddatatothecells.2. SettheFillRange('FillRangeMethod'intheon-linedocumentation)method.
Example
Forexample,usingthiscode,youwouldaccomplishtheresultsshownintheprecedingfigure.
C#// Define the text to repeat.fpSpread1.ActiveSheet.Cells[0, 0].Text = "A1-text";fpSpread1.ActiveSheet.Cells[0, 1].Text = "A2-text";fpSpread1.ActiveSheet.Cells[1, 0].Text = "B1-text";fpSpread1.ActiveSheet.Cells[1, 1].Text = "B2-text";
Spread Windows Forms Developer’s Guide 480
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.ActiveSheet.Cells[0, 0].BackColor = Color.Cyan;fpSpread1.ActiveSheet.Cells[0, 0].ForeColor = Color.DarkBlue;fpSpread1.ActiveSheet.Cells[0, 1].BackColor = Color.Coral;fpSpread1.ActiveSheet.Cells[0, 1].ForeColor = Color.DarkRed;
// Fill 3 more columns to the right with the two columns' contentsfpSpread1.ActiveSheet.FillRange(0, 1, 2, 1, 3, FarPoint.Win.Spread.FillDirection.Right);// Fill 4 more rows down with the contents of the square// of 2 rows and 2 columnsfpSpread1.ActiveSheet.FillRange(0, 0, 2, 2, 4, FarPoint.Win.Spread.FillDirection.Down);
VB' Define the text to repeat.FpSpread1.ActiveSheet.Cells(0, 0).Text = "A1-text"FpSpread1.ActiveSheet.Cells(0, 1).Text = "A2-text"FpSpread1.ActiveSheet.Cells(1, 0).Text = "B1-text"FpSpread1.ActiveSheet.Cells(1, 1).Text = "B2-text"
FpSpread1.ActiveSheet.Cells(0, 0).BackColor = Color.CyanFpSpread1.ActiveSheet.Cells(0, 0).ForeColor = Color.DarkBlueFpSpread1.ActiveSheet.Cells(0, 1).BackColor = Color.CoralFpSpread1.ActiveSheet.Cells(0, 1).ForeColor = Color.DarkRed
' Fill 3 more columns to the right with the two columns' contentsFpSpread1.ActiveSheet.FillRange(0, 1, 2, 1, 3, FarPoint.Win.Spread.FillDirection.Right)' Fill 4 more rows down with the contents of the square' of 2 rows and 2 columnsFpSpread1.ActiveSheet.FillRange(0, 0, 2, 2, 4, FarPoint.Win.Spread.FillDirection.Down)
Validating User Input
Youcanvalidatethecontentsofthecellinanumberofways.SomevalidationisperformedbytheSpreadcomponentautomatically,basedonthetypeofcell.
Youcanalsousethevalidatorclassestoassignavalidatortoacell.Formoreinformation,refertoUsingValidationinCells(on-linedocumentation).
Beyondthis,tovalidatetheinputfromauser,youcanlookforaneventandrunavalidationroutinebasedontheoccurrenceofthatevent.AnothersimplewaytocheckwhethertheuserentersdatathatisvalidbasedonthecelltypeisbyusingtheIsValidmethod,whichisavailableinallthecelltypeclasses.
CellTypeValidation
Thecellvalidatesuserinputandverifiesthatitfitstherequirementsofthecelltype'sformatandsettings.Atruntime,thecomponentchecksdataeitherwhenitisenteredbytheuserorcode,whenthecomponentlosesthefocus,orboth.Thecomponentvalidatesdataasitisprovided,forexample,astheusertypesthedata,andwhenthecomponentlosesfocus.Userscanenterdatabytypingorpasting;datafromcodecancomefrompropertysettingsoradatabase.Ingeneral,allthesemethodsofenteringdataarehandledinthesamewaybythecomponent,whichchecksthedatatodetermineifitisvalid.
Valuesinthecomponentthatarelessthanthesettingoftheminimumvalue(MinimumValueorMinimumDate,orMinimumTimeproperty)areallowedinthecomponent.Componentsmustallowvalueslessthantheminimumtoletusersprovideapartialvaluethatislaterchangedtoavaluegreaterthantheminimumvalue.Forexample,ifthe
Spread Windows Forms Developer’s Guide 481
Copyright © GrapeCity, Inc. All rights reserved.
MinimumValuepropertyissetto100,andtheusertriestochangethevalueto124byselectingtheexistingvalueandtyping,astheusertypesthevaluechangesto"1",whichislessthantheallowedminimumvalue.However,astheusertypesthevaluebecomes"12"andthen"124".Thefinalvalueisabovetheallowedminimumvalue.Thevalueprovidedbytheuserischeckedtoseeifitislessthantheminimumvaluewhenthecontrollosesthefocus.
Whenthecontrolisvalidatingdataasitcomesintothecomponent,iftheusertriestoprovideinvaliddata,orinvaliddataiscomingfromcodeoradatabase,theUserErroreventoccurs.
Eachcelltypehassomedefaultrestrictionstodeterminewhatisvaliddata.Forexample,thecurrencycelltyperegardsatextstringofcharacterssuchas"abcd"asaninvalidvaluebecauseitexpectsnumericdata.Inaddition,youcansetpropertiesforeachcelltypethatspecifyvaliddatasettings.
Thefollowingtableliststhedefaultdataallowedineachoftheeditablecelltypes.
CellType Default ValidDataExamples
Currency Numericdata,whichcanincludecharactersforthecurrencysymbol,aseparator,andadecimalsymbol
$3.45
$1,234.56
£45
DateTime Dateandtimedata,whichcanincludeseparatorcharacters 8/16/2002,
Monday,August05,20024:40PM
GcDateTime Dateandtimedata,whichcanincludeseparatorcharacters 8/16/2002,
Monday,August05,20024:40PM
GcCharMaskorGcMask
Anycharacterisacceptedthatfitsthemaskstringcriteria
GcComboBoxorGcTextBox
Anycharacterisaccepted
GcNumber Numericdata,whichcanincludecharactersforaseparatorandadecimalsymbol
3.45
1,234.56
GcTimeSpan TimeSpandata,whichcanincludeseparatorcharacters
Hyperlink Anycharacterisaccepted.
General Anycharacterisaccepted.
Mask Anycharacterisacceptedthatfitsthemaskstringcriteria
Number Numericdata,whichcanincludecharactersforaseparatorandadecimalsymbol
3.45
1,234.56
Percent Numericdata,whichcanincludecharactersforthepercentsymbol,aseparator,andadecimalsymbol
0.5
1,234%
Text Anycharacterisaccepted.
Spread Windows Forms Developer’s Guide 482
Copyright © GrapeCity, Inc. All rights reserved.
Formoreinformationaboutdifferencesbetweenthesecelltypes,refertotheCustomizingInteractionwithCellTypes.
Thefollowingtableliststheadditionalpropertiesyoucansetforeachcelltypethatspecifyvaliddatasettings.
CellType CellTypePropertiesforDefiningValidDataCurrency MaximumValue('MaximumValueProperty'intheon-linedocumentation),
MinimumValue('MinimumValueProperty'intheon-linedocumentation)
DateTime MaximumDate('MaximumDateProperty'intheon-linedocumentation),MinimumDate('MinimumDateProperty'intheon-linedocumentation),MaximumTime('MaximumTimeProperty'intheon-linedocumentation),MinimumTime('MinimumTimeProperty'intheon-linedocumentation)
GcCharMask FormatString('FormatStringProperty'intheon-linedocumentation)
GcCharMaskorGcMask
Pattern('PatternProperty'intheon-linedocumentation),MaxLength('MaxLengthProperty'intheon-linedocumentation),MinLength('MinLengthProperty'intheon-linedocumentation)
GcComboBox MaxLength('MaxLengthProperty'intheon-linedocumentation),MaxLengthUnit('MaxLengthUnitProperty'intheon-linedocumentation),FormatString('FormatStringProperty'intheon-linedocumentation)
GcDateTime MaxDate('MaxDateProperty'intheon-linedocumentation),MinDate('MinDateProperty'intheon-linedocumentation),MaxMinBehavior('MaxMinBehaviorProperty'intheon-linedocumentation)
GcNumber MaxValue('MaxValueProperty'intheon-linedocumentation),MinValue('MinValueProperty'intheon-linedocumentation),MaxMinBehavior('MaxMinBehaviorProperty'intheon-linedocumentation),ValueSign('ValueSignProperty'intheon-linedocumentation)
GcTextBox MaxLength('MaxLengthProperty'intheon-linedocumentation),MaxLengthUnit('MaxLengthUnitProperty'intheon-linedocumentation),MaxLengthCodePage('MaxLengthCodePageProperty'intheon-linedocumentation),FormatString('FormatStringProperty'intheon-linedocumentation)
GcTimeSpan MaxValue('MaxValueProperty'intheon-linedocumentation),MinValue('MinValueProperty'intheon-linedocumentation),MaxMinBehavior('MaxMinBehaviorProperty'intheon-linedocumentation),ValueSign('ValueSignProperty'intheon-linedocumentation)
Number MaximumValue('MaximumValueProperty'intheon-linedocumentation),MinimumValue('MinimumValueProperty'intheon-linedocumentation)
Mask Mask('MaskProperty'intheon-linedocumentation),MaskChar('MaskCharProperty'intheon-linedocumentation)
Percent MaximumValue('MaximumValueProperty'intheon-linedocumentation),MinimumValue('MinimumValueProperty'intheon-linedocumentation)
Text MaxLength('MaxLengthProperty'intheon-linedocumentation)
Thefollowingtablelistshowinvaliddataishandledbythenumberandtextcelltypes.TheColumnandCellheadingsinthetablerefertoenteringthedataatthecolumnorcelllevel.
Action TextCell
NumberCell
Column Cell Column Cell
Spread Windows Forms Developer’s Guide 483
Copyright © GrapeCity, Inc. All rights reserved.
Inputinvalidcelltextwhilecellisineditmode +* +* +* +*
Pasteinvalidcelltextwhilecellisineditmode #* #* +* +*
Pasteinvalidcelltextwhilecellisnotineditmode #* #* +* +*
Pastecopiedcellwithcelltypeandinvalidvaluewhilenotineditmode ##** ##** ##** ##**
Pastecopiedcellwithinvalidvalueandcelltypenotsetwhilecellisnotineditmode
#* #* +* +*
InputinvalidvaluewithcellValueproperty(orISheetDataModelSetValuemethod)
++** ++** ++** ++**
InputinvalidstringvaluewithcellTextproperty(orSheetViewSetTextmethod)
#** #** +** +**
InputinvalidcellvaluewithSheetViewSetValuemethod(validate=false)
++** ++** ++** ++**
InputinvalidcellvaluewithSheetViewSetValuemethod(validate=true) +** +** +** +**
Setinvalidcelltypeafterbinding ++** ++** ++** ++**
UsetheClipboardPasteValuesfieldtopasteinvalidcellvaluewhilecellisnotineditmode
#* #* +* +*
DragFillMode.Copy(theoperationiscanceledifthecellislocked) #* #* +* +*
DragFillMode.Series(theoperationiscanceledifthecellislocked) #* #* +* +*
Thefollowinglistdefinestheconditionsintheabovetable:
+Rejectthevalue++Allow(paint)theexistinginvalidvalueandmakethevaluevalid(truncatethevalueorchangeittobewithintheminimum/maximumsetting)whenediting#Truncatethevalue##Pastethevalueandcelltype*FiretheError/EditErrorevents**DonotfiretheError/EditErrorevents
Event-basedValidation
Youcancheckforaneventandrunavalidationroutinebasedontheoccurrenceofthatevent.Forinstance,theChanged('ChangedEvent'intheon-linedocumentation)eventintheSheetViewclassnotifiesyourapplicationthattheuserhaslefteditmodeandthecontentsofthecellhaschanged.Formorethoroughvalidation,tohandlethecasewhereauserpastesavaluefromtheClipboardasopposedtotypinginavalue,usetheChangedeventonthedatamodel(DefaultSheetDataModelclass).Thisisagoodwaytoevaluatethecontentsofacellafterithasbeenedited,andthrowanerrormessageorreverttooriginalvalueifthedatainthecellisnotvalid.Formoreinformationaboutusingevents,refertoManagingEventsfromUserActions.
IsValidMethodValidation
TheIsValidmethodforthecelltypeclassescheckswhetheravalueisvalidforthecelleditor.Spreadusesthatmethodinternallytocheckvaluescomingoutofthecelleditortoensurethattheyarevalid.Inmostcases,itwillreturnTrueif
Spread Windows Forms Developer’s Guide 484
Copyright © GrapeCity, Inc. All rights reserved.
theFormatmethodisabletoformatthespecifiednon-stringvalueintoastringtodisplayintheeditor,orwhethertheParsemethodisabletoparsethespecifiedstringvalueintoavalueoftheappropriatetypeforthecell.
Foradvancedusers,youcanevaluatethecontentsofacellafterithasbeenedited,andthrowanerrormessageandreverttotheoriginalvalueifthedatainthecellisnotvalid.TodothisrequireshandlingtheEditModeOneventandsettingpropertiesinSuperEditBaseandthusGeneralEditorontheeditorcontroleachtimeeditmodeisturnedon.ThesepropertiesincludeInvalidOption,InvalidColor,CanValidate,andUserEntry,butthisrequiresamoreinvolvedprocess.AtthetimetheEditModeOffeventisraised,thevalueinthedatamodelhasalreadybeenchanged.HandleEditModeOnandstorethecell'svalueandthenintheEditModeOffeventifthecurrentvalueofthecellfailsyourvalidation,resetthevaluetothestoredvalue.
Rearranging Data on a Sheet
Youcanrearrangedataonasheetfromcelltocellinmanyways.
CopyingDataonaSheetMovingDataonaSheetSwappingDataonaSheet
Copying Data on a Sheet
YoucancopydatatoandfromcellsusingtheCopy('CopyMethod'intheon-linedocumentation)methodsforthesheet.
Whenyoucopydatatoacell(orrangeofcells),thedatareplacesthedatainthedestinationcell(orcells).Iftheoperationcopiesarangeofcellsandpastesthemtoanoverlappinglocation,thevaluesofallthecellsyouarepastingarereplacedwiththevaluesofthecellsinthecopiedrange.
Youcanspecifywhetherformulasareautomaticallyupdatedwhencellsorrangesofcellsarecopied.Formoreinformationonautomaticrecalculation,refertoRecalculatingandUpdatingFormulasAutomatically.
FormoreinformationoncustomizingClipboardoperations,suchascopy,refertoCustomizingClipboardOperationOptions.
Moving Data on a Sheet
YoucanmovedatafromonecellorrangeofcellstoanotherusingtheMove('MoveMethod'intheon-linedocumentation)methodsforthesheet.
Whenyoumovedatafromonecell(orrangeofcells)toanother,thedatafromtheoriginationcell(orrangeofcells)replacesthedatainthedestinationcell(orcells).Iftheoperationmovesarangeofcellstoanoverlappinglocation,thevaluesofallthecellsoftherangearereplacedwiththevaluesofthecellsinthemovedrange.
Youcanspecifywhetherformulasareautomaticallyupdatedwhencellsorrangesofcellsaremoved.Formoreinformationonautomaticrecalculation,refertoRecalculatingandUpdatingFormulasAutomatically.
Tomovedata3rowsupthesheetand5rowsdown,youwouldneedtoinsertblankrowswhereyouwanttomovetherowsto.Tomove3rowsupand5rowsdown,copythefiverowstemporarilythenmovethe3rowsuptotheirpositionsandthenassignthefivecopiedrowstothecorrectposition.
Example
Thisexamplemovesdatainthesheetandinsertsblankrows.
C#fpSpread1.Sheets[0].SetText(6, 0, "test");var with1 = (FarPoint.Win.Spread.Model.DefaultSheetDataModel)fpSpread1.Sheets[0].Models.Data;FarPoint.Win.Spread.Model.DefaultSheetDataModel dm = new
Spread Windows Forms Developer’s Guide 485
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Spread.Model.DefaultSheetDataModel(5, with1.ColumnCount);dm.SetArray(0, 0, ((FarPoint.Win.Spread.Model.DefaultSheetDataModel)fpSpread1.Sheets[0].Models.Data).GetArray(0, 0, 5, 5));with1.RemoveRows(0, 5);with1.AddRows(0, 3);with1.Move(with1.RowCount - 4, 0, 0, 0, 3, with1.ColumnCount);with1.RemoveRows(with1.RowCount - 4, 3);with1.AddRows(with1.RowCount, 5);with1.SetArray(with1.RowCount - 6, 0, dm.GetArray(0, 0, 5, with1.ColumnCount));
VBFpSpread1.Sheets(0).SetText(6, 0, "test")With CType(FpSpread1.Sheets(0).Models.Data, FarPoint.Win.Spread.Model.DefaultSheetDataModel)Dim dm As New FarPoint.Win.Spread.Model.DefaultSheetDataModel(5, .ColumnCount)dm.SetArray(0, 0, CType(FpSpread1.Sheets(0).Models.Data, FarPoint.Win.Spread.Model.DefaultSheetDataModel).GetArray(0, 0, 5, 5)).RemoveRows(0, 5).AddRows(0, 3).Move(.RowCount - 4, 0, 0, 0, 3, .ColumnCount).RemoveRows(.RowCount - 4, 3).AddRows(.RowCount, 5).SetArray(.RowCount - 6, 0, dm.GetArray(0, 0, 5, .ColumnCount))End With
Swapping Data on a Sheet
Youcanswapthecontentsoftwocellsortworangesofcells.
Whenyouswapdatafromacellorarangeofcellstoanothercellorrangeofcells,thesettingsforthecellareswappedalongwiththedata.Ifyouprovidedsettingsforthecolumnortherowcontainingthecell,orthespreadsheet,butnotthecellitself,thosesettingsarenotswapped.Forexample,ifyouhavesetthesourcecellbackgroundcolortored,thebackgroundcolorisswappedandthetargetcellhasaredbackground.However,ifyouhavesetthebackgroundcolorofthecolumncontainingthesourcecelltored,thatsettingisnotswapped.
Whenyouswapdatafromonecelltoanother,thedatainonecellbecomesthedataintheothercell,andviceversa.Forexample,ifcellA1containsthevalue4andcellB3containsthevalue6andyouswapthevaluesofthecells,thevalueofcellA1becomes6andthevalueofcellB3becomes4.
Ifyouattempttoswaparangethatislargerthantheavailablerangeatthedestination,theswapoperationisnotperformed.Forexample,ifyouattempttoswaparangeoffourcellsandspecifythedestinationasacellattheedgeofthespreadsheet,theswapdoesnottakeplace.
Iftheswapoperationswapsoverlappingrangesofcells,individualcellsareswappedstartingattheoverlappingcorner.
Iftherangesoverlap,suchasmovingrows1and2beforerow0,youcanaddextrarows,movetherows,andthenremovetheextrarows.
Formoreinformationonmethodstomoveorswapdata,refertotheirpageintheAPIreference:
SheetViewClass:SwapRange('SwapRangeMethod'intheon-linedocumentation)MethodSheetViewClass:MoveRange('MoveRangeMethod'intheon-linedocumentation)MethodModelNamespace:DefaultSheetSpanModelClass:SwapColumns('SwapColumnsMethod'intheon-linedocumentation)MethodModelNamespace:DefaultSheetSpanModelClass:SwapRows('SwapRowsMethod'intheon-linedocumentation)Method
UsingCode
Spread Windows Forms Developer’s Guide 486
Copyright © GrapeCity, Inc. All rights reserved.
Hereisanexampleofswappingarangeofcells.
Example
Thisexampleswapsarange.
C#fpSpread1.ActiveSheet.RowCount = 10;fpSpread1.ActiveSheet.ColumnCount = 10;private void button1_Click(object sender, System.EventArgs e){ fpSpread1.ActiveSheet.SwapRange(0, 0, 3, 0, 3, 3, true);}
VBFpSpread1.ActiveSheet.RowCount = 10FpSpread1.ActiveSheet.ColumnCount = 10Private Sub void button1_Click(sender As Object, e As System.EventArgs) FpSpread1.ActiveSheet.SwapRange(0, 0, 3, 0, 3, 3, True)End Sub 'button1_Click
Example
Thisexampleaddsrows,movesrows,andthenremovestheextrarows.
C#fpSpread1.ActiveSheet.RowCount = 10;fpSpread1.ActiveSheet.ColumnCount = 10;private void button1_Click(object sender, System.EventArgs e){ fpSpread1.ActiveSheet.Rows[0,1].Add() ; fpSpread1.ActiveSheet.MoveRange(3,0,0,0,2,4,true); fpSpread1.ActiveSheet.Rows[3,4].Remove();}
VBFpSpread1.ActiveSheet.RowCount = 10FpSpread1.ActiveSheet.ColumnCount = 10Private Sub void button1_Click(sender As Object, e As System.EventArgs) FpSpread1.ActiveSheet.Rows(0,1).Add() FpSpread1.ActiveSheet.MoveRange(3,0,0,0,2,4,True) FpSpread1.ActiveSheet.Rows(3,4).Remove()End Sub 'button1_Click
Whenyouswaprangesofdata,youcanspecifywhetherformulasareadjusted.Formoreinformation,seeRecalculatingandUpdatingFormulasAutomatically.
Removing Data from a Sheet
Youcanremovebothdataandcellformattingfromaselectedcellorrangeofcells,orremoveonlythedata,leavingthecellformattingintact.Formoreinformationaboutcellformatting,refertoUnderstandingHowCellTypesDisplayandFormatData.YoucanremovethedatausinganyoftheclearmethodsorbycuttingthedatausingtheClipboard
Spread Windows Forms Developer’s Guide 487
Copyright © GrapeCity, Inc. All rights reserved.
operation.
Youcanremovethedatausinganyoftheseclearmethodsinthedefaultdatamodel:
Clear('ClearMethod'intheon-linedocumentation),whichclearsbothdataandformulasClearFormulas('ClearFormulasMethod'intheon-linedocumentation),whichclearsonlyformulasClearData('ClearDataMethod'intheon-linedocumentation),whichclearsonlydataClearCustomNames('ClearCustomNamesMethod'intheon-linedocumentation),whichclearscustomnames,andClearCustomFunctions('ClearCustomFunctionsMethod'intheon-linedocumentation),whichclearscustomfunctionsClearRange('ClearRangeMethod'intheon-linedocumentation),whichclearsdata,formulas,notes,andformattingfromarangeofcells
IfyouuseClearRangeandsetthedataOnlyparametertotrue,themethodclearstheformulas,thecellnotes,andthetextinthecellsinthatrange;inotherwords,itclearsalltheinformationthatisinthedatamodelforthosecells.
Youcanremovethecontentsofarangeofcellsusingthismethodintherangeinterface:
IRangeSupport.Clear('ClearMethod'intheon-linedocumentation)
Improving Performance by Suspending the Layout
Onewaytoimprovetheperformanceofthecomponent,iftherearechangestomanycells,istoholdorsuspendtherepaintinguntilallthechangesarecomplete.Byholdingtherepainting(suspendingthelayout)whileallthechangesandrecalculationsaredone,andthenresumingthelayoutandrepaintingallthecells,thecomponentcansavealotoftimeandstilldeliverarefreshedinterfacetotheuser.
LayoutObjects
Alayoutisanobjectthatstorescalculatedvalues(mostlywidthsandheightsofcells,spans,andviewports)usedforpaintingthecomponentinitscurrentstate.Thismayincludehowmanyviewportsthereare,whatthetopleftcellineachviewportis,howbigeachcolumnandrowisandhowmanyarecurrentlyvisibleineachviewport,etc.Thepurposeofthelayoutobjectistooptimizepaintingofthecomponentbystoringthecalculatedlayoutvaluesusedduringpaintingandreusingthemeachtimethecomponentrepaintsinsteadofrecalculatingthemeachtime.Whenachangeistrackedthatrequiresthelayoutobjecttoberegenerated,itisdiscardedandanewoneiscalculatedbythepaintcode.ThelayoutobjectsarenotpartofthepublicAPI,buttheycacheallofthelayoutinformationrequiredtopaintthesheet,likethecolumnwidths,rowheights,cellspans,celloverflowsandtherectanglesofcellnotesthatarealwaysvisible(Cell.NoteStyle=NoteStyle.StickyNote).
SuspendingtheLayoutLogic
Toimproveperformance,youcansuspendthelayout,whichstopsthelayoutobjectfrombeingupdatedandthusthecomponentdoesnotspendanytimemakingcalculationsforrepaintinguntilthelayoutisresumed.Twomethodsaccomplishthis,theSuspendLayout('SuspendLayoutMethod'intheon-linedocumentation)andResumeLayout('ResumeLayoutMethod'intheon-linedocumentation)methodsintheFpSpread('FpSpreadClass'intheon-linedocumentation)class.Besuretousethetwomethodstogetherwithinaparticularscopeofoperation,otherwiseaproblemmayoccurwiththelayoutbeingsuspendedandnotabletoresume.
TheSuspendLayout('SuspendLayoutMethod'intheon-linedocumentation)methodpreventsthecomponentfromrecomputingthelayoutofcolumns,rows,andcellswhenchangesaremadetothesheet.Ifyouaremakinglotsofchangestothesheetinablockofcode,usingSuspendLayout('SuspendLayoutMethod'intheon-linedocumentation)preventsthecomponentfromdoingredundantintermediaterecalculationsofthelayoutobjectsaseachchangeismade,andusingResumeLayout('ResumeLayoutMethod'intheon-linedocumentation)(true)recomputesthelayoutonceafterallofyourchangesaremade.Thisapproachincreasesperformancegreatly,butthereareadditionalapproachesyoucandodependingonwhatfeaturesyoursheetsrequire,asdescribedinthesection,"OtherPerformanceImprovements."
Spread Windows Forms Developer’s Guide 488
Copyright © GrapeCity, Inc. All rights reserved.
Example
Thisexamplesuspendsandresumesthelayout.
C#Dim st As System.DateTime = System.DateTime.NowWith FpSpread1.SuspendLayout().Sheets(0).ActiveSkin = FarPoint.Win.Spread.SheetSkin.Load("d:\temp\skin.skn").ResumeLayout()End WithMsgBox("Duration (ticks)=" & System.DateTime.Now.Ticks - st.Ticks)
private void PerformInitialSetup() { // (0) used for property labels. _propertyLabelOrdinal = 0; // Set up the spread spread.SuspendLayout(); SheetView sheet = spread.ActiveSheet; sheet.Models.ColumnHeaderData = new HeaderDataModel(spread, _orientation); sheet.Models.Style = new SheetStyleModel(_orientation); spread.NamedStyles = _config.Styles.NamedStyles;
// Insert initial data sheet.Columns.Count = 2; foreach (Block block in _config.Blocks) { // Insert any leading blank rows if (block.SpaceBefore > 0) sheet.Rows.Add(sheet.Rows.Count, block.SpaceBefore); if (block.DealProperties != null) { int rowIndex = sheet.Rows.Count; sheet.Rows.Add(rowIndex, block.DealProperties.Count); foreach (DealProperty property in block.DealProperties) { sheet.Cells[rowIndex, _propertyLabelOrdinal].Value = property; sheet.Rows[rowIndex].StyleName = block.StyleName; rowIndex++; } } // Insert any trailing blank rows if (block.SpaceAfter > 0) sheet.Rows.Add(sheet.Rows.Count, block.SpaceAfter); } // Set initial styles sheet.Columns[_propertyLabelOrdinal].StyleName = "dealPropertyLabels"; spread.ResumeLayout(); }
SuspendedNotification
Ifthelayoutissuspendedwithoutacorrespondingresumemethodinthesamescopeandanexceptionoccurs,the
Spread Windows Forms Developer’s Guide 489
Copyright © GrapeCity, Inc. All rights reserved.
componentdisplaysanotification,asshowninthefollowingfigure.Ifthestateofthecomponentchangessuchthatthelayoutobjectcontainsinvaliddata(usuallytheincorrectnumberofitems)thenanexceptioncanresultwhenthecomponenttriestopaintwiththeinvalidlayoutdata.Thenotificationisshownwheneverthereisanunhandledexceptionthatoccursduringthepaintingofthecontrol,andthelayoutissuspendedwhentheexceptionoccurred.
ThisshouldonlyhappenwhenthelayoutissuspendedwithSuspendLayout('SuspendLayoutMethod'intheon-linedocumentation),andthenchangesaremadetothecomponentstateandthecomponentsomehowmadetopaintagainwithaninvalidlayoutobject.Itispossiblethattherecouldbeanexceptionthatcausesthismessagetobedisplayedthatisnotrelatedtothelayoutbeingsuspended,forexample,ifanexceptionisthrownbyacustomcelltypeobjectduringacalltoIRenderer.PaintCell.
Anychangesmadetothecomponentstatecouldtriggerlayoutrecalculation,butnotallchangesdoso.Changesthatrearrangerowsorcolumns,suchassortingandfiltering,definitelyrequireit,butsettingtextonlydoesitundercertaincircumstances,forexample,whenyouhaveAllowCellOverflowturnedon.Ifthelayoutissuspended,buttheSpreadisabletopaintusingoldlayoutinformationwithoutanyproblems,thentheSpreadmayactinunexpectedways,forexample,itwillnotscrollwhenyoutry,butthenotificationisnotdisplayed.
OtherPerformanceImprovements
Beyondthesuspending(andsubsequentresuming)ofthelayoutlogic,therearefewotherthingsyoucanconsiderthatmayimproveperformance.
Ifyouarenotusingstickynotes,thenyoucansetAutoUpdateNotestofalsetopreventthecomponentfromcheckingforstickynotesthatneedtobemadevisibleorhiddenormoved.IfyouareusingAllowCellOverflow,turningthatoffincreasestheperformanceofthelayoutcalculations,becausethatfeaturerequiresmultipletextwidthcalculationsoneachchangetothedatainacell.Ifyouareusingformulas,settingAutoCalculationtofalsebeforeyourupdatesandthensettingitbacktotrueandcallingRecalculateafterwardseliminatesredundantintermediaterecalculationsofyourformulas.
Someotherthingstoconsideraretoreducethesizeofthecontrolordisplayfewercolumnsandrowsatonce(thelayoutobjectsonlycalculatethevisibleportionofthesheet),orimplementyourownsheetmodelobjects(likeyourowndatamodelobjectimplementingISheetDataModel)whichremovefeaturesthatyoudonotrequire(forexample,ifyoudonotrequiredatabinding,thedatabindinginterfacesdonotneedtobeimplemented).
UsingtheMethodsTogether
Aroughoutlineofthecodeforsuspendinglayoutwouldbe:
SuspendLayout
insertyourcodehere
ResumeLayout
Themethodsareintendedfortemporarilyignoringchangestothelayoutsothatmanychangescanbemadewithoutperformingtheredundantlayoutrecalculationsbetweeneachchange.Whilelayoutcalculationissuspended,eventhandlerstrackingchangestothecomponentarenotabletorecalculatethelayoutandthepaintcodedoesnotaccessthenewlayout.Foranestedloopthatmakesachangetoeverycell,saychangingavalueineachcell,thisisacasethatwoulddefinitelybenefitfromsuspendingthelayoutbeforeandresumingthelayoutafterward.
Spread Windows Forms Developer’s Guide 490
Copyright © GrapeCity, Inc. All rights reserved.
Donotusethesemethodsunlessthechangesaresuchthattheperformancecanbenefitfromthelayoutbeingsuspendedtemporarily.
Alwaysusethetwomethodstogetherinthesamescope,otherwisethecomponentmightnotpaintcorrectlyifSuspendLayout('SuspendLayoutMethod'intheon-linedocumentation)iscalledwithoutamatchingcalltoResumeLayout('ResumeLayoutMethod'intheon-linedocumentation)inthesamescope.
Example
Thisexampleshowsthetwomethodsusedtogetherwithinaspecificscopearoundcodethatchangesthecells.ThissuspendstherepaintingoftheSpreadcomponentwhilechangingthecolorofthecellsandthenresumestherepainting.
C#fpSpread1.SuspendLayout();fpSpread1.Sheets[0].Cells[0, 0, 499, 499].BackColor = Color.Blue;fpSpread1.ResumeLayout(true);
VBFpSpread1.SuspendLayout()FpSpread1.Sheets(0).Cells(0, 0, 499, 499).BackColor = Color.BlueFpSpread1.ResumeLayout(True)
Spread Windows Forms Developer’s Guide 491
Copyright © GrapeCity, Inc. All rights reserved.
Managing Keyboard Interaction
YoucancustomizeuserinteractionwithyourSpreadcomponentbymappingkeyboardinputsfromtheusertoparticularactionsontheSpreadcomponentusinginputmapsandactionmaps.Forexample,pressingtheHomekeycanbeassociatedwithmovingtheactivecelltothefirstcellintherow.Manyofthekeysaremappedtoactionsbydefault.Youcancustomizethesedefaultmapsaswellasaddnewmappingstocreatetheinteractionsyouwant.Thefollowingtopicsdescribethedefaultmappingsaswellasproceduresforsettingupmapstocustomizekeystrokeprocessing.
UnderlyingKeystrokeProcessingFactorsofKeyboardMapUsageDefaultKeyboardNavigationDefaultKeyboardMapsDeactivatingtheDefaultKeyboardMapChangingtheDefaultKeyboardMapUsingInputMapswithActionMapsCustomizingtheInputMapsChanginganInputMapforaChildViewUsingtheExcelCompatibilityInputMapsSavingandLoadingMapFiles
Formoreinformationontheclassesinvolved,refertotheActionMap('ActionMapClass'intheon-linedocumentation)andInputMap('InputMapClass'intheon-linedocumentation)classes.
Underlying Keystroke Processing
TheSpreadcomponentbuildsitskeystrokeprocessingontopoftheunderlyingWindowskeystrokeprocessing.
TheSystem.Windows.Forms.Controlclassprovidesthefollowingmethodsandeventsforprocessingkeystrokesthatoccurwhilethecomponenthasfocus:
IsInputKeymethodIsInputCharmethodOnKeyDownmethodOnKeyPressmethodOnKeyUpmethodKeyDowneventKeyPresseventKeyUpevent
TheSystem.Windows.Forms.Controlclassprovidesthefollowingmethodsforprocessingkeystrokesthatoccurwhilethecomponentoroneofitschildcontrolshasfocus:
ProcessDialogKeyProcessDialogChar
Inadditiontothemethodsandeventsinthe.NETFrameworkthathandlekeyboardinput,theSpreadcomponentprovidesinputmaps,asdescribedinDefaultKeyboardMaps.Inputmapsprovideatable-baseddescriptionofthekeyboardbehaviorforaSpreadcomponent.ThisallowstheapplicationtoquerythekeyboardbehaviorforaSpreadcomponent.Aninputmapisessentiallyacollectionofkeystrokesandrelatedactions.
TheSpreadcomponentprovidesaWhenFocusedinputmapforprocessingkeystrokesthatoccurwhilethecomponenthasfocus.TheWhenFocusedinputmapisusedtoimplementtheFpSpread('FpSpreadClass'intheon-linedocumentation)classIsInputKey,IsInputChar,OnKeyDown,OnKeyPress,andOnKeyUpmethodswhichinturnraisetheKeyDown,KeyPress,andKeyUpevents.
Spread Windows Forms Developer’s Guide 492
Copyright © GrapeCity, Inc. All rights reserved.
TheSpreadcomponentprovidesaWhenAncestorOfFocusedinputmapforprocessingkeystrokesthatoccurwhilethecomponentoroneofitschildcontrolshasfocus.TheWhenAncestorOfFocusedinputmapisusedtoimplementtheFpSpread('FpSpreadClass'intheon-linedocumentation)class'sProcessDialogKeyandProcessDialogCharmethods.Thesemethodsdonotraiseanyevents.MostkeystrokesprocessedbytheSpreadcomponentmustbeprocessedwhetherthecomponentoroneofitschildcontrolshavefocus,whichmeansthatmostoftheSpreadkeyboardbehaviorisdescribedintheWhenAncestorOfFocusinputmap.
Note:WhenkeystrokesareprocessedbytheProcessDialogKeyandProcessDialogCharmethods,noeventsareraised.Thisistrueofmostothergrid-likecomponents,includingtheMicrosoftDataGrid.
TheSpreadcomponenthasmultipleoperationmodes(Normal,ReadOnly,RowMode,SingleSelect,MultiSelect,ExtendedSelect).Eachoperationmoderequiresdifferentkeyboardbehavior.Therefore,theSpreadcomponenthasseparateWhenFocusedandWhenAncestorOfFocusedinputmapsforeachoperationmode,aslistedinthetopicDefaultKeyboardMaps.Formorediscussionofthese,refertoFactorsofKeyboardMapUsage.
ThepredefinedactionsavailablefortheSpreadcomponentareintheSpreadActions('SpreadActionsClass'intheon-linedocumentation)class.Foracompletelistofactions(includingactionsthatdonothavedefaultkeys),refertotheSpreadActions('SpreadActionsClass'intheon-linedocumentation)class.
Ifyouwanttoturnoffoneofthedefaultmapkeystrokesettings,youcansetthekeystroketotheNonememberoftheSpreadActions('SpreadActionsClass'intheon-linedocumentation)class.
Formoreinformationabouttheprogramminginterfaceforinputsandactionsandmaps,refertotheseclasses:
Action('ActionClass'intheon-linedocumentation)classActionMap('ActionMapClass'intheon-linedocumentation)classInputMap('InputMapClass'intheon-linedocumentation)classKeyStroke('KeystrokeStructure'intheon-linedocumentation)classSpreadActions('SpreadActionsClass'intheon-linedocumentation)class
Factors of Keyboard Map Usage
Thereareseveralfactorsinvolvedwithusingmappingsthatshouldbeunderstoodbeforeeitherchangingthedefaultmappingsorcreatingyourownmappings.Theseinclude:
FocusLocationandOperationModeGlobalversusLocalParentversusChildWorkbookEnterKeystrokeBindingExceptionActionCalledNone
FocusLocationandOperationMode
Keyboardmappingisdependentontwofactors:thefocuslocationandtheoperationmode.Forexample,theEnterkeyhasdifferentactionsdependingifitispressedwhenacelleditorhasthefocusorwhenthecontrolhasthefocus.Ifthecelleditorhasthefocus(thecellisineditmode),pressingEntertakesthecelloutofeditmode.Ifthecontrolhasthefocus,andnotachildcontrol(suchasacelleditor),pressingtheEnterkeyputstheactivecellineditmode.Foroperationmodes,forexample,ifthesheetisinReadOnlymode,itsmapdoesnothaveentriesformovingtheactivecellbecausethereisnoactivecell.Customizethedefaultmapskeepingfocuslocationsandoperationmodesinmind.Eachmappingislikeadictionary,definingameaning(anaction)foreachkeystroke.Justasdifferentdictionariesareneededfordifferentlanguages,differentkeyboardmapsareneededfordifferentfocuslocationsandoperationmodes.
TheSpreadcomponentprovidestwoinputmaps,WhenFocusedandWhenAncestorOfFocused,oneforeachtypeoffocuslocation.TheWhenFocusedmapcontainskeyboardbindingsthatapplywhentheSpreadcomponenthasfocusbutnotwhenachildcontrolhasfocus.PlacinganentryintheWhenFocusedinputmapisequivalenttooverridingtheIsInputKeyandIsInputCharmethods(toreturntrueforthekeystroke)andtheOnKeyDown,
Spread Windows Forms Developer’s Guide 493
Copyright © GrapeCity, Inc. All rights reserved.
OnKeyPress,andOnKeyUpmethods(toprocessthekeystroke).TheWhenAncestorOfFocusedmapcontainskeyboardbindingsthatapplywheneithertheSpreadcomponentorachildcontrolhasfocus.PlacinganentryintheWhenAncestorOfFocusedmapisequivalenttooverridingtheProcessDialogKeyandProcessDialogCharmethods(toprocessthekeystroke).
Thefirstfactoriswhatreceivesthekeystrokeorkeystrokecombination.Keystrokeprocessingin.NETishandledintwophases:apre-processingphaseandanormal-processingphase.MostkeystrokeprocessinginSpreadishandledduringthepre-processingphase,whichcorrespondstotheWhenAncestorOfFocusedinputmapmode(refertoInputMapMode('InputMapModeEnumeration'intheon-linedocumentation)enumerationsettings).Inthepre-processingphase,keystrokesarehandledbytheIsInputChar,IsInputKey,ProcessDialogChar,andProcessDialogKeymethods.Thenormal-processingphasecorrespondstotheWhenFocusedinputmapmode.Inthenormal-processingphase,keystrokesarehandledbytheOnKeyDown,OnKeyPress,andOnKeyUpmethods(whichraisetheKeyDown,KeyPress,andKeyUpeventsrespectively).
ForatypicalSpreadcomponent,mostinteractionsthatoccurwhileyouareworkingwiththecomponentoccuraspartoftheWhenAncestorOfFocusedinputmap.Actionssuchasmovingtheactivecell,selectingarangeofcells,andotherswouldbepartofthismap.Forexample,pressingtheTabkeymovestheactivecell,evenifacellisineditmode.Incontrast,somekeysareonlymappedwhenthereisnotacellineditmode(thecomponenthasthefocus,butnotacelleditor).Forexample,theequals(=)keydoesnotperformanactionifpressedwhenacellisineditmode.Ifnocellisineditmode,pressingtheequalskeystartsformulaeditingfortheactivecell.
GlobalversusLocal
TheSpreadcomponentprovidesaparentglobalinputmap,whichissharedbyallSpreadcomponentsinaproject.WhenyoucustomizetheinputmapforaSpreadcomponent,youarecustomizingalocalmapforonlythatcomponent.
TheglobalmapallowstheSpreadcomponenttosavememorybysharingamap.Thelocalmapletsyoucustomizesettings,thenclearthemlaterandretainthedefaultsettingsaslistedinDefaultKeyboardMaps.
Therefore,whenworkingwithinputmaps,youneedtobeawareofwhichmethodsworkwiththeglobalmapandwhichworkwiththelocalmap.
TheGetmethodtoreturninputmapssearchesallinputmaps,includingtheglobalandthelocal.ThePut,Remove,andClearmethodsonlyworkwiththelocalmap.Forexample,ifyoucalltheRemovemethod,itremovesthecustomsettingsforalocalmap,butdoesnotchangethedefaultsettingsprovidedbytheglobalmap.
Youcannotmodifytheglobalmapitself,butifyouwanttodoso,youcancreateanewinputmapandassignittobetheglobalmapinsteadofthedefaultoneprovided.
ParentversusChildWorkbook
Thekeyboardbindingsintheparentworkbook'sinputmapdonotaffectthechildworkbook.TheSpreadcomponentcontainsoneormoreinstancesoftheSpreadViewclass.Inahierarchysetup,theparentisoneinstanceoftheSpreadViewclassandeachchildisaninstanceoftheSpreadViewclass.EachinstanceoftheSpreadViewclasshasitsowninputmap.Thisgivesyoutheoptionofhavingdifferentkeyboardbehaviorsateachlevelofthehierarchy.Ifyouwantaparticularkeyboardbehavioratalllevelsinthehierarchythenyouwouldneedtomodifytheinputmapfortheparentandeachchild.
EnterKeystrokeBindingException
Mostofthebuilt-inkeystrokesonlyhaveabindingintheWhenAncestorOfFocusedmapandthusonlyletyouoverrideonebinding.TheEnterkeystrokeistheexception.IntheWhenAncestorOfFocusedmap,theEnterkeystrokeisboundtotheStopEditingaction.IntheWhenFocusedmap,theEnterkeystrokeisboundtotheStartEditingaction.Thus,youneedtooverridebothbindings.Hereissomesamplecode:
C#InputMap whenAncestorOfFocusedMap = spread.GetInputMap(InputMapMode.WhenAncestorOfFocused);
Spread Windows Forms Developer’s Guide 494
Copyright © GrapeCity, Inc. All rights reserved.
InputMap whenFocusedMap = spread.GetInputMap(InputMapMode.WhenFocused);whenAncestorOfFocusedMap.Put(new Keystroke(Keys.Enter, Keys.None), SpreadActions.MoveToNextRow);whenFocusedMap.Put(new Keystroke(Keys.Enter, Keys.None), SpreadActions.MoveToNextRow);
ActionCalledNone
TheNoneactionisaspecialactionindicatingthatthekeystrokeisnotprocessedbytheinputmap.
PlacingaNoneactioninaninputmapissimilartocallingtheRemovemethodontheinputmap.ThedifferencebetweenthemisthataNoneactioncanoverrideanentryinaparentmapwhereastheRemovemethodonlyaffectsentriesinthespecifiedmap.Bydefault,theWhenFocusedandWhenAncestorOfFocusedmapshavenodirectentriesbutdohaveindirectentriesviaparentmaps.TheWhenFocused'sparentmapcontainsnobindingfortheEsckey.
Default Keyboard Navigation
Thedefaultbehaviorforend-userkeyboardactionissummarizedinthesetables.
DefaultBehavioronaSheet
Thedefaultbehaviorforend-userkeyboardactiononthesheetissummarizedinthistable.
KeyCode Action ActionNameEscape Ifeditmodeison,previouscellvalue
replacesnewvalueandeditmodeisturnedoff
CancelEditing('CancelEditingField'intheon-linedocumentation)
F2 Ifeditmodeison,clearstheactivecellvalue ClearCell('ClearCellField'intheon-linedocumentation)
Ctrl+CorCtrl+Insert
CopiestheselectiontotheClipboard ClipboardCopy('ClipboardCopyField'intheon-linedocumentation)
Ctrl+XorShift+Delete
CutstheselectiontotheClipboard ClipboardCut('ClipboardCutField'intheon-linedocumentation)
Ctrl+VorShift+Insert
PastesthedataandformattingfromtheClipboard
ClipboardPasteAll('ClipboardPasteAllField'intheon-linedocumentation)
F3 Ifeditmodeison,placesthecurrentdateandtimeinadate-timecell
DateTimeNow('DateTimeNowField'intheon-linedocumentation)
Ctrl+Shift+Home
Extendstheselectiontoincludethefirstcell ExtendToFirstCell('ExtendToFirstCellField'intheon-linedocumentation)
Shift+Home Extendstheselectiontoincludethefirstcolumn
ExtendToFirstColumn('ExtendToFirstColumnField'intheon-linedocumentation)
Shift+Home Extendstheselectiontoincludethefirstiteminalist
ExtendToFirstItem('ExtendToFirstItemField'intheon-linedocumentation)
Ctrl+Shift+End
Extendstheselectiontoincludethelastcell ExtendToLastCell('ExtendToLastCellField'intheon-linedocumentation)
Shift+End Extendstheselectiontoincludethelastcolumn
ExtendToLastColumn('ExtendToLastColumnField'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 495
Copyright © GrapeCity, Inc. All rights reserved.
Shift+End Extendstheselectiontoincludethelastiteminalist
ExtendToLastItem('ExtendToLastItemField'intheon-linedocumentation)
Shift+RightArroworCtrl+Shift+RightArrow
Extendsselectionrightonecolumnbyindex ExtendToNextColumn('ExtendToNextColumnField'intheon-linedocumentation)
Shift+RightArroworCtrl+Shift+RightArrow
Extendsselectionrightonecolumnbyvisual ExtendToNextColumnVisual('ExtendToNextColumnVisualField'intheon-linedocumentation)
Shift+DownArrow
Extendsselectiondownonerow ExtendToNextItem('ExtendToNextItemField'intheon-linedocumentation)
Ctrl+Shift+PageDown
Extendsselectionrightonepageofcolumns ExtendToNextPageOfColumns('ExtendToNextPageOfColumnsField'intheon-linedocumentation)
Shift+PageDown
Extendsselectionrightonepageofitems ExtendToNextPageOfItems('ExtendToNextPageOfItemsField'intheon-linedocumentation)
Shift+PageDown
Extendsselectiondownonepageofrows ExtendToNextPageOfRows('ExtendToNextPageOfRowsField'intheon-linedocumentation)
Shift+DownArroworCtrl+Shift+DownArrow
Extendsselectiondownonerow ExtendToNextRow('ExtendToNextRowField'intheon-linedocumentation)
Shift+LeftArroworCtrl+Shift+LeftArrow
Extendsselectionleftonecolumnbyindex ExtendToPreviousColumn('ExtendToPreviousColumnField'intheon-linedocumentation)
Shift+LeftArroworCtrl+Shift+LeftArrow
Extendsselectionleftonecolumnbyvisual ExtendToPreviousColumnVisual('ExtendToPreviousColumnVisualField'intheon-linedocumentation)
Shift+UpArrow
Extendsselectionleftoneitem ExtendToNextItem('ExtendToNextItemField'intheon-linedocumentation)
Ctrl+Shift+PageUp
Extendsselectionleftonepageofcolumns ExtendToPreviousPageOfColumns('ExtendToPreviousPageOfColumnsField'intheon-linedocumentation)
Shift+PageUp Extendsselectionuponepageofitems ExtendToPreviousPageOfItems('ExtendToPreviousPageOfItemsField'intheon-linedocumentation)
Shift+PageUp Extendsselectionuponepageofrows ExtendToPreviousPageOfRows('ExtendToPreviousPageOfRowsField'intheon-linedocumentation)
Shift+UpArroworCtrl+Shift+UpArrow
Extendsselectionuponerow ExtendToPreviousRow('ExtendToPreviousRowField'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 496
Copyright © GrapeCity, Inc. All rights reserved.
Ctrl+Home Movesactivecelltofirstrow,firstcolumn MoveToFirstCell('MoveToFirstCellField'intheon-linedocumentation)
Home Movesactivecelltothefirstcellintherow MoveToFirstColumn('MoveToFirstColumnField'intheon-linedocumentation)
Home Movesactivecelltothefirstiteminthelist MoveToFirstItem('MoveToFirstItemField'intheon-linedocumentation)
Ctrl+End Movesactivecelltolastrow,lastcolumn MoveToLastCell('MoveToLastCellField'intheon-linedocumentation)
End Movesactivecelltothelastcellintherow MoveToLastColumn('MoveToLastColumnField'intheon-linedocumentation)
End Movesactivecelltothelastiteminthelist MoveToLastItem('MoveToLastItemField'intheon-linedocumentation)
RightArroworCtrl+RightArrow
Movesactivecellrightonecolumnbyindex MoveToNextColumn('MoveToNextColumnField'intheon-linedocumentation)
RightArroworCtrl+RightArrow
Movesactivecellrightonecolumn MoveToNextColumnVisual('MoveToNextColumnVisualField'intheon-linedocumentation)
Tab Movestheactivecelltothenextcolumnandwrapsattheendoftherow.(TheTabkeyskipshiddencolumnsautomatically.)
MoveToNextColumnWrap('MoveToNextColumnWrapField'intheon-linedocumentation)
DownArrow Movestothenextiteminthelist. MoveToNextItem('MoveToNextItemField'intheon-linedocumentation)
Ctrl+PageDown
Movesactivecellrightonepageofcolumns MoveToNextPageOfColumns('MoveToNextPageOfColumnsField'intheon-linedocumentation)
PageDown Movesdownonepageofitems MoveToNextPageOfItems('MoveToNextPageOfItemsField'intheon-linedocumentation)
PageDown Movesactivecelldownonepageofrows MoveToNextPageOfRows('MoveToNextPageOfRowsField'intheon-linedocumentation)
DownArrow Movesactivecelldownonerow MoveToNextRow('MoveToNextRowField'intheon-linedocumentation)
DownArroworCtrl+DownArrow
Movesactivecelldownonerow MoveToNextRow('MoveToNextRowField'intheon-linedocumentation)
LeftroworCtrl+LeftArrow
Movesactivecellleftonecolumnbyindex MoveToPreviousColumn('MoveToPreviousColumnField'intheon-linedocumentation)
LeftArroworCtrl+LeftArrow
Movesactivecellleftonecolumnbyvisual MoveToPreviousColumnVisual('MoveToPreviousColumnVisualField'intheon-linedocumentation)
Shift+Tab Movestheactivecelltothepreviouscolumnandwrapsattheendoftherow.(TheTabkeyskipshiddencolumnsautomatically).
MoveToPreviousColumnWrap('MoveToPreviousColumnWrapField'intheon-linedocumentation)
Ctrl+Left Movestopreviousiteminthelist MoveToPreviousItem('MoveToPreviousItem
Spread Windows Forms Developer’s Guide 497
Copyright © GrapeCity, Inc. All rights reserved.
Arrow Field'intheon-linedocumentation)
Ctrl+PageUp Movesactivecellleftonepageofcolumns MoveToPreviousPageOfColumns('MoveToPreviousPageOfColumnsField'intheon-linedocumentation)
PageUp Movesuponepageofitems MoveToPreviousPageOfItems('MoveToPreviousPageOfItemsField'intheon-linedocumentation)
PageUp Movesactivecelluponepageofrows MoveToPreviousPageOfRows('MoveToPreviousPageOfRowsField'intheon-linedocumentation)
UpArroworCtrl+UpArrow
Movesactivecelluponerow MoveToPreviousRow('MoveToPreviousRowField'intheon-linedocumentation)
Ctrl+Y Movesactivecelluponerow Redo('RedoField'intheon-linedocumentation)
Ctrl+Home Scrollstodisplaythefirstcell ScrollToFirstCell('ScrollToFirstCellField'intheon-linedocumentation)
Home Scrollstodisplaythefirstcolumn ScrollToFirstColumn('ScrollToFirstColumnField'intheon-linedocumentation)
Ctrl+End Scrollstodisplaythelastcell ScrollToLastCell('ScrollToLastCellField'intheon-linedocumentation)
End Scrollstodisplaythelastcolumn ScrollToLastColumn('ScrollToLastColumnField'intheon-linedocumentation)
Right Scrollstodisplaythenextcolumnbyindex ScrollToNextColumn('ScrollToNextColumnField'intheon-linedocumentation)
Right Scrollstodisplaythenextcolumnbyvisual ScrollToNextColumnVisual('ScrollToNextColumnVisualField'intheon-linedocumentation)
Ctrl+PageDown
Scrollstodisplaythenextpageofcolumns ScrollToNextPageOfColumns('ScrollToNextPageOfColumnsField'intheon-linedocumentation)
PageDown Scrollstodisplaythenextpageofrows ScrollToNextPageOfRows('ScrollToNextPageOfRowsField'intheon-linedocumentation)
Down Scrollstodisplaythenextrow ScrollToNextRow('ScrollToNextRowField'intheon-linedocumentation)
Left Scrollstodisplaythepreviouscolumnbyindex
ScrollToPreviousColumn('ScrollToPreviousColumnField'intheon-linedocumentation)
Left Scrollstodisplaythepreviouscolumnbyvisual
ScrollToPreviousColumnVisual('ScrollToPreviousColumnVisualField'intheon-linedocumentation)
Ctrl+PageUp Scrollstodisplaythepreviouspageofcolumns
ScrollToPreviousPageOfColumns('ScrollToPreviousPageOfColumnsField'intheon-linedocumentation)
PageUp Scrollstodisplaythepreviouspageofrows ScrollToPreviousPageOfRows('ScrollToPreviousPageOfRowsField'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 498
Copyright © GrapeCity, Inc. All rights reserved.
UpArrow Scrollstodisplaythepreviousrow ScrollToPreviousRow('ScrollToPreviousRowField'intheon-linedocumentation)
Ctrl+spacebar Selectsthecolumncontainingtheactivecell SelectColumn('SelectColumnField'intheon-linedocumentation)
Home Selectsthefirstiteminthelist SelectFirstItem('SelectFirstItemField'intheon-linedocumentation)
End Selectsthelastiteminthelist SelectLastItem('SelectLastItemField'intheon-linedocumentation)
Down Selectsthenextiteminthelist SelectNextItem('SelectNextItemField'intheon-linedocumentation)
PageDown Selectsthenextpageofitemsinthelist SelectNextPageOfItems('SelectNextPageOfItemsField'intheon-linedocumentation)
UpArrow Selectsthepreviousiteminthelist SelectPreviousItem('SelectPreviousItemField'intheon-linedocumentation)
PageUp Selectsthepreviouspageofitemsinthelist SelectPreviousPageOfItems('SelectPreviousPageOfItemsField'intheon-linedocumentation)
Shift+spacebar Selectstherowcontainingtheactivecell SelectRow('SelectRowField'intheon-linedocumentation)
Ctrl+Shift+spacebar
Selectsthecurrentsheet SelectSheet('SelectSheetField'intheon-linedocumentation)
F4 Ifeditmodeisoninadatecell,spreadsheetdisplaysapop-upcalendartoletyouchooseadate
ShowSubEditor('ShowSubEditorField'intheon-linedocumentation)
EnterorBackspace
Beginsediting;stopseditingifeditmodeison.
StartEditing('StartEditingField'intheon-linedocumentation)orStopEditing('StopEditingField'intheon-linedocumentation)
= Beginseditingformula StartEditingFormula('StartEditingFormulaField'intheon-linedocumentation)
Ctrl+Z Movesactivecelluponerow Undo('UndoField'intheon-linedocumentation)
Keyboardnavigationisdefinedbydefaultmaps,thatmapuserkeyboardactionswithSpreadcomponentactions.Forexample,bydefault,pressingTabmovestheactivecelltothenextcolumn.YoucancustomizeanyorallofthekeyboardactionsbymappingthemtoSpreadcomponentactions.
Thebuilt-inkeyboardactions(forexample,MoveToNextRowWrap)treatacellspanasexistinginbothcolumnsorrows.Youcanenterthespanbynavigatingdowneithercolumnorrow.Whenleavingthespaninabackwardsdirection(forexample,MoveToPreviousRowWrap),thebuilt-inactionusestheupperleftcornerofthespanforcomputingthepreviouscolumnorrow.Whenleavingthespaninaforwardsdirection(forexample,MoveToNextRowWrap),thebuilt-inactionusesthelowerrightcornerofthespanforcomputingthenewcolumnorrow.
FortheCtrl+PageUpandCtrl+PageDownkeys,ifyouwantyourapplicationtomimicthebehaviorfoundinExcel(thatis,moveleftorrightonesheetregardlessofnumberofsheets)thenrebindthekeystrokestotheMoveToPreviousSheetandMoveToNextSheetactions.
Actionsthatextend,move,orscrolltothenextorpreviouscolumnusethevisuallayoutofthescreenbydefault.Thepreviouscolumnisacolumnthatisvisuallyleftoftheactivecolumnandthenextcolumniscolumnthatisvisuallyright
Spread Windows Forms Developer’s Guide 499
Copyright © GrapeCity, Inc. All rights reserved.
oftheactivecolumn.InSpreadWindowsForms2.5,cellcoordinateswereused.Incellcoordinates,thepreviouscolumnistheactivecolumn-1andthenextcolumnistheactivecolumn+1.ThecellcoordinateactionsarestillavailableandarelistedintheSpreadActions('SpreadActionsClass'intheon-linedocumentation)class.
DefaultBehaviorforShapesonaSheet
ThedefaultnavigationkeysforshapesonasheetareusedwithalloperationmodesandcanbechangedwiththeSetInputMapWhenShapeHasFocus('SetInputMapWhenShapeHasFocusMethod'intheon-linedocumentation)method.Thedefaultnavigationkeysforshapesarelistedinthefollowingtable.
KeyCode Action ActionNameTab Movestonextshape ActivateNextShape('ActivateNextShapeField'intheon-line
documentation)
Shift+Tab Movestopreviousshape
ActivatePreviousShape('ActivatePreviousShapeField'intheon-linedocumentation)
Ctrl+CorCtrl+Insert
Copiesshape ClipboardCopyShape('ClipboardCopyShapeField'intheon-linedocumentation)
Ctrl+XorShift+Delete
Cutsshape ClipboardCutShape('ClipboardCutShapeField'intheon-linedocumentation)
Ctrl+VorShift+Insert
Pastesshape ClipboardPasteShape('ClipboardPasteShapeField'intheon-linedocumentation)
N/A Cutsdataonly ClipboardCutDataOnly('ClipboardCutDataOnlyField'intheon-linedocumentation)
Escape Deactivatesshape DeactivateShape('DeactivateShapeField'intheon-linedocumentation)
Ctrl+UpArrow
Decreasesshapeheight
DecreaseShapeHeight('DecreaseShapeHeightField'intheon-linedocumentation)
Ctrl+LeftArrow
Decreasesshapewidth
DecreaseShapeWidth('DecreaseShapeWidthField'intheon-linedocumentation)
Delete Deletesshape DeleteShape('DeleteShapeField'intheon-linedocumentation)
Ctrl+DownArrow
Increasesshapeheight
IncreaseShapeHeight('IncreaseShapeHeightField'intheon-linedocumentation)
Ctrl+RightArrow
Increasesshapewidth
IncreaseShapeWidth('IncreaseShapeWidthField'intheon-linedocumentation)
DownArrow Movesshapedown MoveShapeDown('MoveShapeDownField'intheon-linedocumentation)
LeftArrow Movesshapeleft MoveShapeLeft('MoveShapeLeftField'intheon-linedocumentation)
RightArrow Movesshaperight MoveShapeRight('MoveShapeRightField'intheon-linedocumentation)
UpArrow Movesshapeup MoveShapeUp('MoveShapeUpField'intheon-linedocumentation)
Alt+RightArrow
Rotatesshapeclockwise
RotateShapeClockwise('RotateShapeClockwiseField'intheon-linedocumentation)
Alt+LeftArrow
Rotatesshapecounter-clockwise
RotateShapeCounterClockwise('RotateShapeCounterClockwiseField'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 500
Copyright © GrapeCity, Inc. All rights reserved.
Formoreinformationaboutshapes,refertoCustomizingDrawing.
DefaultBehaviorforChildControlsonaSheet
ThedefaultnavigationkeysforchildcontrolsonasheetareusedwithalloperationmodesandcanbechangedwiththeSetInputMapWhenChildHasFocus('SetInputMapWhenChildHasFocusMethod'intheon-linedocumentation)method.Thedefaultnavigationkeysforchildcontrolsonasheetarelistedinthefollowingtable.
KeyCode Action ActionNameTab Movestonext
controlActivateNextChild('ActivateNextChildField'intheon-linedocumentation)
Shift+Tab Movestopreviouscontrol
ActivateNextShape('ActivateNextShapeField'intheon-linedocumentation)
Escape Deactivatescontrol DeactivateChild('DeactivateChildField'intheon-linedocumentation)
Ctrl+UpArrow
Decreasescontrolheight
DecreaseChildHeight('DecreaseChildHeightField'intheon-linedocumentation)
Ctrl+LeftArrow
Decreasescontrolwidth
DecreaseShapeWidth('DecreaseShapeWidthField'intheon-linedocumentation)
Delete Deletescontrol DeleteChild('DeleteChildField'intheon-linedocumentation)
Ctrl+DownArrow
Increasescontrolheight
IncreaseChildHeight('IncreaseChildHeightField'intheon-linedocumentation)
Ctrl+RightArrow
Increasescontrolwidth
IncreaseChildWidth('IncreaseChildWidthField'intheon-linedocumentation)
DownArrow Movescontroldown MoveChildDown('MoveChildDownField'intheon-linedocumentation)
LeftArrow Movescontrolleft MoveChildLeft('MoveChildLeftField'intheon-linedocumentation)
RightArrow Movescontrolright MoveChildRight('MoveChildRightField'intheon-linedocumentation)
UpArrow Movescontrolup MoveChildUp('MoveChildUpField'intheon-linedocumentation)
Formoreinformationaboutcontrols,refertoPlacingChildControlsonaSheet.
Default Keyboard Maps
Spreadprovidestwelvedefaultmapsthatmapkeystrokestoactionsforeachfocuslocation(alsoreferredtoasinputmapmode)andoperationmode.Youcancustomizeanyorallofthesemapstochangetheactionassociatedwithakeystrokeortoaddadditionalactionsforotherkeystrokes.
ThefollowingdefaultmapsareprovidedwithSpreadWindowsFormsforeachoperationmodeandinputmapmode.
DefaultMapforExcelCompatibilityDefaultMapforNormalandWhenFocusedDefaultMapforNormalandWhenAncestorOfFocusedDefaultMapforReadOnlyandWhenFocusedDefaultMapforReadOnlyandWhenAncestorOfFocusedDefaultMapforRowModeandWhenFocusedDefaultMapforRowModeandWhenAncestorOfFocused
Spread Windows Forms Developer’s Guide 501
Copyright © GrapeCity, Inc. All rights reserved.
DefaultMapforSingleSelectandWhenFocusedDefaultMapforSingleSelectandWhenAncestorOfFocusedDefaultMapforMultiSelectandWhenFocusedDefaultMapforMultiSelectandWhenAncestorOfFocusedDefaultMapforExtendedSelectandWhenFocusedDefaultMapforExtendedSelectandWhenAncestorOfFocused
Default Map for Excel Compatibility
ThedefaultmapforExcelcompatibilitymodeissummarizedinthistable.ThistableapplieswhentheinputmapmodeisWhenAncestorOfFocusedandthestateisnormaloreditmode.
KeyCode ActionNameDelete ClearSelectedCellsData('ClearSelectedCellsDataField'intheon-line
documentation)
Ctrl+UpArrow MoveToPreviousRowWithData('MoveToPreviousRowWithDataField'intheon-linedocumentation)
Ctrl+DownArrow MoveToNextRowWithData('MoveToNextRowWithDataField'intheon-linedocumentation)
Ctrl+LeftArrow MoveToPreviousColumnWithData('MoveToPreviousColumnWithDataField'intheon-linedocumentation)
Ctrl+RightArrow MoveToNextColumnWithData('MoveToNextColumnWithDataField'intheon-linedocumentation)
Ctrl+Shift+UpArrow
ExtendToPreviousRowWithData('ExtendToPreviousRowWithDataField'intheon-linedocumentation)
Ctrl+Shift+DownArrow
ExtendToNextRowWithData('ExtendToNextRowWithDataField'intheon-linedocumentation)
Ctrl+Shift+LeftArrow
ExtendToPreviousColumnWithData('ExtendToPreviousColumnWithDataField'intheon-linedocumentation)
Ctrl+Shift+RightArrow
ExtendToNextColumnWithData('ExtendToNextColumnWithDataField'intheon-linedocumentation)
F2 StartEditing('StartEditingField'intheon-linedocumentation)
F4 Redo('RedoField'intheon-linedocumentation)
Enter MoveToNextRow('MoveToNextRowField'intheon-linedocumentation)
Shift+Enter MoveToPreviousRow('MoveToPreviousRowField'intheon-linedocumentation)
Ctrl+PageUp MoveToPreviousSheet('MoveToPreviousSheetField'intheon-linedocumentation)
Ctrl+PageDown MoveToNextSheet('MoveToNextSheetField'intheon-linedocumentation)
Alt+PageUp MoveToPreviousPageOfColumns('MoveToPreviousPageOfColumnsField'intheon-linedocumentation)
Alt+PageDown MoveToNextPageOfColumns('MoveToNextPageOfColumnsField'intheon-linedocumentation)
Ctrl+; DateTimeNow('DateTimeNowField'intheon-linedocumentation)
Tab MoveToNextColumnVisual('MoveToNextColumnVisualField'intheon-line
Spread Windows Forms Developer’s Guide 502
Copyright © GrapeCity, Inc. All rights reserved.
documentation)
Shift+Tab MoveToPreviousColumnVisual('MoveToPreviousColumnVisualField'intheon-linedocumentation)
Ctrl+A SelectSheet('SelectSheetField'intheon-linedocumentation)
Alt+Backspace Undo('UndoField'intheon-linedocumentation)
ThefollowingtableapplieswhentheinputmapmodeisWhenFocusedandthestateisnormal.
KeyCode ActionNameCtrl+C ClipboardCopy('ClipboardCopyField'intheon-linedocumentation)
Ctrl+Insert ClipboardCopy('ClipboardCopyField'intheon-linedocumentation)
Ctrl+X ClipboardCut('ClipboardCutField'intheon-linedocumentation)
Shift+Delete ClipboardCut('ClipboardCutField'intheon-linedocumentation)
Ctrl+V ClipboardPasteAll('ClipboardPasteAllField'intheon-linedocumentation)
Shift+Insert ClipboardPasteAll('ClipboardPasteAllField'intheon-linedocumentation)
Backspace StartEditing('StartEditingField'intheon-linedocumentation)
= StartEditingFormula('StartEditingFormulaField'intheon-linedocumentation)
Ctrl+Z Undo('UndoField'intheon-linedocumentation)
Ctrl+Y Redo('RedoField'intheon-linedocumentation)
Default Map for Normal and WhenFocused
Thedefaultmapforthisoperationmodeandinputmapmodeissummarizedinthistable.
KeyCode ActionNameCtrl+C ClipboardCopy('ClipboardCopyField'intheon-linedocumentation)
Ctrl+Insert ClipboardCopy('ClipboardCopyField'intheon-linedocumentation)
Ctrl+X ClipboardCut('ClipboardCutField'intheon-linedocumentation)
Shift+Delete ClipboardCut('ClipboardCutField'intheon-linedocumentation)
Ctrl+V ClipboardPasteAll('ClipboardPasteAllField'intheon-linedocumentation)
Shift+Insert ClipboardPasteAll('ClipboardPasteAllField'intheon-linedocumentation)
Enter StartEditing('StartEditingField'intheon-linedocumentation)
= StartEditingFormula('StartEditingFormulaField'intheon-linedocumentation)
Default Map for Normal and WhenAncestorOfFocused
Thedefaultmapforthisoperationmodeandinputmapmodeissummarizedinthistable.
KeyCode ActionNameEsc CancelEditing('CancelEditingField'intheon-linedocumentation)
Alt+DownArrow ComboShowList('ComboShowListField'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 503
Copyright © GrapeCity, Inc. All rights reserved.
Alt+UpArrow ComboShowList('ComboShowListField'intheon-linedocumentation)
F2 ClearCell('ClearCellField'intheon-linedocumentation)
F3 DateTimeNow('DateTimeNowField'intheon-linedocumentation)
Ctrl+Shift+Home ExtendToFirstCell('ExtendToFirstCellField'intheon-linedocumentation)
Shift+Home ExtendToFirstColumn('ExtendToFirstColumnField'intheon-linedocumentation)
Ctrl+Shift+End ExtendToLastCell('ExtendToLastCellField'intheon-linedocumentation)
Shift+End ExtendToLastColumn('ExtendToLastColumnField'intheon-linedocumentation)
Shift+RightArrow ExtendToNextColumnVisual('ExtendToNextColumnVisualField'intheon-linedocumentation)
Ctrl+Shift+RightArrow
ExtendToNextColumnVisual('ExtendToNextColumnVisualField'intheon-linedocumentation)
Ctrl+Shift+PageDown
ExtendToNextPageOfColumns('ExtendToNextPageOfColumnsField'intheon-linedocumentation)
PageDown ExtendToNextPageOfRows('ExtendToNextPageOfRowsField'intheon-linedocumentation)
Shift+PageDown ExtendToNextPageOfRows('ExtendToNextPageOfRowsField'intheon-linedocumentation)
Shift+DownArrow ExtendToNextRow('ExtendToNextRowField'intheon-linedocumentation)
Ctrl+Shift+DownArrow
ExtendToNextRow('ExtendToNextRowField'intheon-linedocumentation)
Shift+LeftArrow ExtendToPreviousColumnVisual('ExtendToPreviousColumnVisualField'intheon-linedocumentation)
Ctrl+Shift+LeftArrow
ExtendToPreviousColumnVisual('ExtendToPreviousColumnVisualField'intheon-linedocumentation)
Ctrl+Shift+PageUp ExtendToPreviousPageOfColumns('ExtendToPreviousPageOfColumnsField'intheon-linedocumentation)
Shift+UpArrow ExtendToPreviousRow('ExtendToPreviousRowField'intheon-linedocumentation)
Ctrl+Shift+UpArrow
ExtendToPreviousRow('ExtendToPreviousRowField'intheon-linedocumentation)
PageUp ExtendToPreviousPageOfRows('ExtendToPreviousPageOfRowsField'intheon-linedocumentation)
Shift+PageUp ExtendToPreviousPageOfRows('ExtendToPreviousPageOfRowsField'intheon-linedocumentation)
Ctrl+Home MoveToFirstCell('MoveToFirstCellField'intheon-linedocumentation)
Home MoveToFirstColumn('MoveToFirstColumnField'intheon-linedocumentation)
Ctrl+End MoveToLastCell('MoveToLastCellField'intheon-linedocumentation)
End MoveToLastColumn('MoveToLastColumnField'intheon-linedocumentation)
RightArrow MoveToNextColumnVisual('MoveToNextColumnVisualField'intheon-linedocumentation)
Ctrl+RightArrow MoveToNextColumnVisual('MoveToNextColumnVisualField'intheon-line
Spread Windows Forms Developer’s Guide 504
Copyright © GrapeCity, Inc. All rights reserved.
documentation)
Tab MoveToNextColumnWrap('MoveToNextColumnWrapField'intheon-linedocumentation)
DownArrow MoveToNextRow('MoveToNextRowField'intheon-linedocumentation)
Ctrl+DownArrow MoveToNextRow('MoveToNextRowField'intheon-linedocumentation)
LeftArrow MoveToPreviousColumnVisual('MoveToPreviousColumnVisualField'intheon-linedocumentation)
Ctrl+LeftArrow MoveToPreviousColumnVisual('MoveToPreviousColumnVisualField'intheon-linedocumentation)
Shift+Tab MoveToPreviousColumnWrap('MoveToPreviousColumnWrapField'intheon-linedocumentation)
Ctrl+PageUp MoveToPreviousPageOfRows('MoveToPreviousPageOfRowsField'intheon-linedocumentation)
Ctrl+PageDown MoveToPreviousPageOfColumns('MoveToPreviousPageOfColumnsField'intheon-linedocumentation)
Ctrl+UpArrow MoveToPreviousRow('MoveToPreviousRowField'intheon-linedocumentation)
UpArrow MoveToPreviousRow('MoveToPreviousRowField'intheon-linedocumentation)
Ctrl+spacebar SelectColumn('SelectColumnField'intheon-linedocumentation)
Shift+spacebar SelectRow('SelectRowField'intheon-linedocumentation)
Enter SelectRow('SelectRowField'intheon-linedocumentation)
Ctrl+Shift+spacebar SelectSheet('SelectSheetField'intheon-linedocumentation)
F4 ShowSubEditor('ShowSubEditorField'intheon-linedocumentation)
Default Map for ReadOnly and WhenFocused
Nodefaultactionsaredefinedforthisoperationmodeandinputmapmode.
Default Map for ReadOnly and WhenAncestorOfFocused
Thedefaultmapforthisoperationmodeandinputmapmodeissummarizedinthistable.
KeyCode ActionNameCtrl+Home ScrollToFirstCell('ScrollToFirstCellField'intheon-linedocumentation)
Home ScrollToFirstColumn('ScrollToFirstColumnField'intheon-linedocumentation)
Ctrl+End ScrollToLastCell('ScrollToLastCellField'intheon-linedocumentation)
End ScrollToLastColumn('ScrollToLastColumnField'intheon-linedocumentation)
RightArrow ScrollToNextColumnVisual('ScrollToNextColumnVisualField'intheon-linedocumentation)
Ctrl+PageDown
ScrollToNextPageOfColumns('ScrollToNextPageOfColumnsField'intheon-linedocumentation)
PageDown ScrollToNextPageOfRows('ScrollToNextPageOfRowsField'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 505
Copyright © GrapeCity, Inc. All rights reserved.
DownArrow ScrollToNextRow('ScrollToNextRowField'intheon-linedocumentation)
LeftArrow ScrollToPreviousColumnVisual('ScrollToPreviousColumnVisualField'intheon-linedocumentation)
Ctrl+PageUp
ScrollToPreviousPageOfColumns('ScrollToPreviousPageOfColumnsField'intheon-linedocumentation)
PageUp ScrollToPreviousPageOfRows('ScrollToPreviousPageOfRowsField'intheon-linedocumentation)
UpArrow ScrollToPreviousRow('ScrollToPreviousRowField'intheon-linedocumentation)
Default Map for RowMode and WhenFocused
Thedefaultmapforthisoperationmodeandinputmapmodeissummarizedinthistable.
KeyCode ActionNameF2 ClearCell('ClearCellField'intheon-linedocumentation)
Alt+UpArrow ComboShowList('ComboShowListField'intheon-linedocumentation)
Alt+DownArrow ComboShowList('ComboShowListField'intheon-linedocumentation)
F3 DateTimeNow('DateTimeNowField'intheon-linedocumentation)
F4 ShowSubEditor('ShowSubEditorField'intheon-linedocumentation)
Enter StartEditing('StartEditingField'intheon-linedocumentation)
= StartEditingFormula('StartEditingFormulaField'intheon-linedocumentation)
Default Map for RowMode and WhenAncestorOfFocused
Thedefaultmapforthisoperationmodeandinputmapmodeissummarizedinthistable.
KeyCode ActionNameEsc CancelEditing('CancelEditingField'intheon-linedocumentation)
Ctrl+Home MoveToFirstCell('MoveToFirstCellField'intheon-linedocumentation)
Home MoveToFirstColumn('MoveToFirstColumnField'intheon-linedocumentation)
Ctrl+End MoveToLastCell('MoveToLastCellField'intheon-linedocumentation)
End MoveToLastColumn('MoveToLastColumnField'intheon-linedocumentation)
RightArrow MoveToNextColumnVisual('MoveToNextColumnVisualField'intheon-linedocumentation)
Ctrl+RightArrow
MoveToNextColumnVisual('MoveToNextColumnVisualField'intheon-linedocumentation)
Tab MoveToNextColumnWrap('MoveToNextColumnWrapField'intheon-linedocumentation)
Ctrl+PageDown
MoveToNextPageOfColumns('MoveToNextPageOfColumnsField'intheon-linedocumentation)
PageDown MoveToNextPageOfRows('MoveToNextPageOfRowsField'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 506
Copyright © GrapeCity, Inc. All rights reserved.
DownArrow MoveToNextRow('MoveToNextRowField'intheon-linedocumentation)
Ctrl+DownArrow
MoveToNextRow('MoveToNextRowField'intheon-linedocumentation)
LeftArrow MoveToPreviousColumnVisual('MoveToPreviousColumnVisualField'intheon-linedocumentation)
Ctrl+LeftArrow
MoveToPreviousColumnVisual('MoveToPreviousColumnVisualField'intheon-linedocumentation)
Shift+Tab MoveToPreviousColumnWrap('MoveToPreviousColumnWrapField'intheon-linedocumentation)
Ctrl+PageUp MoveToPreviousPageOfColumns('MoveToPreviousPageOfColumnsField'intheon-linedocumentation)
PageUp MoveToPreviousPageOfRows('MoveToPreviousPageOfRowsField'intheon-linedocumentation)
UpArrow MoveToPreviousRow('MoveToPreviousRowField'intheon-linedocumentation)
Ctrl+UpArrow
MoveToPreviousRow('MoveToPreviousRowField'intheon-linedocumentation)
Enter StopEditing('StopEditingField'intheon-linedocumentation)
Default Map for SingleSelect and WhenFocused
Thedefaultmapforthisoperationmodeandinputmapmodeissummarizedinthistable.
KeyCode ActionNameCtrl+C ClipboardCopy('ClipboardCopyField'intheon-linedocumentation)
Ctrl+Insert ClipboardCopy('ClipboardCopyField'intheon-linedocumentation)
Default Map for SingleSelect and WhenAncestorOfFocused
Thedefaultmapforthisoperationmodeandinputmapmodeissummarizedinthistable.
KeyCode
ActionName
RightArrow
ScrollToNextColumnVisual('ScrollToNextColumnVisualField'intheon-linedocumentation)
LeftArrow ScrollToPreviousColumnVisual('ScrollToPreviousColumnVisualField'intheon-linedocumentation)
Home SelectFirstItem('SelectFirstItemField'intheon-linedocumentation)
End SelectLastItem('SelectLastItemField'intheon-linedocumentation)
DownArrow
SelectNextItem('SelectNextItemField'intheon-linedocumentation)
PageDown SelectNextPageOfItems('SelectNextPageOfItemsField'intheon-linedocumentation)
UpArrow SelectPreviousItem('SelectPreviousItemField'intheon-linedocumentation)
PageUp SelectPreviousPageOfItems('SelectPreviousPageOfItemsField'intheon-line
Spread Windows Forms Developer’s Guide 507
Copyright © GrapeCity, Inc. All rights reserved.
documentation)
Default Map for MultiSelect and WhenFocused
Thedefaultmapforthisoperationmodeandinputmapmodeissummarizedinthistable.
KeyCode ActionNameCtrl+C ClipboardCopy('ClipboardCopyField'intheon-linedocumentation)
Ctrl+Insert ClipboardCopy('ClipboardCopyField'intheon-linedocumentation)
Default Map for MultiSelect and WhenAncestorOfFocused
Thedefaultmapforthisoperationmodeandinputmapmodeissummarizedinthistable.
KeyCode
ActionName
Home MoveToFirstItem('MoveToFirstItemField'intheon-linedocumentation)
End MoveToLastItem('MoveToLastItemField'intheon-linedocumentation)
DownArrow
MoveToNextItem('MoveToNextItemField'intheon-linedocumentation)
PageDown MoveToNextPageOfItems('MoveToNextPageOfItemsField'intheon-linedocumentation)
UpArrow MoveToPreviousItem('MoveToPreviousItemField'intheon-linedocumentation)
PageUp MoveToPreviousPageOfItems('MoveToPreviousPageOfItemsField'intheon-linedocumentation)
RightArrow
ScrollToNextColumnVisual('ScrollToNextColumnVisualField'intheon-linedocumentation)
LeftArrow ScrollToPreviousColumnVisual('ScrollToPreviousColumnVisualField'intheon-linedocumentation)
spacebar ToggleItem('ToggleItemField'intheon-linedocumentation)
Default Map for ExtendedSelect and WhenFocused
Thedefaultmapforthisoperationmodeandinputmapmodeissummarizedinthistable.
KeyCode ActionNameCtrl+C ClipboardCopy('ClipboardCopyField'intheon-linedocumentation)
Ctrl+Insert ClipboardCopy('ClipboardCopyField'intheon-linedocumentation)
Default Map for ExtendedSelect and WhenAncestorOfFocused
Thedefaultmapforthisoperationmodeandinputmapmodeissummarizedinthistable.
Key ActionName
Spread Windows Forms Developer’s Guide 508
Copyright © GrapeCity, Inc. All rights reserved.
CodeRight ScrollToNextColumnVisual('ScrollToNextColumnVisualField'intheon-line
documentation)
LeftArrow ScrollToPreviousColumnVisual('ScrollToPreviousColumnVisualField'intheon-linedocumentation)
Home SelectFirstItem('SelectFirstItemField'intheon-linedocumentation)
End SelectLastItem('SelectLastItemField'intheon-linedocumentation)
DownArrow
SelectNextItem('SelectNextItemField'intheon-linedocumentation)
PageDown SelectNextPageOfItems('SelectNextPageOfItemsField'intheon-linedocumentation)
PageUp SelectPreviousPageOfItems('SelectPreviousPageOfItemsField'intheon-linedocumentation)
UpArrow SelectPreviousItem('SelectPreviousItemField'intheon-linedocumentation)
Deactivating the Default Keyboard Map
Youcandeactivateorturnoffthedefaultinputmap.
UsingCode
1. CreateanInputMap('InputMapClass'intheon-linedocumentation)object.2. UsetheGetInputMap('GetInputMapMethod'intheon-linedocumentation)method.
Example
ThisexampledeactivatestheF2key.
C#private void Form1_Load(object sender, System.EventArgs e){ FarPoint.Win.Spread.InputMap im = new FarPoint.Win.Spread.InputMap(); // Deactivate F2 key in cells not being edited. im = fpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused); im.Put(new FarPoint.Win.Spread.Keystroke(Keys.F2, Keys.None), FarPoint.Win.Spread.SpreadActions.None); // Deactivate F2 key in cells being edited. im = fpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused);im.Put(new FarPoint.Win.Spread.Keystroke(Keys.F2, Keys.None), FarPoint.Win.Spread.SpreadActions.None);}
VBPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim im As New FarPoint.Win.Spread.InputMap ' Deactivate F2 key in cells not being edited. im = FpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused) im.Put(New FarPoint.Win.Spread.Keystroke(Keys.F2, Keys.None), FarPoint.Win.Spread.SpreadActions.None)
Spread Windows Forms Developer’s Guide 509
Copyright © GrapeCity, Inc. All rights reserved.
' Deactivate F2 key in cells being edited. im = FpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused) im.Put(New FarPoint.Win.Spread.Keystroke(Keys.F2, Keys.None), FarPoint.Win.Spread.SpreadActions.None)End Sub
Changing the Default Keyboard Map
Thedefaultinputmapdefinesthebehaviorofthecomponentforenduserinteractionwiththekeyboard.Forexample,bydefault,whentheenduserpressestheEnterkeyinanactivecell,theeditmodeturnsonforthatcell.Youcanchangethisdefaultbehavior,bychangingthedefaultinputmap.
UsingCode
1. CreateanInputMap('InputMapClass'intheon-linedocumentation)object.2. UsetheGetInputMap('GetInputMapMethod'intheon-linedocumentation)method.
Example
ThisexamplechangesthebehaviorsothatpressingtheEnterkeymovestheactivecelltothenextrow.
C#private void Form1_Load(object sender, System.EventArgs e){ FarPoint.Win.Spread.InputMap im = new FarPoint.Win.Spread.InputMap(); // Define the operation of pressing Enter key in cells not being edited as "Move to the next row". im = fpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused); im.Put(new FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow); // Define the operation of pressing Enter key in cells being edited as "Move to the next row". im = fpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused); im.Put(new FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow);}
VBPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim im As New FarPoint.Win.Spread.InputMap ' Define the operation of pressing Enter key in cells not being edited as "Move to the next row". im = FpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused) im.Put(New FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow) ' Define the operation of pressing Enter key in cells being edited as "Move to the next row".im = FpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused)
Spread Windows Forms Developer’s Guide 510
Copyright © GrapeCity, Inc. All rights reserved.
im.Put(New FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow)End Sub
Example
ThisexampledeactivatestheF2key.
C#private void Form1_Load(object sender, System.EventArgs e){ FarPoint.Win.Spread.InputMap im = new FarPoint.Win.Spread.InputMap(); // Deactivate F2 key in cells not being edited. im = fpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused); im.Put(new FarPoint.Win.Spread.Keystroke(Keys.F2, Keys.None), FarPoint.Win.Spread.SpreadActions.None); // Deactivate F2 key in cells being edited. im = fpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused);im.Put(new FarPoint.Win.Spread.Keystroke(Keys.F2, Keys.None), FarPoint.Win.Spread.SpreadActions.None);}
VBPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim im As New FarPoint.Win.Spread.InputMap ' Deactivate F2 key in cells not being edited. im = FpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused) im.Put(New FarPoint.Win.Spread.Keystroke(Keys.F2, Keys.None), FarPoint.Win.Spread.SpreadActions.None) ' Deactivate F2 key in cells being edited. im = FpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused) im.Put(New FarPoint.Win.Spread.Keystroke(Keys.F2, Keys.None), FarPoint.Win.Spread.SpreadActions.None)End Sub
Using Input Maps with Action Maps
Internally,theSpreadViewobjectusesaninputmappairedwithanactionmaptoprocessakeystroke.Aninputmap(InputMap('InputMapClass'intheon-linedocumentation)object)isusedtoconvertakeystroke(KeyStroke('KeystrokeStructure'intheon-linedocumentation)object)toanobjectthatidentifiestheaction.Anactionmap(ActionMap('ActionMapClass'intheon-linedocumentation)object)isusedtoconverttheobjecttoanaction.
UsingCode
1. CreateanewInputMap('InputMapClass'intheon-linedocumentation)objectforwhichtomapkeysandactions.
2. SetanexistinginputmapequaltotheInputMap('InputMapClass'intheon-linedocumentation)objectyoucreated.
3. UsetheInputMap('InputMapClass'intheon-linedocumentation)classPutmethodtomapspecifickeystospecificactions.
Spread Windows Forms Developer’s Guide 511
Copyright © GrapeCity, Inc. All rights reserved.
Example
Forexample,theinternalcodethathandlesKeyDowneventslookssomethinglikethis:
C#object actionMapKey = GetInputMap(InputMapMode.WhenFocused).Get(newKeystroke(e.KeyCode, e.Modifiers));if (actionMapKey != null){ Action action = GetActionMap().Get(actionMapKey); if (action != null) { action.PerformAction(this); e.Handled = true; }}
VBDim actionMapKey As Object = GetInputMap(InputMapMode.WhenFocused).Get(New Keystroke(e.KeyCode, e.Modifiers))If Not (actionMapKey Is Nothing) Then Dim action As Action = GetActionMap().Get(actionMapKey) If Not (action Is Nothing) Then action.PerformAction(Me) e.Handled = True End IfEnd If
ExcelusesCtl+9andCtl+Shift+9tohideandunhiderows.SupposeyouwanttoimplementthisfeatureinSpread.Youcouldcreatethefollowingclassestodefinethehideandunhideactions.
C#private class HideRowAction : Action{ public override void PerformAction(object source) { if (source is SpreadView) { SpreadView spread = (SpreadView)source; SheetView sheet = spread.Sheets[spread.ActiveSheetIndex]; if (sheet.SelectionCount > 0) { for (int i = 0; i < sheet.SelectionCount; i++) { CellRange range = sheet.GetSelection(i); if (range.Row == -1) sheet.Rows[0, sheet.RowCount - 1].Visible = false; else sheet.Rows[range.Row, range.Row + range.RowCount - 1].Visible = false; } } else { sheet.Rows[sheet.ActiveRowIndex].Visible = false;
Spread Windows Forms Developer’s Guide 512
Copyright © GrapeCity, Inc. All rights reserved.
} } }} private class UnhideRowAction : Action{ public override void PerformAction(object source) { if (source is SpreadView) { SpreadView spread = (SpreadView)source; SheetView sheet = spread.Sheets[spread.ActiveSheetIndex]; if (sheet.SelectionCount > 0) { for (int i = 0; i < sheet.SelectionCount; i++) { CellRange range = sheet.GetSelection(i); if (range.Row == -1) sheet.Rows[0, sheet.RowCount - 1].Visible = true; else sheet.Rows[range.Row, range.Row + range.RowCount - 1].Visible = true; } } else { sheet.Rows[sheet.ActiveRowIndex].Visible = true; } } }}
VBPrivate Class HideRowAction Inherits Action Public Overrides Sub PerformAction([source] As Object) If TypeOf [source] Is SpreadView Then Dim spread As SpreadView = CType([source], SpreadView) Dim sheet As SheetView = spread.Sheets(spread.ActiveSheetIndex) If sheet.SelectionCount > 0 Then Dim i As Integer For i = 0 To sheet.SelectionCount - 1 Dim range As CellRange = sheet.GetSelection(i) If range.Row = - 1 Then sheet.Rows(0, sheet.RowCount - 1).Visible = False Else sheet.Rows(range.Row, range.Row + range.RowCount - 1).Visible = False End If Next i Else sheet.Rows(sheet.ActiveRowIndex).Visible = False End If End If End Sub 'PerformActionEnd Class 'HideRowAction
Spread Windows Forms Developer’s Guide 513
Copyright © GrapeCity, Inc. All rights reserved.
Private Class UnhideRowAction Inherits Action Public Overrides Sub PerformAction([source] As Object) If TypeOf [source] Is SpreadView Then Dim spread As SpreadView = CType([source], SpreadView) Dim sheet As SheetView = spread.Sheets(spread.ActiveSheetIndex) If sheet.SelectionCount > 0 Then Dim i As Integer For i = 0 To sheet.SelectionCount - 1 Dim range As CellRange = sheet.GetSelection(i) If range.Row = - 1 Then sheet.Rows(0, sheet.RowCount - 1).Visible = True Else sheet.Rows(range.Row, range.Row + range.RowCount - 1).Visible = True End If Next i Else sheet.Rows(sheet.ActiveRowIndex).Visible = True End If End If End Sub 'PerformActionEnd Class 'UnhideRowAction
Youcouldthenaddthekeystrokesandactionstothemapsasfollows.
C#InputMap im = spread.GetInputMap(InputMapMode.WhenFocused);ActionMap am = spread.GetActionMap();im.Put(new Keystroke(Keys.D9, Keys.Control), "HideRow");im.Put(new Keystroke(Keys.D9, Keys.Control | Keys.Shift), "UnhideRow");am.Put("HideRow", new HideRowAction());am.Put("UnhideRow", new UnhideRowAction());
VBDim im As InputMap = spread.GetInputMap(InputMapMode.WhenFocused)Dim am As ActionMap = spread.GetActionMap()im.Put(New Keystroke(Keys.D9, Keys.Control), "HideRow")im.Put(New Keystroke(Keys.D9, Keys.Control Or Keys.Shift), "UnhideRow")am.Put("HideRow", New HideRowAction())am.Put("UnhideRow", New UnhideRowAction())
Formoreinformation,refertothemethodsinActionMap('ActionMapClass'intheon-linedocumentation)andInputMap('InputMapClass'intheon-linedocumentation)classes.
C#public class FpSpread : ...{ ... public ActionMap GetActionMap(); public void SetActionMap(ActionMap value);} public class SpreadView : ...{ ... public ActionMap GetActionMap();
Spread Windows Forms Developer’s Guide 514
Copyright © GrapeCity, Inc. All rights reserved.
public void SetActionMap(ActionMap value);} public class ActionMap{ public ActionMap(); public object[] AllKeys(); public object[] Keys(); public ActionMap Parent { get; set; } public int Size { get; } public void Clear(); public Action Get(object key); public void Put(object key, Action action); public void Remove(object key);} public abstract class Action{ public abstract void PerformAction(object source);}
VBPublic Class FpSpread ......Public Function GetActionMap() As ActionMap
Public Sub SetActionMap(value As ActionMap)
End Class 'FpSpread
Public Class SpreadView ......Public Function GetActionMap() As ActionMap
Public Sub SetActionMap(value As ActionMap)
End Class 'SpreadView
Public Class ActionMap
Public Sub ActionMap()Public object AllKeys()Public object Keys()Public ActionMap ParentPublic Size As IntegerPublic Sub Clear()Public Action Get(By key As object)Public Sub Put(By key As object, By action As Action)Public Sub Remove(By key As object)}
Public MustOverride Class Action{Public Sub PerformAction(By source As object)}
Customizing the Input Maps
YoucanusethedefaultnavigationkeysthataremappedtoSpreadactions.YoucanalsocustomizetheseinputmapssothatanykeyorkeycombinationcanmaptoanySpreadcomponentaction.
Spread Windows Forms Developer’s Guide 515
Copyright © GrapeCity, Inc. All rights reserved.
BesuretoreadFactorsofKeyboardMapUsage.
TheavailableactionstowhichyoucanmapkeysorkeycombinationsareprovidedintheSpreadActions('SpreadActionsClass'intheon-linedocumentation)class.
ThedefaultmapscreatethedefaultnavigationandactionkeyslistedinDefaultKeyboardMaps.Thesemapsareforthedefaultoperationmode,Normal.Othermapsareprovidedforotheroperationmodes.Besuretosetthemapfortheoperationmodeinwhichyourcomponentisworkingwhencustomizinginputmaps.Formoreinformationaboutdefaultvaluesofthevariousmodes,refertoDefaultKeyboardMaps.Inputmapsworkdifferentlydependingonthecurrentfocus.
Formoredetaileddescriptionsofinputmaps,refertotheInputMap('InputMapClass'intheon-linedocumentation)class.
ThePropertieswindowdoesnothaveoptionstocustomizeinputmaps.
UsingCode
1. CreateanewInputMap('InputMapClass'intheon-linedocumentation)objectforwhichtomapkeysandactions.
2. SetanexistinginputmapequaltotheInputMap('InputMapClass'intheon-linedocumentation)objectyoucreated.
3. UsetheInputMap('InputMapClass'intheon-linedocumentation)classPutmethodtomapspecifickeystospecificactions.
Example
ThisexamplecodesetstheinputmapforoperationmodeNormalforboththeobjectwithfocusanditsancestor.ThisexamplesetstheEnterkeytoalwaysmovetothenextrow.
C#// Create an InputMap object.FarPoint.Win.Spread.InputMap inputmap1;// Assign the InputMap object to the existing map.inputmap1 = fpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused);// Map the Enter key.inputmap1.Put(new FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow);// Create another InputMap object.FarPoint.Win.Spread.InputMap inputmap2;// Assign this InputMap object to the existing map.inputmap2 = fpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused);// Map the Enter key.inputmap2.Put(new FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow);
VB' Create an InputMap object.Dim inputmap1 As New FarPoint.Win.Spread.InputMap()' Assign the InputMap object to the existing map.inputmap1 = FpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused)' Map the Enter key.inputmap1.Put(New FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow)
Spread Windows Forms Developer’s Guide 516
Copyright © GrapeCity, Inc. All rights reserved.
' Create another InputMap object.Dim inputmap2 As New FarPoint.Win.Spread.InputMap()' Assign this InputMap object to the existing map.inputmap2 = FpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused)' Map the Enter key.inputmap2.Put(New FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow)
UsingtheSpreadDesigner
1. IntheSettingsmenu,clicktheInputMapiconundertheOtherSettingssection.
2. Selecttheinputmap,key,andaction.
3. Addthenewkeyandaction.
4. SelectOK.
5. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Changing an Input Map for a Child View
Normally,whenyouchangeaninputmapdefinition,itappliesonlytoinputsintheactivesheet.Forahierarchicaldisplay,thisonlyappliestotheparentsheetandnottoanyexpandedchildsheetsofthehierarchy.Spreadtreatstheparentandeachchildasdifferentworkbooks.Ifyouwanttochangeinputmapsforchildpartsofahierarchy,youneedtoimplementtheChildWorkbookCreated('ChildWorkbookCreatedEvent'intheon-linedocumentation)eventwhichoccurswhenthechildworkbooksarecreated.Thenyoucanchangetheinputmapsforthosechildworkbooks.
UsingCode
1. CreateanInputMap('InputMapClass'intheon-linedocumentation)object.2. UsetheGetInputMap('GetInputMapMethod'intheon-linedocumentation)method.3. UsethePut('PutMethod'intheon-linedocumentation)method.4. Createadataset.
Example
Thisexampleshowshowtochangeaninputmapforaparent,thenexpandahierarchicaldisplayandchangetheinput
Spread Windows Forms Developer’s Guide 517
Copyright © GrapeCity, Inc. All rights reserved.
mapforachildofthathierarchy.
C# private void Form1_Load(object sender, System.EventArgs e) { // Change input maps for Enter key in parent hierarchies. FarPoint.Win.Spread.InputMap im = new FarPoint.Win.Spread.InputMap(); im = fpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused); im.Put(new FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow); im = fpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused);im.Put(new FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow); DataSet ds = new DataSet(); DataTable fpParent = new DataTable(); DataTable fpChild1 = new DataTable(); fpParent = ds.Tables.Add("SAMPLE"); fpParent.Columns.AddRange(new DataColumn[] {new DataColumn("Column1", Type.GetType("System.String")), new DataColumn("Column2", Type.GetType("System.Int32"))}); fpParent.Rows.Add(new object[] {"Parent1", 0}); fpParent.Rows.Add(new object[] {"Parent2", 1}); fpChild1 = ds.Tables.Add("Child1"); fpChild1.Columns.AddRange(new DataColumn[] {new DataColumn("Column1", Type.GetType("System.String")), new DataColumn("Column2", Type.GetType("System.Int32"))}); fpChild1.Rows.Add(new object[] {"Child1-1", 0}); fpChild1.Rows.Add(new object[] {"Child1-2", 0}); fpChild1.Rows.Add(new object[] {"Child1-3", 0}); fpChild1.Rows.Add(new object[] {"Child2-1", 1}); fpChild1.Rows.Add(new object[] {"Child2-2", 1}); fpChild1.Rows.Add(new object[] {"Child2-3", 1}); ds.Relations.Add("Relation1", fpParent.Columns["Column2"], fpChild1.Columns["Column2"]); fpSpread1.ActiveSheet.DataSource = ds; // Expand child hierarchies. fpSpread1.ActiveSheet.ExpandRow(0, true); fpSpread1.ActiveSheet.ExpandRow(1, true); } private void fpSpread1_ChildWorkbookCreated(object sender, FarPoint.Win.Spread.ChildWorkbookCreatedEventArgs e) { // Change its input map for Enter key in child hierarchies (e.Workbook: the target is child SpreadView). FarPoint.Win.Spread.InputMap im = new FarPoint.Win.Spread.InputMap(); im = e.Workbook.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused); im.Put(new FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow); im = e.Workbook.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused); im.Put(new FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow);
Spread Windows Forms Developer’s Guide 518
Copyright © GrapeCity, Inc. All rights reserved.
}
VB Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Change input maps for Enter key in parent hierarchies. Dim im As New FarPoint.Win.Spread.InputMap im = FpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused) im.Put(New FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow) im = FpSpread1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused) im.Put(New FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow) Dim ds As New DataSet Dim fpParent As DataTable Dim fpChild1 As DataTable fpParent = ds.Tables.Add("SAMPLE") fpParent.Columns.AddRange(New DataColumn() {New DataColumn("Column1", Type.GetType("System.String")), New DataColumn("Column2", Type.GetType("System.Int32"))}) fpParent.Rows.Add(New Object() {"Parent1", 0}) fpParent.Rows.Add(New Object() {"Parent2", 1}) fpChild1 = ds.Tables.Add("Child1") fpChild1.Columns.AddRange(New DataColumn() {New DataColumn("Column1", Type.GetType("System.String")), New DataColumn("Column2", Type.GetType("System.Int32"))}) fpChild1.Rows.Add(New Object() {"Child1-1", 0}) fpChild1.Rows.Add(New Object() {"Child1-2", 0}) fpChild1.Rows.Add(New Object() {"Child1-3", 0}) fpChild1.Rows.Add(New Object() {"Child2-1", 1}) fpChild1.Rows.Add(New Object() {"Child2-2", 1}) fpChild1.Rows.Add(New Object() {"Child2-3", 1}) ds.Relations.Add("Relation1", fpParent.Columns("Column2"), fpChild1.Columns("Column2"))FpSpread1.ActiveSheet.DataSource = ds ' Expand child hierarchies. FpSpread1.ActiveSheet.ExpandRow(0, True) FpSpread1.ActiveSheet.ExpandRow(1, True) End Sub
Private Sub FpSpread1_ChildWorkbookCreated(ByVal sender As Object, ByVal e As FarPoint.Win.Spread.ChildWorkbookCreatedEventArgs) Handles FpSpread1.ChildWorkbookCreated ' Change its input map for Enter key in child hierarchies (e.Workbook: the target is child SpreadView). Dim im As New FarPoint.Win.Spread.InputMap im = e.Workbook.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused) im.Put(New FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextRow) im = e.Workbook.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused) im.Put(New FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None),
Spread Windows Forms Developer’s Guide 519
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Spread.SpreadActions.MoveToNextRow) End Sub
Using the Excel Compatibility Input Maps
YoucanspecifywhethertousethedefaultSpreadinputmapsortheExcelcompatibilityinputmaps.Youcanalsospecifytheinputmapmodeandtheoperationmode.Someactionsmaynotapplytocertainmodessuchasstartingcelleditingwithread-onlymode.
UsetheLoadXmlInputMapFile('LoadXmlInputMapFileMethod'intheon-linedocumentation)methodtoloadtheExcelcompatibilityfileorotherinputmapfile.SpreadinstallsadefaultExcelcompatibilityfiletotheproductbinfolder.
UsingCode
SettheoptionsintheLoadXmlInputMapFile('LoadXmlInputMapFileMethod'intheon-linedocumentation)method.
Example
ThisexamplespecifiestheExcelcompatibilityoption.
C#fpSpread1.LoadXmlInputMapFile("ExcelCompatibility.imp");//fpSpread1.LoadXmlInputMapFile("ExcelCompatibility.imp",FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused,FarPoint.Win.Spread.OperationMode.Normal);
VBFpSpread1.LoadXmlInputMapFile("ExcelCompatibility.imp")'FpSpread1.LoadXmlInputMapFile("ExcelCompatibility.imp",FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused,FarPoint.Win.Spread.OperationMode.Normal)
UsingtheSpreadDesigner
1. SelecttheSettingsmenuandthenselecttheInputMapiconlocatedundertheOtherSettingssection.2. ClicktheLoadInputMapsbuttontoloadtheExcelcompatibilityfile.3. SelectOK.4. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Saving and Loading Map Files
YoucanloadorsavetheinputmapstoanXMLfile.UsetheSaveXmlInputMapFile('SaveXmlInputMapFileMethod'intheon-linedocumentation)methodtosavetoafileandtheLoadXmlInputMapFile('LoadXmlInputMapFileMethod'intheon-linedocumentation)toloadfromaninputmapfile.
SpreadinstallsadefaultExcelcompatibilityXMLfiletotheinputmapfolder.
UsingCode
1. Createaninputmap.
Spread Windows Forms Developer’s Guide 520
Copyright © GrapeCity, Inc. All rights reserved.
2. Savetheinputmaptoafile.
Example
ThisexamplesavesaninputmaptoanXMLfile.
C#FarPoint.Win.Spread.SpreadView sv = fpSpread1.GetRootWorkbook();FarPoint.Win.Spread.InputMap im = new FarPoint.Win.Spread.InputMap();im.Put(new FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None),FarPoint.Win.Spread.SpreadActions.MoveToNextRow);sv.SetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused, im);fpSpread1.SaveXmlInputMapFile("file.xml",FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused,FarPoint.Win.Spread.OperationMode.Normal);
VBDim sv As FarPoint.Win.Spread.SpreadView = FpSpread1.GetRootWorkbookDim im As New FarPoint.Win.Spread.InputMap()im.Put(New FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None),FarPoint.Win.Spread.SpreadActions.MoveToNextRow)sv.SetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused, im)FpSpread1.SaveXmlInputMapFile("file.xml",FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused,FarPoint.Win.Spread.OperationMode.Normal)
UsingtheSpreadDesigner
1. SelecttheSettingsmenuandthenselecttheInputMapiconlocatedundertheOtherSettingssection.2. FromtheSelectInputMapsection,selectthemodeoptions.3. Specifytheshortcutkeyandaction.4. ClickAddtoaddthenewinputmap.5. UsetheSavebuttontosavetheinputmaptoafile.UsetheLoadInputMapsbuttontoloadaninputmapfileinstead.
6. SelectOKtoapplytheinputmap.7. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Spread Windows Forms Developer’s Guide 521
Copyright © GrapeCity, Inc. All rights reserved.
Managing Events from User Actions
ThistopicsummarizeswhicheventsareraisedforeachuseractionontheSpreadcomponent.Whileitisnotacomprehensivelistofeveryactionthattheusercouldpossiblyperform,itdetailstheeventsformostofthecommonactionsperformedbytheuser.
Thetypesofuseractionsareorganizedasfollows:
ClickingActionsSelectingActionsEnteringDataActionsSheet-LevelActionsInteractivityActionsShapeActionsPrintActions
Thelistsprovidedinthesesectionsareanattempttoillustratethesequenceofeventsthatareraisedfortypicalactions.Sincesomeactionsoccurallthetimeorrepeatedlyforanyoftheseactions,wehaveleftoffsomeoftheseactionsfromthelists.Forexample,theselistsdonotincludeMouseMove,MouseHover,MouseEnter,MouseLeave,Invalidated,andCursorChangedevents.
Ingeneral,ifyouarelookingforawaytointercepteachchangethatoccursinacell,theEditChangeeventisraisedforeachkeystroketheusermakesastheyaretypingdataintoacell.
Clicking Actions
Clicking,double-clicking,andright-clickingactionsinSpreadresultintheseevents:
UserAction ListofEventsClickonageneralcell MouseDown
EnterGotFocusCellClick('CellClickEvent'intheon-linedocumentation)LeaveCell('LeaveCellEvent'intheon-linedocumentation)EnterCell('EnterCellEvent'intheon-linedocumentation)PaintMouseUpMouseCaptureChangedSelectionChanged('SelectionChangedEvent'intheon-linedocumentation)Paint
Clickonacomboboxcellandselectanitem
ComboDropDown('ComboDropDownEvent'intheon-linedocumentation)ComboSelChange('ComboSelChangeEvent'intheon-linedocumentation)EditChange('EditChangeEvent'intheon-linedocumentation)ComboCloseUp('ComboCloseUpEvent'intheon-linedocumentation)Paint
Clickonamultipleoptioncell MouseDown
Spread Windows Forms Developer’s Guide 522
Copyright © GrapeCity, Inc. All rights reserved.
andselectanoption CellClick('CellClickEvent'intheon-linedocumentation)LeaveCell('LeaveCellEvent'intheon-linedocumentation)EnterCell('EnterCellEvent'intheon-linedocumentation)EditModeStarting('EditModeStartingEvent'intheon-linedocumentation)MouseCaptureChangedControlAddedEditModeOn('EditModeOnEvent'intheon-linedocumentation)LostFocusPaintButtonClicked('ButtonClickedEvent'intheon-linedocumentation)
Double-clickageneralcell(gointoeditmode)
MouseDownCellClick('CellClickEvent'intheon-linedocumentation)LeaveCell('LeaveCellEvent'intheon-linedocumentation)EnterCell('EnterCellEvent'intheon-linedocumentation)PaintMouseUpMouseCaptureChangedSelectionChanged('SelectionChangedEvent'intheon-linedocumentation)PaintMouseDownCellDoubleClick('CellDoubleClickEvent'intheon-linedocumentation)EditModeStarting('EditModeStartingEvent'intheon-linedocumentation)MouseCaptureChangedLayoutControlAddedEditModeOn('EditModeOnEvent'intheon-linedocumentation)LostFocusPaint
Expandingahierarchy(thefirsttime)
MouseDownCellClick('CellClickEvent'intheon-linedocumentation)Expand('ExpandEvent'intheon-linedocumentation)LayoutControlAddedLayoutDataColumnConfigure('DataColumnConfigureEvent'intheon-linedocumentation)...DataColumnConfigure('DataColumnConfigureEvent'intheon-linedocumentation)(repeatforeachcolumninexpandedrow)LayoutControlAdded
Spread Windows Forms Developer’s Guide 523
Copyright © GrapeCity, Inc. All rights reserved.
Layout...Layout(repeatforeachcolumninexpandedrow)ControlAddedLayout...Layout(repeatforeachexpandedrow)ChildWorkbookCreated('ChildWorkbookCreatedEvent'intheon-linedocumentation)ChildViewCreated('ChildViewCreatedEvent'intheon-linedocumentation)LayoutControlRemovedLayoutControlRemovedLayoutControlAddedLayout...Layout(repeatforeachexpandedcolumn)ControlAddedLayoutPaintMouseUpMouseCaptureChangedPaint
Expandingahierarchy(subsequenttimes)
MouseDownCellClick('CellClickEvent'intheon-linedocumentation)Expand('ExpandEvent'intheon-linedocumentation)LayoutControlAddedLayout...Layout(repeated)ControlAddedLayoutPaintMouseUpMouseCaptureChangedPaint
Collapsingahierarchy(thefirsttimeorsubsequenttimes)
MouseDownCellClick('CellClickEvent'intheon-linedocumentation)Expand('ExpandEvent'intheon-linedocumentation)LayoutControlRemovedLayoutControlRemovedPaintMouseUpMouseUp
Spread Windows Forms Developer’s Guide 524
Copyright © GrapeCity, Inc. All rights reserved.
Paint
Selecting Actions
ActionssuchasselectingcellsandworkingwithselectionsinSpreadresultintheseevents:
UserAction ListofEventsSelectacell-clickageneral(default)cell MouseDown
EnterGotFocusCellClick('CellClickEvent'intheon-linedocumentation)MouseUpMouseCaptureChangedSelectionChanged('SelectionChangedEvent'intheon-linedocumentation)Paint
Selectrangeofcells-clickageneral(default)cellanddragtoanothercell
MouseDownCellClick('CellClickEvent'intheon-linedocumentation)LeaveCell('LeaveCellEvent'intheon-linedocumentation)EnterCell('EnterCellEvent'intheon-linedocumentation)PaintSelectionChanging('SelectionChangingEvent'intheon-linedocumentation)Paint...(repeatingPainteverytimeyoudragovertoacellinanotherroworcolumn)MouseUpMouseCaptureChangedSelectionChanged('SelectionChangedEvent'intheon-linedocumentation)Paint
Selectarow(orcolumn)-clickonheadercell MouseDownEnterGotFocusCellClick('CellClickEvent'intheon-linedocumentation)LeaveCell('LeaveCellEvent'intheon-linedocumentation)EnterCell('EnterCellEvent'intheon-linedocumentation)MouseUpMouseCaptureChangedSelectionChanged('SelectionChangedEvent'in
Spread Windows Forms Developer’s Guide 525
Copyright © GrapeCity, Inc. All rights reserved.
theon-linedocumentation)Paint
Entering Data Actions
ActionsinvolvedwithenteringdatainSpreadresultintheseevents.Thesearejustafew.Youcanalsoseewhateventsoccurwhenaformulaisentered.Herearetheeventsforenteringavalue:
UserAction ListofEventsEnteravalueinacell
(seeeventsforclickinacell)EditChange('EditChangeEvent'intheon-linedocumentation)(repeatEditChangeforeachkeypressed)MouseDownEditModeOff('EditModeOffEvent'intheon-linedocumentation)LayoutControlRemovedChange('ChangeEvent'intheon-linedocumentation)GotFocusCellClick('CellClickEvent'intheon-linedocumentation)LeaveCell('LeaveCellEvent'intheon-linedocumentation)EnterCell('EnterCellEvent'intheon-linedocumentation)PaintMouseUpMouseCaptureChangedSelectionChanged('SelectionChangedEvent'intheon-linedocumentation)PaintLostFocusLeaveValidatingValidated
Sheet-Level Actions
Sheet-levelactionsinSpreadresultintheseevents:
Action ListofEventsClickontabofnewsheet MouseDown
EnterGotFocusSheetTabClick('SheetTabClickEvent'intheon-linedocumentation)ActiveSheetChanging('ActiveSheetChangingEvent'intheon-linedocumentation)ActiveSheetChanged('ActiveSheetChangedEvent'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 526
Copyright © GrapeCity, Inc. All rights reserved.
PaintMouseUpMouseCaptureChangedPaint
Clickonthetaboftheactivesheet
Paint
Removeasheet Paint
Interactivity Actions
ThistableliststheeventsforthevariousactionsinvolvedwithuserinteractivityinSpread.Youcanalsoseewhateventsoccurforsorting,filtering,grouping,andsearching.Orcreatinganewviewportormovingascrollbarbyclickingthescrollbarbutton.
Action ListofEventsResizeacolumn-dragthecolumnresizecursor
MouseDownEnterGotFocusMouseUpMouseCaptureChangedColumnWidthChanged('ColumnWidthChangedEvent'intheon-linedocumentation)Paint
Shape Actions
ThistableliststheeventsforthevariousshapeactionsinSpread.Youcanalsoseewhateventsoccurwhenashapeisdeleted.
Action ListofEventsMoveShape MouseDown
ShapeActivated('ShapeActivatedEvent'intheon-linedocumentation)Paint...Paint(repeatedforeachcellmovedthrough)MouseUpMouseCaptureChanged
RotateShape MouseDownPaint...Paint(repeatedforeachcellmovedthrough)MouseUpMouseCaptureChanged
Print Actions
Spread Windows Forms Developer’s Guide 527
Copyright © GrapeCity, Inc. All rights reserved.
ThistableliststheeventsforthevariousprintingactionsinSpread:
Action ListofEventsPrintPreview
PrintMessageBox('PrintMessageBoxEvent'intheon-linedocumentation)PrintPreviewShowing('PrintPreviewShowingEvent'intheon-linedocumentation)LostFocusPrintBackground('PrintBackgroundEvent'intheon-linedocumentation)PrintAbort('PrintAbortEvent'intheon-linedocumentation)PrintMessageBox('PrintMessageBoxEvent'intheon-linedocumentation)
Printasheet PrintMessageBox('PrintMessageBoxEvent'intheon-linedocumentation)PrintMessageBox('PrintMessageBoxEvent'intheon-linedocumentation)PrintBackground('PrintBackgroundEvent'intheon-linedocumentation)PrintAbort('PrintAbortEvent'intheon-linedocumentation)PrintMessageBox('PrintMessageBoxEvent'intheon-linedocumentation)GotFocusPaint
Spread Windows Forms Developer’s Guide 528
Copyright © GrapeCity, Inc. All rights reserved.
Managing File Operations
YoucansavedatafromSpreadintoseveraldifferentfiletypesandopendatafilesfromseveraldifferentfiletypesintoSpread.Atdesigntime,youcanusetheSpreadDesignertosavetheSpreadtoanyofvariousfiletypesoropenpreviouslysavedfiles.Withcode,youcansavethewholecomponent,aparticularsheet,ordatafromaparticularrangeofcellstoseveraldifferentfiletypesorstreams.Similarly,youcanallowyouruserstohandlefileoperationsforarangeoffiletypes.
Theproceduresformanagingfileoperationsinclude:
SavingDatatoaFileOpeningExistingFilesUsingSerializationSavingandLoadingaSkinStoringExcelSummaryandView(on-linedocumentation)
ForinformationaboutsavingandopeningfilesinSpreadDesigner,refertoSavingandOpeningDesignFiles(on-linedocumentation)intheSpreadDesignerGuide.
Saving Data to a File
Youcansavethedata,andforsometypesoffilesthedataandformatting,inthecomponenttoafileorstream.SpreadprovidesmethodsforsavingfromaSpreadfiletoseveralfiletypes.Consultthefollowingtopicsforinstructionsandmoreinformationregardingsavingtoafile.
SavingtoaSpreadXMLFileSavingtoanExcelFileSavingtoaTextFileSavingtoanHTMLTableSavingSpreadsheetDatatoSimpleXML
Saving to a Spread XML File
YoucansavethedataorthedataandformattinginaSpreadcomponenttoaSpreadXMLfileortoastream.AllsheetsinthecomponentaresavedtothefileorstreamifyouusetheSave('SaveMethod'intheon-linedocumentation)methodintheFpSpreadclass.Ifyouchoosetosavetheformatting,thesaveddataincludesformattingcharacters,suchascurrencysymbols,andotherinformationsuchascelltypes.
Formoredetailsonthemethodsused,refertotheSave('SaveMethod'intheon-linedocumentation)methodsintheFpSpread('FpSpreadClass'intheon-linedocumentation)classortheSaveXml('SaveXmlMethod'intheon-linedocumentation)methodsintheSheetView('SheetViewClass'intheon-linedocumentation)class.
ForinstructionsforopeningSpread-compatibleXMLfiles,seeOpeningaSpreadXMLFile.
UsingCode
UsetheSave('SaveMethod'intheon-linedocumentation)methodoftheFpSpread('FpSpreadClass'intheon-linedocumentation)componenttospecifythepathandfilenameoftheSpreadXMLfileortheStreamobject,andwhethertosavedataonly.
Example
ThisexamplecodesavesthedataandformattinginaSpreadcomponenttoaSpreadXMLfile.
Spread Windows Forms Developer’s Guide 529
Copyright © GrapeCity, Inc. All rights reserved.
C#// Save the data and formatting to an XML file.fpSpread1.Save("C:\\SpWinFile1.xml", false);
VB' Save the data and formatting to an XML file.FpSpread1.Save("C:\SpWinFile1.xml", False)
UsingtheSpreadDesigner
1. FromtheFilemenu,chooseSave.TheSaveAsdialogappears.
2. ChangetheSaveastypeboxtoXMLfiles(*.xml).3. Specifythepathandfilenametowhichtosavethefile,andthenclickSave.
Ifthefileissavedsuccessfully,amessageappearsstatingthefilehasbeensaved.
4. ClickOKtoclosetheSpreadDesigner.
Saving to an Excel File
YoucansavedatatoanExcel-formattedfile(BIFF8format)ortheExcel2007XMLformat(xlsx)usingtheUseOOXMLFormatoptionoftheExcelSaveFlags('ExcelSaveFlagsEnumeration'intheon-linedocumentation)enumeration.BydefaultwhenyousavetoExcel,whateverisstoredinthedatamodeloftheSpreadiswrittenouttoafileorstreaminBIFF8format.
IfyouputanumberordateinanExcelcellandthewidthofthecolumnisnotlargeenoughtodisplaythedata,thenExcelshowsthecellfilledwith###.MakesurethewidthofthecolumnissetwideenoughtodisplaythedataintheexportedExcel-formattedfile.
Formoredetailsonthemethodsused,refertoSaveExcel('SaveExcelMethod'intheon-linedocumentation)methodsoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class.TherearemanydifferentSaveExcel('SaveExcelMethod'intheon-linedocumentation)methods.SomeofthemethodshaveasaveFlagsoption.Thisallowsyoutospecifyheadersandotheroptions.Headersareexportedasfrozencolumnsandrows.
TheDocumentcachingoptionintheExcelOpenFlags('ExcelOpenFlagsEnumeration'intheon-linedocumentation)orExcelSaveFlags('ExcelSaveFlagsEnumeration'intheon-linedocumentation)enumerationallowsuserstoopen,edit,andsavewithoutthelossofadvanceddocumentcontentandformatting.Thecontentcanbelosslessonlyiftheopeningfileformatissimilartothesavingfileformat.Iftheadvanceddocumentcontentusesfilesbesidesthexls(x)file,thentheadditionalfilesneedtobeinthesamefolderwiththexls(x)file.Advancedcontentcouldbemacros,ActiveXcontrols,dataconnections,andsoon.
FormoreinformationabouthowthedataissavedtoanExcel-formattedfile,seetheImportandExportReference(on-linedocumentation).
UsingCode
UseoneoftheSaveExcel('SaveExcelMethod'intheon-linedocumentation)methodsoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class,providingthepathandfilenameforthefiletosave,andanyadditionalparametersdependingontheparticularmethod.
Example
ThisexamplecodesavesthedatainaSpreadcomponenttoanExcel-formattedfileandspecifiesthatbothrowand
Spread Windows Forms Developer’s Guide 530
Copyright © GrapeCity, Inc. All rights reserved.
columnheadersareincludedintheoutput.
C#// Save the data to an Excel-formatted file, including headers.fpSpread1.SaveExcel("C:\\excelfile.xls", FarPoint.Win.Spread.Model.IncludeHeaders.BothCustomOnly);
VB' Save the data to an Excel-formatted file, including headers.FpSpread1.SaveExcel("C:\excelfile.xls", FarPoint.Win.Spread.Model.IncludeHeaders.BothCustomOnly)
UsingtheSpreadDesigner
1. FromtheFilemenu,chooseSave.TheSaveAsdialogappears.
2. ChangetheSaveastypeboxtoExcelfiles(*.xls).3. Specifythepathandfilenametowhichtosavethefile,andthenclickSave.
Ifthefileissavedsuccessfully,amessageappearsstatingthefilehasbeensaved.
4. ClickOKtoclosetheSpreadDesigner.
Saving to a Text File
Youcansavethedataorthedataandformattinginasheettoatextfile,usingeitherdefaulttabdelimitersorcustomdelimiters(suchasacommaforacsvfile).Inaddition,youcanspecifywhetherheadersaresavedwiththedata.
Savingtoatextfileisdoneforindividualsheets.Ifyouwanttosaveallthesheetsinthecomponent,youmustsaveeachsheettoatextfile.
Tab-delimitedfilessavedfromthecomponentcontaindataseparatedbytabsandcarriagereturns.Tab-delimitedfilescanbeopened,modified,andsavedusinganystandardtexteditor.Delimitedfilescontaindataseparatedbyuser-defineddelimiters,suchascommas,quotationmarks,orotherdelimiters.
Youcansavetheentiresheetoraportionofthesheetdatafromthecomponenttotab-delimitedanddelimitedfiles.
Ifyouupgradedfromaversionpriortoversion5,thenyoumaywishtoreplaceanyobsoleteparametersintheSaveTextFile('SaveTextFileMethod'intheon-linedocumentation)andSaveTextFileRange('SaveTextFileRangeMethod'intheon-linedocumentation)methods.
Formoredetailsonthemethodsandcurrentparameters,refertotheSaveTextFile('SaveTextFileMethod'intheon-linedocumentation)andSaveTextFileRange('SaveTextFileRangeMethod'intheon-linedocumentation)methodsoftheSheetView('SheetViewClass'intheon-linedocumentation)class.
Forinstructionsforopeningtextfiles,seeOpeningaCustomTextFile.
UsingCode
1. Tosavetheentiresheet,useoneoftheSheetView('SheetViewClass'intheon-linedocumentation)classSaveTextFile('SaveTextFileMethod'intheon-linedocumentation)methods,specifyingthepathandfilenameorstream,whetherdataordataandformattingissaved,whetherheadersaresaved,andthecustomdelimiters,dependingonthemethodyouchoose.
2. Tosaveaportionofasheet,useoneoftheSheetView('SheetViewClass'intheon-linedocumentation)classSaveTextFileRange('SaveTextFileRangeMethod'intheon-linedocumentation)methods,specifyingthestartingrowandcolumn,thenumberofrowsandcolumnstosave,thepathandfilenameorstream,whetherdataordataandformattingissaved,whetherheadersaresaved,andthecustomdelimiters,
Spread Windows Forms Developer’s Guide 531
Copyright © GrapeCity, Inc. All rights reserved.
dependingonthemethodyouchoose.
Example
Thisexamplecodesavesarangeofdataandformattingtoatextfile,includingheadersandusingcustomdelimiters.
C#// Save a range of data and formatting to a text file.fpSpread1.Sheets[0].SaveTextFileRange(1, 1, 1, 2, "C:\\filerange.txt", FarPoint.Win.Spread.TextFileFlags.Unformatted, FarPoint.Win.Spread.Model.IncludeHeaders.BothCustomOnly, "#", "%", "^");
VB' Save a range of data and formatting to a text file.FpSpread1.Sheets(0).SaveTextFileRange(1, 1, 1, 2, "C:\filerange.txt", FarPoint.Win.Spread.TextFileFlags.Unformatted, FarPoint.Win.Spread.Model.IncludeHeaders.BothCustomOnly, "#", "%", "^")
Saving to an HTML Table
YoucansaveanindividualsheetorarangeofcellsinasheettoanHTMLtableinafileorstreamifyouneedtodisplaythesheetinaWebbrowser.Thisdoesnotsavetheentirespreadsheet,onlyanindividualsheet.
TheHTMLexportsavesasmuchoftheformattinginformationorpresentation-relatedsettingsaspossible,dependingonwhetherthatinformationcanbetranslatedtoanHTMLelementorattribute.TheheadercellsarenotsavedouttoXML;onlythedataareacells.Ifyouhavegroupingturnedon,onlythedataareaofthesheet(notthegroupingbaratthetop,andnotthegroupheadingrows)issaved.
TosavethesheettoanHTMLtable,usetheSaveHtml('SaveHtmlMethod'intheon-linedocumentation)methodsoftheSheetView('SheetViewClass'intheon-linedocumentation)class.
TheHTMLexportmethodswillnotworkwithclientprofiling.
TosavearangeofcellsonasheettoanHTMLtable,usetheSaveHtmlRange('SaveHtmlRangeMethod'intheon-linedocumentation)methodsoftheSheetView('SheetViewClass'intheon-linedocumentation)class.
Intheexamplebelow,noticethattheentirefileisinasingle<TABLE>elementandthateachofthecells,bothheadingsanddataarea,aretranslatedtotablecells.Headingcellsareoutputas<TH>elements(tableheadingcells)anddataareacellsareoutputas<TD>elements(tabledatacells).Alloftheformattinginformationispreservedandkeptasattributesinthetablecellattributes.Asetof<COLGROUP>elements(columngroups)definethewidthofthecolumnsinthetable.TheappearanceofthespreadsheetisreproducedascloselyaspossibleinHTMLinthisfairlysimpleorganization.
FordetailedspecificationsoftheHTMLelementsandtheirattributes,refertotheWorldWideWebConsortium(W3C)(http://www.w3.org)HTML4.01referencesite(http://www.w3.org/TR/html4).
UsingCode
UsetheSaveHtml('SaveHtmlMethod'intheon-linedocumentation)method.
Example
ThisexampleusestheSaveHtml('SaveHtmlMethod'intheon-linedocumentation)method.
C#fpSpread1.ActiveSheet.SaveHtml("C:\\testfiles\\FPSpread-SheetToHTML.html");
VBFpSpread1.ActiveSheet.SaveHtml("C:\testfiles\FPSpread-SheetToHTML.html")
Thisgivesthefollowingresult:
<table cellspacing="0" cellpadding="0"rules="all" border="1" style="border-width:1px;border-style:solid;width:548px;border-collapse:collapse;">
<COLGROUP>
<col width=49px>
<col width=150px>
<col width=300px> <col width=49px>
</COLGROUP>
<tr style="height:20px;">
<th style="background-color:#A9A9A9;"></th>
<th align="center" valign="middle" style="color:White;background-color:#A9A9A9;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">Artist</th>
<th align="center" valign="middle" style="color:White;background-color:#A9A9A9;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">Website</th>
<th align="center" valign="middle" style="color:White;background-color:#A9A9A9;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">id</th>
</tr>
<tr style="height:20px;"> <th align="center"valign="middle"
style="color:White;background-color:#A9A9A9;"></th>
<td align="left" valign="top" style="color:Gray;background-color:#F8F8FF;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">Aerosmith</td>
<td align="left" valign="top" style="color:Gray;background-color:#F8F8FF;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">http://www.aerosmith.com/detect.html</td>
<td align="right" valign="top" style="color:Gray;background-color:#F8F8FF;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">0</td>
</tr>
<tr style="height:20px;">
<th align="center" valign="middle" style="color:White;background-color:#A9A9A9;"></th>
<td align="left" valign="top" style="color:Gray;background-color:#DCDCDC;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">Foreigner</td>
<td align="left" valign="top" style="color:Gray;background-color:#DCDCDC;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">http://www.foreigneronline.com/</td>
<td align="right" valign="top" style="color:Gray;background-color:#DCDCDC;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">1</td>
</tr>
<tr style="height:20px;">
Spread Windows Forms Developer’s Guide 532
Copyright © GrapeCity, Inc. All rights reserved.
<th align="center" valign="middle" style="color:White;background-color:#A9A9A9;"></th>
<td align="left" valign="top" style="color:Gray;background-color:#F8F8FF;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">Jimi Hendrix</td>
<td align="left" valign="top" style="color:Gray;background-color:#F8F8FF;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">http://www.jimi-hendrix.com/</td>
<td align="right" valign="top" style="color:Gray;background-color:#F8F8FF;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">2</td>
</tr>
<tr style="height:20px;">
<th align="center" valign="middle" style="color:White;background-color:#A9A9A9;"></th>
<td align="left" valign="top" style="color:Gray;background-color:#DCDCDC;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">Pink Floyd</td>
<td align="left" valign="top" style="color:Gray;background-color:#DCDCDC;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">http://www.pinkfloyd.com</td>
<td align="right" valign="top" style="color:Gray;background-color:#DCDCDC;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">3</td>
</tr>
<tr style="height:20px;">
<th align="center" valign="middle" style="color:White;background-color:#A9A9A9;"></th>
<td align="left" valign="top" style="color:Gray;background-color:#F8F8FF;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">TheWho</td>
<td align="left" valign="top" style="color:Gray;background-color:#F8F8FF;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">http://www.thewho.net/</td>
<td align="right" valign="top" style="color:Gray;background-color:#F8F8FF;font-family:Arial;font-size:12pt;font-weight:normal;font-style:normal;text-decoration:none;">4</td>
</tr>
</table>
Saving Spreadsheet Data to Simple XML
YoucansavethedatafromasheettoanXMLfileorstreamifyouneedtoprocessthedatafurtherandwantthedatainastructuredformat.Thisdoesnotsavetheentirespreadsheetnordoesitsavetheformattinginformationorpresentation-relatedsettings.OnlythevaluesinthecellsaresavedtoXML.TheheadercellsarenotsavedouttoXML;onlythedataareacells.
TosavethedatatoXML,usetheSaveXml('SaveXmlMethod'intheon-linedocumentation)methodsoftheSheetViewclass.
Youcansavethedatatoonefile(orstream)andtheXMLschematoanotherfile(orstream).Anexampleoutputisshownbelow.Thetoplevel(orroot)elementisthesheet(SheetName)andwithinthesheetelementarerowelements(Row1,Row2,andsoon)andwithineachrowarethecolumnelements(Column1,Column2,andsoon)andwithineachcolumnelementisthedata.Thesheetelementusesthenameofthesheet.Therowsareallgenericrowsandarenotgivenuniquenames.Thecolumnsareeachgivenauniquenameandcolumnswithoutdataareignored.
TheSaveXml('SaveXmlMethod'intheon-linedocumentation)methodonlysavesthedataforanindividualsheet,notforanentirehierarchythatconsistsofseveralsheets.
Thismethodonlysavesthedata.Forcelltypedata,seeUnderstandingHowCellTypesDisplayandFormatData.
UsingCode
UsetheSaveXml('SaveXmlMethod'intheon-linedocumentation)methodtosavedatatoanXMLfile.
Example
Thisexamplesavesthedataforasheetnamed"EastCoastSales"toanXMLfileandtheschematoanotherfile.
C#fpSpread1.ActiveSheet.SaveXml("C:\\testfiles\\FPSpread-SheetToXML2.xml", "C:\\testfiles\\FPSpread-SchemaForXML2.xml");
VBFpSpread1.ActiveSheet.SaveXml("C:\testfiles\FPSpread-SheetToXML2.xml", "C:\testfiles\FPSpread-SchemaForXML2.xml")
Thisgivesthefollowingresult:
<EastCoastSales>
<Row>
<Column1>Aerosmith</Column1>
<Column2>http://www.aerosmith.com/detect.html</Column2>
<Column3>0</Column3>
</Row>
<Row>
<Column1>Foreigner</Column1>
<Column2>http://www.foreigneronline.com/</Column2>
<Column3>1</Column3>
</Row>
.
.
.
<Row>
<Column1>The Who</Column1>
<Column2>http://www.thewho.net/</Column2>
<Column3>4</Column3>
</Row>
</EastCoastSales>
Thecorrespondingschemawouldbesomethinglikethis:
Spread Windows Forms Developer’s Guide 533
Copyright © GrapeCity, Inc. All rights reserved.
<?xml version="1.0" encoding="utf-16"?><xs:schemaid="Sheet1" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema"xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:elementname="EastCoastSales" msdata:IsDataSet="true" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choiceminOccurs="0" maxOccurs="unbounded"> <xs:element name="Row"> <xs:complexType> <xs:sequence> <xs:elementname="Column1" type="xs:string" minOccurs="0" /> <xs:elementname="Column2" type="xs:string" minOccurs="0" /> <xs:elementname="Column3" type="xs:string" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element></xs:schema>
Opening Existing Files
SpreadcanopenXMLfilesorstreamobjectsthatwerecreatedbySpread,aswellastextandExcelfiles.TextfilesmustusedelimitersthatSpreadcanprocesstoplacedataintotheappropriatecells.Spreadprovidesmethodsforopeningseveralfiletypes.Consultthefollowingtopicsforinstructionsandmoreinformationregardingsavingtoafile.
OpeningaSpreadXMLFileOpeninganExcelFileOpeningaSpreadCOMFile.OpeningaCustomTextFile
IfyouopenorloadafileorStreamobjectthatcontainsmorerowsorcolumnsthanthesheetorsheetsintowhichyouareopeningthefileorstream,thecomponentaddsrowsorcolumnsasneededtothesheetorsheets.IfyouopenorloadafileorStreamobjectwithfewerrowsorcolumnsthanthesheetorsheetsintowhichyouareopeningthefileorstream,thecomponentopensthefileandloadsthedata,anddoesnotremovetheadditionalrowsorcolumnsinthesheetorsheets.
OpeningexistingfilesusingSpreadDesignerplacesthedatafromthefileintothedesignstringusedtocreatethecomponent.Longerdesignstringsnegativelyimpactresponsiveness,includingmakingpageloadsslowerandincreasingresponsetimetoediting.KeepthisinmindwhenusingSpreadDesignertoopenandloadfiles.
Opening a Spread XML File
SpreadcanopendataordataandformattingfromaSpread-compatibleXMLfileorastreamintotheSpreadcomponent.
FormoredetailsonopeningaSpreadXMLfile,refertotheOpen('OpenMethod'intheon-linedocumentation)methodsoftheFpSpread('FpSpreadClass'intheon-linedocumentation)classortheOpen('OpenMethod'intheon-linedocumentation)methodsoftheSheetView('SheetViewClass'intheon-linedocumentation)class.
ForinstructionsforsavingSpreadXMLfiles,seeSavingtoaSpreadXMLFile.
UsingCode
UsetheFpSpread('FpSpreadClass'intheon-linedocumentation)classOpen('OpenMethod'intheon-linedocumentation)method,specifyingthepathandfilenameoftheSpreadXMLfiletoopenortheStreamobjecttoopen.
Example
ThisexamplecodeopensanexistingSpread-compatibleXMLfileinthecomponent.
C#// Open a Spread-compatible XML file.fpSpread1.Open("C:\\spreadfile.xml");
VB' Open a Spread-compatible XML file.
Spread Windows Forms Developer’s Guide 534
Copyright © GrapeCity, Inc. All rights reserved.
FpSpread1.Open("C:\spreadfile.xml")
UsingtheSpreadDesigner
1. FromtheFilemenu,selectOpen.2. Adialogappearswarningyouthatthisoverwritesyourexistingsettingsifyouopenafile.ClickYestocontinue
withthefileopen.TheOpendialogappears.
3. ChangetheFilesoftypeboxtoXMLfiles(*.xml).4. Specifythepathandfilenameofthefiletoopen,andthenclickOpen.
Ifthefileisopenedsuccessfully,amessageappearsstatingthefilehasbeenopened.
5. ClickOKtoclosetheSpreadDesigner.
Opening an Excel File
YoucanopenanexistingExcel-formattedfile(BIFF8formatorxlsx)inSpread.Youcanopentheentiremultiple-sheetfileintotheSpreadcomponentorspecifyaparticularsheet(eitherbynameornumber)andopenitintoaspecificsheet.
Spreadcanbeusedinbothboundandunboundmodes.WhenopeninganExcelfile,SpreadisbeingusedintheunboundmodeandthustheDataSourcepropertyreturnsnull(orNothinginVisualBasic).
UseoneoftheOpenExcel('OpenExcelMethod'intheon-linedocumentation)methodsoftheFpSpread('FpSpreadClass'intheon-linedocumentation)classtoopenallthesheetsintheExcelfile,providingthepathandfilenameforthefiletoopenandanyadditionalinformation.YoucanspecifyadditionalopenoptionswiththeExcelOpenFlags('ExcelOpenFlagsEnumeration'intheon-linedocumentation)enumeration.Thisenumerationallowsyoutodeterminehowfrozencolumnsandrowsareimported,ifdataonlyisimported,andotheroptions.ToopenaspecificsheetoftheExcelfile,useoneoftheOpenExcel('OpenExcelMethod'intheon-linedocumentation)methodsoftheSheetView('SheetViewClass'intheon-linedocumentation)class,specifyingthesheetbynameornumber.
TheDocumentcachingoptionintheExcelOpenFlagsorExcelSaveFlagsenumerationallowsuserstoopen,edit,andsavewithoutthelossofadvanceddocumentcontentandformatting.Thecontentcanbelosslessonlyiftheopeningfileformatissimilartothesavingfileformat.Iftheadvanceddocumentcontentusesfilesbesidesthexls(x)file,thentheadditionalfilesneedtobeinthesamefolderwiththexls(x)file.Advancedcontentcouldbemacros,ActiveXcontrols,dataconnections,andsoon.
NotethatthesheetindexreferringtosheetsintheExcelfileiszero-based,sothefirstsheetintheExcelfileis0,thesecondis1,andsoon.
IftheExcelfileisopeninanotherapplication(openinExcelforexample)whenyouaretryingtoopenitinSpread,nothingisimported,andtheSpreadopenswithoutanyimporteddata.
FormoreinformationabouthowthedataisimportedfromanExcel-formattedfile,seetheImportandExportReference(on-linedocumentation).
UsingCode
UseoneoftheOpenExcel('OpenExcelMethod'intheon-linedocumentation)methodsoftheFpSpread('FpSpreadClass'intheon-linedocumentation)classtoanExcelfile.ToopenaspecificsheetoftheExcelfile,useoneoftheOpenExcel('OpenExcelMethod'intheon-linedocumentation)methodsoftheSheetView('SheetViewClass'intheon-linedocumentation)class(usingtheSheetsorActiveSheetshortcut).
Example
ThisexamplecodeopensanentireExcel-formattedfileusingthemethodintheFpSpread('FpSpreadClass'intheon-linedocumentation)class,andloadsthedatafromthespecifiedExcelsheetintothespecifiedsheetoftheSpread
Spread Windows Forms Developer’s Guide 535
Copyright © GrapeCity, Inc. All rights reserved.
component.
C#// Open the fourth sheet of the Excel file.fpSpread1.ActiveSheet.OpenExcel("C:\\excelfile.xls", 3);
VB' Open the fourth sheet of the Excel file.FpSpread1.ActiveSheet.OpenExcel("C:\excelfile.xls", 3)
UsingtheSpreadDesigner
1. FromtheFilemenu,selectOpen.2. Adialogappearswarningyouthatthisoverwritesyourexistingsettingsifyouopenafile.ClickYestocontinue
withthefileopen.TheOpendialogappears.
3. ChangetheFilesoftypeboxtoExcelfiles(*.xls).Toopenacomma-delimitedfile,changetheFilesoftypeboxtoComma-delimitedfiles(*.csv).
4. Specifythepathandfilenameofthefiletoopen,andthenclickOpen.Ifthefileisopenedsuccessfully,amessageappearsstatingthefilehasbeenopened.
5. ClickOKtoclosetheSpreadDesigner.
Opening a Spread COM File
YoucanopenanexistingfilefromtheCOMversionofSpread(SpreadCOM7.0orlater).FordetailsonopeningaSpreadCOMfile,refertotheOpenSpreadFile('OpenSpreadFileMethod'intheon-linedocumentation)methodsoftheFpSpreadclass.
Sincethe.NETplatformiscompletelydifferentfromtheCOMenvironment,therearemanydifferencesbetweentheSpreadfilefortheproductsinthesetwoenvironments.FormoreinformationaboutimportingSpreadCOMfilesandunderstandingcompatibilitywithSpreadWindowsForms,refertotheVersionComparisonReference(on-linedocumentation).
UsingCode
UsetheOpenSpreadFile('OpenSpreadFileMethod'intheon-linedocumentation)methodoftheFpSpreadclass,providingthepathandfilenameforthefiletoopen,orusetheOpenSpreadFile('OpenSpreadFileMethod'intheon-linedocumentation)methodoftheSheetView('SheetViewClass'intheon-linedocumentation)class(intheActiveSheetorSheetsshortcutobject).
Example
ThisexamplecodeopensaSpreadCOM7fileintheactivesheet.
C#// Open an old Spread 7 file into the active sheet.fpSpread1.ActiveSheet.OpenSpreadFile("C:\\oldfile.ss7");
VB' Open an old Spread 7 file into the active sheet.FpSpread1.ActiveSheet.OpenSpreadFile("C:\oldfile.ss7")
Spread Windows Forms Developer’s Guide 536
Copyright © GrapeCity, Inc. All rights reserved.
UsingtheSpreadDesigner
1. FromtheFilemenu,selectOpen.2. Adialogappearswarningyouthatthisoverwritesyourexistingsettingsifyouopenafile.ClickYestocontinue
withthefileopen.TheOpendialogappears.
3. ChangetheFilesoftypeboxtoSpread7files(*.ss7or*.ss8).4. Specifythepathandfilenameofthefiletoopen,andthenclickOpen.
Ifthefileisopenedsuccessfully,amessageappearsstatingthefilehasbeenopened.
5. ClickOKtoclosetheSpreadDesigner.
Opening a Custom Text File
Youcanopenexistingtextfilesthataredelimited,eitherfilessavedfromSpreadordelimitedtextfilesfromothersources.Thedatafromthefileyouopenisplacedinthesheetforwhichyoucallthemethod.
Ifthefileusescustomdelimiters(suchascommasincsvfiles),youmustspecifythedelimiterssothecomponentcancorrectlyplacethedatawithinthesheet.Ifyourfileusesstandardtab-delimitedformat,youneednotuseamethodthatletsyouspecifydelimiters.
Ifyouupgradedfromaversionpriortoversion5,thenyoumaywishtoreplaceanyobsoleteparametersintheLoadTextFilemethods.
Formoredetailsandcurrentparameters,refertotheLoadTextFile('LoadTextFileMethod'intheon-linedocumentation)orLoadTextFileRange('LoadTextFileRangeMethod'intheon-linedocumentation)methodsintheSheetView('SheetViewClass'intheon-linedocumentation)class.
Forinstructionsforsavingtotextfiles,seeSavingtoaTextFile.
UsingCode
UseanyoftheLoadTextFile('LoadTextFileMethod'intheon-linedocumentation)methodsintheSheetView('SheetViewClass'intheon-linedocumentation)class(fortheActiveSheetorSheetsobject).
Example
Thisexampleopensatextfileandhandlestheheadersandspecifiesthedelimiters.
C#fpSpread1.ActiveSheet.LoadTextFile("C:\\textfile.txt", FarPoint.Win.Spread.TextFileFlags.Unformatted, FarPoint.Win.Spread.Model.IncludeHeaders.BothCustomOnly, "\n", ",", "");
VBFpSpread1.ActiveSheet.LoadTextFile("C:\textfile.txt", FarPoint.Win.Spread.TextFileFlags.Unformatted, FarPoint.Win.Spread.Model.IncludeHeaders.BothCustomOnly, Chr(10), ",", "")
UsingtheSpreadDesigner
1. FromtheFilemenu,selectOpen.
Spread Windows Forms Developer’s Guide 537
Copyright © GrapeCity, Inc. All rights reserved.
2. Adialogappearswarningyouthatthisoverwritesyourexistingsettingsifyouopenafile.ClickYestocontinuewiththefileopen.TheOpendialogappears.
3. ChangetheFilesoftypeboxtoCustomtextfiles(*.txt).Toopenacomma-delimitedfile,changetheFilesoftypeboxtoComma-delimitedfiles(*.csv).
4. Specifythepathandfilenameofthefiletoopen,andthenclickOpen.Ifthefileisopenedsuccessfully,amessageappearsstatingthefilehasbeenopened.
5. ClickOKtoclosetheSpreadDesigner.
Using Serialization
InSpread,youcanserializeobjectsinthespreadsheetortheentirespreadsheetcomponentusingseveralmethods.BesureyouunderstandthedifferencebetweensavingwiththemethodsinFarPoint.Win.Serializer('SerializerClass'intheon-linedocumentation)asopposedtotheonesinthemodelnamespaceFarPoint.Win.Spread.Model.SpreadSerializer('SpreadSerializerClass'intheon-linedocumentation).TheSpreadSerializer('SpreadSerializerClass'intheon-linedocumentation)isintendedforsavingandloadingentireSpreadcomponentobjectsortextfilesfromasheet,whiletheSerializer('SerializerClass'intheon-linedocumentation)containsmethodsforsavingandloadinganyserializableobjectusingourXMLserializationimplementation.Formoredetailsonserializinganddeserializing,refertothesetasks.
ImplementingaSerializerClassParsingFormulasinCustomXMLDeserialization
ThemethodtouseforsimplysavinganobjecttoafileisSaveObject('SaveObjectMethod'intheon-linedocumentation);themethodforloadingtheobjectbackfromthefileisLoadObject('LoadObjectMethod'intheon-linedocumentation).ThemethodsareoverloadedsoyoucansaveorloadtoastreamoruseaparticularXMLserializationinterface.FormanypurposestheoverloadforSaveObject('SaveObjectMethod'intheon-linedocumentation)withonlytheobject,filename,androotelementnamearguments,andtheoverloadforLoadObject('LoadObjectMethod'intheon-linedocumentation)withonlythetype,filename,andelementnameshouldwork.TheSaveObject('SaveObjectMethod'intheon-linedocumentation)methodcheckstoseeiftheobjectisintheFarPointSpreadDLLortheFarPointWinDLL,andifnot,thenitsavestheassemblynameintheXMLnodeattributesandusesthatnametoloadtheassemblyintheCreateObjectInstanceAndDeserialize('CreateObjectInstanceAndDeserializeMethod'intheon-linedocumentation)method.
Design-timeserializationiscomplicated,andSpreadusesseveralcustomCodeDomSerializerobjectstoserializeatdesigntime.ThoseserializersarecodedtoexpecttheFpSpreadandtheSheetViewtobefieldsintheobjectbeingserialized,andiftheobjectisinsteadreturnedbyapropertyaccessor,thecodeprobablyisnotgetgeneratedcorrectly.ForthisreasonexposingapropertyoftypeFpSpreadorSheetViewatdesigntimeisnotrecommended.
Implementing a Serializer Class
WhenusingtheSerializer('SerializerClass'intheon-linedocumentation)class,rememberthesetips:
YoumusthaveaparameterlessconstructordefinedinorderforSerializer.CreateObjectInstanceAndDeserialize('CreateObjectInstanceAndDeserializeMethod'intheon-linedocumentation)tocreateanewinstanceofyourclasstodeserialize.Itisagoodideatoinitializethefieldsintheclasswithsomedefaultordummyvalues,butitisnotnecessaryifyoualwayssaveeachfieldtotheXMLregardlessofwhetheritissettoitsdefault(whichisrequiredtomakeGetObjectXml('GetObjectXmlMethod'intheon-linedocumentation)andSetObjectXml('SetObjectXmlMethod'intheon-linedocumentation)workproperly).TheSerializerCanSerializeObject('CanSerializeObjectMethod'intheon-linedocumentation)methoddetermineswhetherthespecifiedobjectcanbeserializedwithSerializeObject.ThismethodcheckswhethertheobjectimplementsICanSerializeXml(inwhichcaseitreturnsthevalueoftheobject'sCanSerializeXmlproperty),orwhethertheobjectimplementsISerializeSupport,orisasimpletype,orif
Spread Windows Forms Developer’s Guide 538
Copyright © GrapeCity, Inc. All rights reserved.
thetype'sIsSerializablepropertyreturnstrue.Savingtheobjectusingelements(seethefirstsubclassexamplebelow)requiresmorecoding,butresultsinmorereadableXMLwhenthenumberofpropertiesbeingsavedishigh(asinthisexampleoftheLineBorderclassbelow).Savingtheobjectusingattributes(thesecondsubclassexamplebelow)requireslesscoding,andresultsinmorereadableXMLwhenthenumberofpropertiesbeingsavedislow(asinthisexampleoftheGradientLineBorderclassbelow),sothelattersubclassexampleisbetter.IfyouimplementISerializeSupport('ISerializeSupportInterface'intheon-linedocumentation)usingelements,thenyoushouldcallthebaseclassimplementationfirst(ifthereisone),thensaveandloadyourproperties.Youshouldalsoreturnafterreadingthelastendelementthatyouserialize,sothatsubclassescanalsouseelementstoserializetheirproperties.IfyouimplementISerializeSupport('ISerializeSupportInterface'intheon-linedocumentation)usingattributes,thenyoushouldreadyourattributesfirst,thencallthebaseclassimplementation(ifthereisone).Youcanusebothattributesandelementstoserializeyourobject;therearesomeSpreadobjects(mostlythemodels)whichdothis.Inthatcaseyoushoulddotheattributesfirst,thencallthebaseclass,thensaveandloadyourelements,returningfromDeserializeafteryoureachthelastendelement.
Theexamplesbelowshowsavingsimplethingslikeintegersandcolors,butsavingothertypesisnodifferent.TherearemethodsinSerializerforsavingandloadingColor,DateTime,DateTimeFormatInfo,Enumtypes,Font,Image,Int32array,NumberFormatInfo,PointFarray,Stringarray,andObject.Itisbest(thoughnotrequired)tousethemostspecificmethodavailable.Forexample,itwouldworktouseSerializeObjecttosaveasimpletypeoraColorvalue,butitislessefficientandmaynotresultinthesameXML.
Ingeneral,thereisareasoneachofthemethodswascreatedforitsspecifictype.DateTimeFormatInfoandNumberFormatInfomustbesavedusingtheirrespectivemethodsbecauseSerializeObjectwoulddefaulttousingbinaryserialization,whichdoesnotworkacrossversionsoftheframework(soaDateTimeFormatInfosavedusing.NET1.0doesnotloadusing.NET1.1or2.0).
Forsimpletypes(Int32,String,Boolean,etc.)itisbesttouseToString()toconvertthemtoastringforsaving(passingCultureInfo.InvariantCultureifpossible)andthenuseXmlConverttoconvertthestringsbackintovalues.
SaveObjectisintendedforsavingobjectswhichimplementISerializeSupport('ISerializeSupportInterface'intheon-linedocumentation),orforcertainspecifictypes(intrinsicdatatypesandDataSet),orforgenericobjectswhichareserializablebutdonotimplementISerializeSupport(suchobjectsgetsavedusingEncodeObject,whichusesaBinaryFormattertosavetheobjecttoaMemoryStreamandthenusesConverttoencodethebytesintoabase-64string).
DebugversusReleaseBuild
Togetfilessavedwithadebugbuildtoloadintoareleasebuildthatisstrongnamed,youmusteliminateorupdatetheassemblyattributeinthenodewheretheobjectissaved.SerializeObjectwillwriteanassemblyattributeiftheassemblyinwhichtheobject'stypeisdefinedisdifferentfromthecallingassemblyanddifferentfromtheexecutingassembly(FarPoint.Win.dll).
ThecallingassemblyisusuallyFarPoint.Win.Spread.dllbutispossiblytheuser'sassemblyiftheyaredefiningtheirownobjectswhichimplementISerializeSupportandsavingchildobjectsusingSerializeObject.Thetrickycaseis,unfortunately,likelythemostcommonone:ausercreatesacustomobjecttoplugintotheSpread'sobjectmodel(forexample,acustomdatamodel)andtheywanttosaveandloadtheSpreadusingthesaveandloadmethodsinFpSpreadandusedifferentbuildsoftheirassembly.
Inthatcase,theassemblyattributeisrequiredtoloadthecorrectassemblycontainingtheobject'stypedefinition,butthecorrectattributeforthedebugandreleasebuildsisdifferent.Inthatcase,theuserwouldneedtoeditthevalueintheXMLtochangetheassemblyreference(usingsomethinglikeString.Replace).
ThelesscommoncasesinvolveuserswhoareusingISerializeSupportandSerializertosaveandloadtheirownfilescontainingobjectsthattheydefine,perhapsinthesameassemblyorinadifferentassemblythattheyarewritinginparallel.Iftheobjectsaredefinedinthesameassembly,thentheassemblytabwillnotbewrittenout,andifitisadifferentassembly,thedevelopercancalltheoverloadsforSerializeObjectand
Spread Windows Forms Developer’s Guide 539
Copyright © GrapeCity, Inc. All rights reserved.
CreateObjectInstanceAndDeserializewhichtakethecallingAssemblyargumentandpasstheassemblycontainingtheobject(evenifthatisnotreallytheassemblycallingintoSerializer).Thatwillpreventtheassemblyattributefrombeingwrittenout,butitisimportantthatthisbedoneonbothends(thecalltosaveandload)sothatthetypereferencecanberesolvedandaninstanceoftheobjectcreated.
HerearesomeexamplesofhowyoumightimplementISerializeSupport.
UsingCode
Thisexampleusesthebaseclass.
Example
ThefollowingcodeprovidestheimplementationofISerializeSupportinFarPoint.Win.LineBorder:
C#// A constructor with no arguments is required for ISerializeSupport.// It does not need to be public though. internal LineBorder() { color = SystemColors.WindowFrame; thickness = 1; left = top = right = bottom = true; inset = new Inset(1); } /// <summary>/// Saves the object to XML./// </summary>/// <param name="w">XmlTextWriter object to which to save the object</param>/// <returns>true if successful; false otherwise</returns> public virtual bool Serialize(XmlTextWriter w) { w.WriteStartElement("Inset"); w.WriteElementString("Bottom",inset.Bottom.ToString()); w.WriteElementString("Left", inset.Left.ToString()); w.WriteElementString("Right", inset.Right.ToString()); w.WriteElementString("Top", inset.Top.ToString()); w.WriteEndElement(); Serializer.SerializeColor(color, "Color", w); w.WriteStartElement("Sides"); w.WriteElementString("Bottom", bottom.ToString()); w.WriteElementString("Left", left.ToString()); w.WriteElementString("Right", right.ToString()); w.WriteElementString("Top", top.ToString()); w.WriteEndElement(); w.WriteElementString("Thickness", thickness.ToString(CultureInfo.InvariantCulture)); return true; } /// <summary>/// Loads the object from XML./// </summary>/// <param name="r">XmlNodeReader from which to load the object</param>/// <returns>true if successful; false otherwise</returns> public virtual bool Deserialize(XmlNodeReader r)
Spread Windows Forms Developer’s Guide 540
Copyright © GrapeCity, Inc. All rights reserved.
{ bool inInset = false; bool inBottom = false; bool inLeft = false; bool inRight = false; bool inTop = false; bool inColor = false; bool inSides = false; bool inThickness = false; int bottom = inset.Bottom; int left = inset.Left; int right = inset.Right; if( r.IsEmptyElement ) return true; while( r.Read() ) { switch( r.NodeType ) { case XmlNodeType.Element: if( r.Name.Equals("Inset") ) inInset = true; else if( r.Name.Equals("Color") ) inColor = true; else if( r.Name.Equals("Sides") ) inSides = true; else if( inInset || inSides ) { if( r.Name.Equals("Bottom") ) inBottom = true; else if( r.Name.Equals("Left") ) inLeft = true; else if( r.Name.Equals("Right") ) inRight = true; else if( r.Name.Equals("Top") ) inTop = true; } else if( r.Name.Equals("Thickness") ) inThickness = true; break; case XmlNodeType.Text: if( inInset ){if( inBottom )bottom = XmlConvert.ToInt32(r.Value);else if( inLeft )left = XmlConvert.ToInt32(r.Value);else if( inRight )right = XmlConvert.ToInt32(r.Value);else if( inTop )inset = new Inset(left, XmlConvert.ToInt32(r.Value), right, bottom);}else if( inSides ){if( inBottom )this.bottom = XmlConvert.ToBoolean(r.Value.ToLower(CultureInfo.InvariantCulture));else if( inLeft )this.left = XmlConvert.ToBoolean(r.Value.ToLower(CultureInfo.InvariantCulture));
Spread Windows Forms Developer’s Guide 541
Copyright © GrapeCity, Inc. All rights reserved.
else if( inRight )this.right = XmlConvert.ToBoolean(r.Value.ToLower(CultureInfo.InvariantCulture));else if( inTop )this.top = XmlConvert.ToBoolean(r.Value.ToLower(CultureInfo.InvariantCulture));}else if( inColor )color = Serializer.DeserializeColorValue(r.Value);else if( inThickness )thickness = XmlConvert.ToInt32(r.Value);break;case XmlNodeType.EndElement:if( inInset && r.Name.Equals("Inset") )inInset = false;else if( inColor && r.Name.Equals("Color") )inColor = false;else if( inSides && r.Name.Equals("Sides") )inSides = false;else if( inInset || inSides ){if( inBottom && r.Name.Equals("Bottom") )inBottom = false;else if( inLeft && r.Name.Equals("Left") )inLeft = false;else if( inRight && r.Name.Equals("Right") )inRight = false;else if( inTop && r.Name.Equals("Top") )inTop = false;}else if( inThickness && r.Name.Equals("Thickness") )// return here so that subclasses can deserializereturn true;break;}}return true;}
Example
Thisisanexampleofwhataderivedclassmightdoinoverridesforthosemethods:
C#// A constructor with no arguments is required for ISerializeSupport.// It does not need to be public though.protected GradientLineBorder() : LineBorder(SystemColors.WindowFrame, 1, true, true, true, true){startColor = Color.Blue;endColor = Color.Green;}/// <summary>/// Saves the object to XML./// </summary>/// <param name="w">XmlTextWriter object to which to save the object</param>/// <returns>true if successful; false otherwise</returns>public override bool Serialize(XmlTextWriter w)
Spread Windows Forms Developer’s Guide 542
Copyright © GrapeCity, Inc. All rights reserved.
{if( !base.Serialize(w) )return false;Serializer.SerializeColor(startColor, "StartColor", w);Serailizer.SerializeColor(endColor, "EndColor", w);return true;}/// <summary>/// Loads the object from XML./// </summary>/// <param name="r">XmlNodeReader from which to load the object</param>/// <returns>true if successful; false otherwise</returns>public override bool Deserialize(XmlNodeReader r){bool inStartColor = false;bool inEndColor = false;
if( r.IsEmptyElement )return true;if( !base.Deserialize(r) )return false;while( r.Read() ){switch( r.NodeType ){case XmlNodeType.Element:if( r.Name.Equals("StartColor") )inStartColor = true;else if( r.Name.Equals("EndColor") )inEndColor = true;case XmlNodeType.Text:if( inStartColor )startColor = Serializer.DeserializeColorValue(r.Value);else if( inEndColor )endColor = Serializer.DeserializeColorValue(r.Value);break;case XmlNodeType.EndElement:if( inStartColor && r.Name.Equals("StartColor") )inStartColor = false;else if( inEndColor && r.Name.Equals("EndColor") )// return here so that subclasses can deserializereturn true;break;}}return true;}
Example
Another(somewhateasier)waytoimplementitwouldbethisway:
C#/// <summary>/// Saves the object to XML./// </summary>
Spread Windows Forms Developer’s Guide 543
Copyright © GrapeCity, Inc. All rights reserved.
/// <param name="w">XmlTextWriter object to which to save the object</param>/// <returns>true if successful; false otherwise</returns>public override bool Serialize(XmlTextWriter w){ w.WriteAttributeString("startColor", Serializer.SerializeColorValue(startColor));w.WriteAttributeString("endColor", Serializer.SerializeColorValue(endColor));return base.Serialize(w);}/// <summary>/// Loads the object from XML./// </summary>/// <param name="r">XmlNodeReader from which to load the object</param>/// <returns>true if successful; false otherwise</returns>public override bool Deserialize(XmlNodeReader r){
if( r.MoveToAttribute("startColor") )startColor = Serializer.DeserializeColorValue(r.Value);if( r.MoveToAttribute("endColor") )endColor = Serializer.DeserializeColorValue(r.Value);return base.Deserialize(r); }
Parsing Formulas in Custom XML Deserialization
Withtheimplementationofcross-sheetreferencesinSpread,formulascancontainreferencestoothersheets.Ifsuchformulasareloadedfromafile,theSpreadcomponentmustloadsheetsandformulasinaspecificsequenceforthecross-sheetreferencestowork.Theparsingofformulasloadedfromafilemustbedelayeduntilallthesheetsintheworkbookhavebeenloaded.TheOpenmethodsinFpSpreadhandlethisautomatically,loadingtheXMLandparsinginthecorrectorder.
Ifyouhavecreatedcustomdeserializationcode,thenyouhavetobecareful.Ifyourcustomcodeloadsindividualsheetsandaddsthemtoaworkbook,thenyouwillneedtoaddcodetoparsetheformulasafterthesheethasbeenaddedtotheworkbook.ThiscanbedonewiththeLoadFormulas('LoadFormulasMethod'intheon-linedocumentation)method,availableintheFpSpread('FpSpreadClass'intheon-linedocumentation)class.ThismethodisimplementedintheDefaultSheetDataModel('DefaultSheetDataModelClass'intheon-linedocumentation)andSheetView('SheetViewClass'intheon-linedocumentation)classesaswellastheFpSpread('FpSpreadClass'intheon-linedocumentation)class.UsingtheLoadFormulas('LoadFormulasMethod'intheon-linedocumentation)methodatthesheetlevelcallsthemethodonallthedatamodelsforaparticularsheet;usingtheLoadFormulas('LoadFormulasMethod'intheon-linedocumentation)methodattheFpSpreadlevelcallsthemethodonallthesheets.
Forexample,thefollowingcode(inVisualBasic):
FpSpread.Sheets.Add(FarPoint.Win.Serializer.LoadObject(GetType (FarPoint.Win.Spread.SheetView), "C:\SavedSheet.xml", "RootNode"))
shouldbechangedto:
FpSpread.Sheets.Add(FarPoint.Win.Serializer.LoadObject(GetType (FarPoint.Win.Spread.SheetView), "C:\SavedSheet.xml", "RootNode")) FpSpread.LoadFormulas()
Thiscodeshouldbecalledafterthecodethatloadsthesheetandaddsittotheworkbook.
Formoredetails,refertothesemethods:
FpSpreadLoadFormulas('LoadFormulasMethod'intheon-linedocumentation)methodSheetViewLoadFormulas('LoadFormulasMethod'intheon-linedocumentation)methodDefaultSheetDataModelLoadFormulas('LoadFormulasMethod'intheon-linedocumentation)methodDefaultSheetDataModelParseFormula('ParseFormulaMethod'intheon-linedocumentation)method
Formoreinformationaboutformulasandcross-sheetreferencing,refertotheFormulaReference.
Saving and Loading a Skin
Youcansaveskinsettingsforasheetortheentirecontroltoafile(.SKN)andthenloaditintoanotherprojectoruseitasatemplateforotherprojects.TheSheetSkin('SheetSkinClass'intheon-linedocumentation)classhasLoadandSavemethodsforasheet.TheSpreadSkin('SpreadSkinClass'intheon-linedocumentation)classhasLoadandSavemethodsfortheentirecontrol.Ifyouwanttohaveacertainlookfortheentirecontrol,useaspreadskin.Ifyouwanteachsheettohaveadifferentlook,useasheetskin.
SavingaSkinLoadingaSkin
Formoreinformationoncreatingaskinforasheet,refertoCreatingaCustomSkinforaSheet.
Formoreinformationoncreatingaskinfortheentirecontrol,refertoCreatingaCustomSkinforaComponent.
Formoreinformationonapplyingaskin,refertoApplyingaSkintoaSheetorApplyingaSkintotheComponent.
Spread Windows Forms Developer’s Guide 544
Copyright © GrapeCity, Inc. All rights reserved.
ForinformationoncustomizingaskinintheSpreadDesigner,refertotheexplanationoftheSheetSkinEditor(on-linedocumentation)ortheSpreadSkinEditor(on-linedocumentation)intheSpreadDesignerGuide.
Formoredetailsaboutskins,refertotheSheetSkin('SheetSkinClass'intheon-linedocumentation)classortheSpreadSkin('SpreadSkinClass'intheon-linedocumentation)class.
Saving a Skin
Youcansavetheskintoafileorastream.
Ifyoudonotspecifyapath,thefileissavedintheVisualStudioprojectbinfolderinaDebugsubfolder.Ifyouspecifyapaththatincludesafolderthatdoesnotexist,anerrormessageappearsduringcodecompile.
UsetheSave('SaveMethod'intheon-linedocumentation)methodsintheSheetSkin('SheetSkinClass'intheon-linedocumentation)orSpreadSkin('SpreadSkinClass'intheon-linedocumentation)class.
UsingCode
UsetheSave(SheetSkin,String)methodintheSheetSkin('SheetSkinClass'intheon-linedocumentation)classforsavingtoafile;usetheSave(SheetSkin,Stream)methodforsavingtoastream.
Example
Thisexamplecodesavesaskintoafile.
C#// define a skin and save itFarPoint.Win.Spread.SheetSkin sk = new FarPoint.Win.Spread.SheetSkin("BlueSkin", Color.White, Color.DarkGray, Color.Black, Color.Blue, FarPoint.Win.Spread.GridLines.Both, Color.Blue, Color.Red, Color.White, Color.Black, Color.LightGray, Color.Gray, false, false, true, true, true);FarPoint.Win.Spread.SheetSkin.Save(sk,"C:\\BlueSkinTemplate.skn");// FarPoint.Win.Spread.SpreadSkin.Save for a SpreadSkin
VB' define a skin and save itDim sk As New FarPoint.Win.Spread.SheetSkin("BlueSkin", Color.White, Color.DarkGray, Color.Black, Color.Blue, FarPoint.Win.Spread.GridLines.Both, Color.Blue, Color.Red, Color.White, Color.Black, Color.LightGray, Color.Gray, False, False, True, True, True)FarPoint.Win.Spread.SheetSkin.Save(sk,"C:\BlueSkinTemplate.skn")' FarPoint.Win.Spread.SpreadSkin.Save for a SpreadSkin
Loading a Skin
Youcanloadaskinfromafileorastream.
UsetheLoad('LoadMethod'intheon-linedocumentation)methodsintheSheetSkin('SheetSkinClass'intheon-linedocumentation)orSpreadSkin('SpreadSkinClass'intheon-linedocumentation)class.
UsingCode
UsetheLoad(String)methodintheSheetSkin('SheetSkinClass'intheon-linedocumentation)class(orSpreadSkin('SpreadSkinClass'intheon-linedocumentation)class)forloadingfromafile;usetheLoad(Stream)methodforloadingfromastream.
Spread Windows Forms Developer’s Guide 545
Copyright © GrapeCity, Inc. All rights reserved.
Example
Thisexamplecodeloadsaskinfromafile.
C#// load a sheet skinFarPoint.Win.Spread.SheetSkin.Load("C:\\BlueSkinTemplate.skn").Apply(FpSpread1.Sheets[0];// load a spread Skin// FarPoint.Win.Spread.SpreadSkin.Load("C:\\farpoint.skn").Apply (FpSpread1);
VB' load a sheet skinFarPoint.Win.Spread.SheetSkin.Load("C:\BlueSkinTemplate.skn").Apply(FpSpread1.Sheets(0))' load a Spread Skin'FarPoint.Win.Spread.SpreadSkin.Load("C:\farpoint.skn").Apply(FpSpread1)
Spread Windows Forms Developer’s Guide 546
Copyright © GrapeCity, Inc. All rights reserved.
Managing Printing
Youcanprintaspreadsheet,orpartsofaspreadsheet,anduseavarietyofoptionstocustomizeprinting.
Spreadoffersyouseveralwaystohandletheprintingandprovidessomedefaulthandlingifyouwanttokeepitsimple.Youcanprintvariouspartsofthesheet,youcansetoptionsfortheappearanceofwhatisprinted,youcanpreviewtheprinting,youcanapplyprinter'ssettingtoprintpreview,youcanshowtheprintpreviewdialoglikeexcel,youcanprintinduplexmode(printonbothsidesofthepaper),youcanprintmorethanonepageinasheetofpaperandyoucanprovidetheprintingoperationtotheenduser.
MuchoftheprintingworkusesthePrintSheet('PrintSheetMethod'intheon-linedocumentation)methodintheFpSpread('FpSpreadClass'intheon-linedocumentation)class.ManyoftheoptionsavailableforcustomizingtheprintingareinthePrintInfo('PrintInfoProperty'intheon-linedocumentation)class.ForeachsheetinSpreadyouassignaPrintInfoobject.Moreinformationonthetasksinvolvedwiththemanagementofprintingaregiveninthesetopics:
SpecifyingWhattoPrintCustomizingtheAppearanceofthePrintingOptimizingthePrintingDisplayingDialogsforUsers
YoucanalsohandleprintingwithintheSpreadDesigner.FormoreinformationonprintingandpreviewinginSpreadDesigner,refertoPrintingaSheetfromSpreadDesigner(on-linedocumentation).
SheetsareprintedonthecurrentdefaultprinterinyourWindowsenvironmentunlessyouspecifyotherwise.YoucanprintsheetsonanyWindows-supportedprinter.
Specifying What to Print
Youcanprintanysheetintheworkbookorprinttheentiresetofsheets.Youcanalsoprintanyofseveralpartsofthespreadsheet.
PrintinganEntireSheetPrintingtoPDFPrintingaChildViewofaHierarchicalDisplayPrintingParticularPagesPrintingthePortionoftheSheetwithDataPrintingaRangeofCellsonaSheetPrintinganAreaoftheSheetPrintingaSheetwithCellNotesPrintingaSheetwithShapesPrintinginDuplexMode(on-linedocumentation)
Printing an Entire Sheet
YoucanprintasheetinthecomponentwiththeFpSpread.PrintSheet('PrintSheetMethod'intheon-linedocumentation)method.Usethismethodtoprintthesheetorsheets,usingthePrintInfo('PrintInfoProperty'intheon-linedocumentation)settingsforeachsheet.Youcanonlyprintonesheetinthecomponentatatime;eachsheetcanhaveitsownPrintInfoobject,butyoucancallthePrintSheetmethodoncetodooneorallofthesheets.Ifthesheetparameterissetto-1,allthesheetsintheSpreadcomponentprint,witheachsheet(withitsindividualPrintInfosettings)asaseparateprintjob.ThePrintDocument('PrintDocumentEvent'intheon-linedocumentation)eventoccurswhenprintingasheet.
Thedefaultsettingprintsinblackandwhiteandautomaticallydeterminesthebestorderinwhichtoprintpages.With
Spread Windows Forms Developer’s Guide 547
Copyright © GrapeCity, Inc. All rights reserved.
thedefaultsettings,thefollowingitemsprintusingtheprinter’scurrentorientationsetting:
allthecolumnsandrowsinthesheet(butonlythecellsthathavedatainthem)thesheet’sborderthecolumnandrowheaderstheheadershadowsthegridlines
Tocustomizethesesettings,refertoUnderstandingthePrintingOptionsandCustomizingthePrintedPageHeaderorFooter.ToallowSpreadtodeterminethebestprintsettings,refertoOptimizingthePrintingUsingRules.
YoucancallPrintSheetwithdifferentsheetparametersoneaftertheotherbutcallingPrintSheetonthesamesheetwithoutwaitingfortheinitialprinttoconcludecouldproduceincorrectresults.Beforecallingthenextprintforagivensheet,youneedtowaitforthepreviousonetobefinished.YoucandothisbycatchingthePrintMessageBoxeventandqueryingtheBeginPrintingparametertoseeifitisFalse.
YoucanalsousetheSpreadDesignertosetpropertiesforprinting,andyoucanprintdirectlyfromtheSpreadDesigner.Formoreinformation,refertoPrintingaSheetfromSpreadDesigner(on-linedocumentation).
UsingCode
UsethePrintSheetmethodintheFpSpread('FpSpreadClass'intheon-linedocumentation)classtoprintthespecifiedsheet.
Example
Thisexamplecodeprintsthesecondsheetinthecomponent.
C#fpSpread1.PrintSheet(1);
VBFpSpread1.PrintSheet(1)
Printing to PDF
YoucanprintasheettoaPortableDocumentFormat(PDF,version1.4)fileusingthePrintToPdf('PrintToPdfProperty'intheon-linedocumentation)methodinthePrintInfo('PrintInfoClass'intheon-linedocumentation)class.UsethePdfFileName('PdfFileNameProperty'intheon-linedocumentation)propertytospecifythefilenameandlocationtowhichtosavethefile.SincePrintInfoobjectsareassignedtoindividualsheets,thismethodprintsanindividualsheet.
YoucansetapasswordwiththePdfSecurity('PdfSecurityProperty'intheon-linedocumentation)property.
ThefollowingcelltypeitemsarenotprintedtoPDF:
CellType DescriptionGcTextBoxCellType('GcTextBoxCellTypeClass'intheon-linedocumentation)
LineSpace('LineSpaceProperty'intheon-linedocumentation),Ellipsis('EllipsisProperty'intheon-linedocumentation),orDisplayAlignment('DisplayAlignmentProperty'intheon-linedocumentation)
AnyGccelltype Sidebuttonappearance
GcDateTimeCellType Fieldappearance
Spread Windows Forms Developer’s Guide 548
Copyright © GrapeCity, Inc. All rights reserved.
('GcDateTimeCellTypeClass'intheon-linedocumentation)
GcNumberCellType('GcNumberCellTypeClass'intheon-linedocumentation)
Fieldappearance
GcTimeSpanCellType('GcTimeSpanCellTypeClass'intheon-linedocumentation)
Fieldappearance
GcMaskCellType('GcMaskCellTypeClass'intheon-linedocumentation)
Fieldappearance
GcCharMaskCellType('GcCharMaskCellTypeClass'intheon-linedocumentation)
Characterboxappearance
GcComboBoxCellType('GcComboBoxCellTypeClass'intheon-linedocumentation)
Imageappearanceorellipsis
Tocustomizeprintsettings,refertoUnderstandingthePrintingOptionsandCustomizingthePrintedPageHeaderorFooter.ToallowSpreadtodeterminethebestprintsettings,refertoOptimizingthePrintingUsingRules.
UsingCode
CallthePrintToPdf('PrintToPdfProperty'intheon-linedocumentation)propertyinthePrintInfo('PrintInfoClass'intheon-linedocumentation)classtoprintthespecifiedsheet.
Example
ThisexamplecodesavesthesheettoaPDFfile.
C#FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();printset.PrintToPdf = true;printset.PdfFileName = "D:\\results.pdf";// Assign the printer settings and printfpSpread1.Sheets[0].PrintInfo = printset;fpSpread1.PrintSheet(0);
VBDim printset As New FarPoint.Win.Spread.PrintInfo()printset.PrintToPdf = Trueprintset.PdfFileName = "D:\results.pdf"' Assign the printer settings and printFpSpread1.Sheets(0).PrintInfo = printsetFpSpread1.PrintSheet(0)
Spread Windows Forms Developer’s Guide 549
Copyright © GrapeCity, Inc. All rights reserved.
UsingtheSpreadDesigner
1. SelecttheFilemenu.2. SelectPrint.3. SelectPrintPDF.4. UsetheSavedialogtopickalocationandspecifyafilename.
Printing a Child View of a Hierarchical Display
Youcanprintchildsheetsofahierarchyandmanagehowtheyareprinted.Todothis,youspecifythespecificchildviewandthenusethePrintSheet('PrintSheetMethod'intheon-linedocumentation)methodasdescribedinPrintinganEntireSheet.
Formoreinformationaboutahierarchicaldisplay,refertoWorkingwithHierarchicalDataDisplay.
UsingCode
UsethePrintSheet('PrintSheetMethod'intheon-linedocumentation)methodtoprintchildsheets.
Example
Thisexampleprintsachildsheet.
C#// Add print code to a command button in a hierarchy example.FarPoint.Win.Spread.SheetView ss;ss = fpSpread1.Sheets[0].GetChildView(0, 0);if (ss != null){ fpSpread1.PrintSheet(ss);};
VB' Add print code to a command button in a hierarchy example.Dim ss As FarPoint.Win.Spread.SheetViewss = FpSpread1.Sheets(0).GetChildView(0, 0)If Not ss Is Nothing Then FpSpread1.PrintSheet(ss)End If
Printing Particular Pages
Youcanprintallorsomeofthepagesforthesheet.SpecifythepagestoprintbysettingthePrintType('PrintTypeProperty'intheon-linedocumentation),PageStart('PageStartProperty'intheon-linedocumentation),andPageEnd('PageEndProperty'intheon-linedocumentation)propertiesofthePrintInfo('PrintInfoClass'intheon-linedocumentation)object.
YoucancalculatethenumberofprintedpagesforthesheetusingtheGetPrintPageCount('GetPrintPageCountMethod'intheon-linedocumentation)method.
UsingthePropertiesWindow
Spread Windows Forms Developer’s Guide 550
Copyright © GrapeCity, Inc. All rights reserved.
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetforwhichtosettheprintthepagerange.5. Inthepropertieslist,double-clickthePrintInfopropertytodisplaythesettingsforthePrintInfoclass.6. SetthePrintTypepropertytoPageRange.7. SetthePageStartandPageEndpropertiestodesignatethepagerangetoprint.8. ClickOKtoclosetheeditor.
UsingaShortcut
1. CreateaPrintInfo('PrintInfoClass'intheon-linedocumentation)object.2. SetthePrintInfo('PrintInfoClass'intheon-linedocumentation)objectPrintType('PrintTypeProperty'intheon-linedocumentation)propertytoPrintType.PageRange.Ifyoujustwanttoprintthecurrentpage,setthePrintType('PrintTypeProperty'intheon-linedocumentation)propertytoPrintType.CurrentPage,andgoontostep4.
3. SetthePrintInfoobjectPageStart('PageStartProperty'intheon-linedocumentation)andPageEnd('PageEndProperty'intheon-linedocumentation)propertiestodesignatethepagerangetoprint.
4. SettheSheetshortcutobjectPrintInfopropertytothePrintInfoobjectyoujustcreated.
Example
Thisexamplecodeprintspages5through10.
C#// Create PrintInfo object and set properties.FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();printset.PrintType = FarPoint.Win.Spread.PrintType.PageRange;printset.PageStart = 5;printset.PageEnd = 10;// Set the PrintInfo property for the first sheet.fpSpread1.Sheets[0].PrintInfo = printset;// Print the sheet.fpSpread1.PrintSheet(0);
VB' Create PrintInfo object and set properties.Dim printset As New FarPoint.Win.Spread.PrintInfo()printset.PrintType = FarPoint.Win.Spread.PrintType.PageRangeprintset.PageStart = 5printset.PageEnd = 10' Set the PrintInfo property for the first sheet.FpSpread1.Sheets(0).PrintInfo = printset' Print the sheet.FpSpread1.PrintSheet(0)
UsingCode
1. CreateaPrintInfo('PrintInfoClass'intheon-linedocumentation)object.2. SetthePrintInfo('PrintInfoClass'intheon-linedocumentation)objectPrintType('PrintTypeProperty'intheon-linedocumentation)propertytoPrintType.PageRange.Ifyoujustwanttoprintthecurrentpage,setthePrintType('PrintTypeProperty'intheon-line
Spread Windows Forms Developer’s Guide 551
Copyright © GrapeCity, Inc. All rights reserved.
documentation)propertytoPrintType.CurrentPage,andgoontostep4.
3. SetthePrintInfoobjectPageStart('PageStartProperty'intheon-linedocumentation)andPageEnd('PageEndProperty'intheon-linedocumentation)propertiestodesignatethepagerangetoprint.
4. SettheSheetViewobjectPrintInfopropertytothePrintInfoobjectyoujustcreated.
Example
Thisexamplecodeprintspages5through10.
C#// Create PrintInfo object and set properties.FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();printset.PrintType = FarPoint.Win.Spread.PrintType.PageRange;printset.PageStart = 5;printset.PageEnd = 10;// Create SheetView object and assign it to the first sheet.FarPoint.Win.Spread.SheetView SheetToPrint = new FarPoint.Win.Spread.SheetView();SheetToPrint.PrintInfo = printset;fpSpread1.Sheets[0] = SheetToPrint;// Print the sheet.fpSpread1.PrintSheet(0);
VB' Create PrintInfo object and set properties.Dim printset As New FarPoint.Win.Spread.PrintInfo()printset.PrintType = FarPoint.Win.Spread.PrintType.PageRangeprintset.PageStart = 5printset.PageEnd = 10' Create SheetView object and assign it to the first sheet.Dim SheetToPrint As New FarPoint.Win.Spread.SheetView()SheetToPrint.PrintInfo = printsetFpSpread1.Sheets(0) = SheetToPrint' Set the PrintInfo property for the first sheet.FpSpread1.Sheets(0).PrintInfo = printset' Print the sheet.FpSpread1.PrintSheet(0)
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetyouwanttoprint.2. FromthePropertywindow,choosePrintInfo.3. SetPrintTypetoPageRange.4. SetPageEndandPageStart.5. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Printing the Portion of the Sheet with Data
Youmaynotwanttoprinttheentiresheetbutonlytheportionofthesheetthathasdata.UsetheUseMax('UseMaxProperty'intheon-linedocumentation)methodofthePrintInfo('PrintInfoClass'intheon-linedocumentation)classtospecifywhethertoprintonlyrowsandcolumnscontainingdataorwhethertoprintallthewaytotheendofthedefinedsheet,eveniftherowsandcolumnsareempty.
Ifyouwanttoprintallofthecolumns(evenifitdoesnothavedatainit)butonlytherowswithdata,youwouldneedtosetUseMaxtoTruetokeepfromprintingrowswithoutdata.Then,youwouldneedtoprogrammaticallyputdatainthelastcolumnandthelastrowwithdata,sotheSpreadprintsallthecolumns.YoucouldaddalineofcodesimilartothefollowingbeforecallingthePrintSheet('PrintSheetMethod'inthe
Spread Windows Forms Developer’s Guide 552
Copyright © GrapeCity, Inc. All rights reserved.
on-linedocumentation)method.
C#FpSpread1.Sheets(0).Cells(FpSpread1.Sheets(0).GetLastNonEmptyRow(FarPoint.Win.Spread.NonEmptyItemFlag.Data), (FpSpread1.Sheets(0).ColumnCount - 1)).Value = ""
VBfpSpread1.Sheets[0].Cells[fpSpread1.Sheets[0].GetLastNonEmptyRow(FarPoint.Win.Spread.NonEmptyItemFlag.Data), fpSpread1.Sheets[0].ColumnCount - 1].Value = "";
Formoreinformationaboutmethodsinvolvedwithfindingdata,refertoFindingRowsorColumnsThatHaveData.
Printing a Range of Cells on a Sheet
Youmaynotwanttoprinttheentiresheetbutonlyaspecifiedrangeofcellsonasheet.Youcanspecifythatonlyarangeofcellswithinasheetprints,ratherthantheentiresheet.AfterspecifyingtherangeofcellswiththePrintInfo('PrintInfoClass'intheon-linedocumentation)object,usethePrintSheet('PrintSheetMethod'intheon-linedocumentation)methodasdescribedinPrintinganEntireSheet.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetforwhichtosettheprintthecellrange.5. Inthepropertieslist,double-clickthePrintInfopropertytodisplaythesettingsforthePrintInfoclass.6. SetthePrintTypepropertytoPageRange.7. SettheColStart,RowStart,ColEnd,andRowEndpropertiestodesignatethecellrangetoprint.8. ClickOKtoclosetheeditor.
UsingaShortcut
CreateaPrintInfo('PrintInfoClass'intheon-linedocumentation)object.SetthePrintInfoobjectPrintType('PrintTypeProperty'intheon-linedocumentation)propertytoPrintType.CellRange.SetthePrintInfoobjectColStart('ColStartProperty'intheon-linedocumentation),RowStart('RowStartProperty'intheon-linedocumentation),ColEnd('ColEndProperty'intheon-linedocumentation),andRowEnd('RowEndProperty'intheon-linedocumentation)propertiestodesignatethecellrangetoprint.SettheSheetshortcutobjectPrintInfopropertytothePrintInfoobjectyoujustcreated.
Example
ThisexamplecodeprintscellsB2throughD4.
C#// Create PrintInfo object and set properties.FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();printset.PrintType = FarPoint.Win.Spread.PrintType.CellRange;printset.ColStart = 1;printset.ColEnd = 3;printset.RowStart = 1;printset.RowEnd = 3;
Spread Windows Forms Developer’s Guide 553
Copyright © GrapeCity, Inc. All rights reserved.
// Set the PrintInfo property for the first sheet.fpSpread1.Sheets[0].PrintInfo = printset;// Print the sheet.fpSpread1.PrintSheet(0);
VB' Create PrintInfo object and set properties.Dim printset As New FarPoint.Win.Spread.PrintInfo()printset.PrintType = FarPoint.Win.Spread.PrintType.CellRangeprintset.ColStart = 1printset.ColEnd = 3printset.RowStart = 1printset.RowEnd = 3' Set the PrintInfo property for the first sheet.FpSpread1.Sheets(0).PrintInfo = printset' Print the sheet.FpSpread1.PrintSheet(0)
UsingCode
1. CreateaPrintInfo('PrintInfoClass'intheon-linedocumentation)object.2. SetthePrintInfoobjectPrintType('PrintTypeProperty'intheon-linedocumentation)propertyto
PrintType.CellRange.3. SetthePrintInfoobjectColStart('ColStartProperty'intheon-linedocumentation),RowStart('RowStartProperty'intheon-linedocumentation),ColEnd('ColEndProperty'intheon-linedocumentation),andRowEnd('RowEndProperty'intheon-linedocumentation)propertiestodesignatethecellrangetoprint.
4. SettheSheetViewobjectPrintInfopropertytothePrintInfoobjectyoujustcreated.
Example
ThisexamplecodeprintscellsB2throughD4.
C#// Create PrintInfo object and set properties.FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();printset.PrintType = FarPoint.Win.Spread.PrintType.CellRange;printset.ColStart = 1;printset.ColEnd = 3;printset.RowStart = 1;printset.RowEnd = 3;// Create SheetView object and assign it to the first sheet.FarPoint.Win.Spread.SheetView SheetToPrint = new FarPoint.Win.Spread.SheetView();SheetToPrint.PrintInfo = printset;fpSpread1.Sheets[0] = SheetToPrint;// Print the sheet.fpSpread1.PrintSheet(0);
VB' Create PrintInfo object and set properties.Dim printset As New FarPoint.Win.Spread.PrintInfo()printset.PrintType = FarPoint.Win.Spread.PrintType.CellRangeprintset.ColStart = 1
Spread Windows Forms Developer’s Guide 554
Copyright © GrapeCity, Inc. All rights reserved.
printset.ColEnd = 3printset.RowStart = 1printset.RowEnd = 3' Create SheetView object and assign it to the first sheet.Dim SheetToPrint As New FarPoint.Win.Spread.SheetView()SheetToPrint.PrintInfo = printsetFpSpread1.Sheets(0) = SheetToPrint' Set the PrintInfo property for the first sheet.FpSpread1.Sheets(0).PrintInfo = printset' Print the sheet.FpSpread1.PrintSheet(0)
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetyouwanttoprint.2. SelectthePageLayoutoption.3. SelectthePrintTitlesicon,chooseGeneral.
TheSheetPrintOptionsdialogappears.
4. ClicktheOutputtab.5. FromtheOutputTypedrop-downlistbox,chooseCellRange.6. ClickOKtoclosetheSheetPrintOptionsdialog.7. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.8. Tospecifytherangeofcells,9. Toprinttherangeofcells,followtheinstructionsinPrintinganEntireSheet.
Printing an Area of the Sheet
Youmaynotwanttoprinttheentiresheetbutonlyaspecifiedareaofthesheet.YoucanspecifyanareaofthesheetwiththePrintType('PrintTypeProperty'intheon-linedocumentation)propertyofthePrintInfoobjectorusetheOwnerPrintDraw('OwnerPrintDrawMethod'intheon-linedocumentation)methodforthecontrol.Aswiththeotherprintingtasks,suchasPrintinganEntireSheet,thisinvolvesthePrintSheet('PrintSheetMethod'intheon-linedocumentation)method.
UsingCode
SetthePrintType('PrintTypeProperty'intheon-linedocumentation)propertyandusethePrintSheet('PrintSheetMethod'intheon-linedocumentation)methodtoprint.
Example
Thisexamplespecifiesanareatoprint.
C#// Create the printer settings objectFarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();// Allow printing of only 20 columns and 20 rows of cellsprintset.ColStart = 1;printset.ColEnd = 20;printset.RowStart = 1;printset.RowEnd = 20;printset.PrintType = FarPoint.Win.Spread.PrintType.CellRange;// Assign the printer settings to the sheet and print it
Spread Windows Forms Developer’s Guide 555
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.Sheets[0].PrintInfo = printset;fpSpread1.PrintSheet(0);
VBDim printset As New FarPoint.Win.Spread.PrintInfo' Allow printing of only 20 columns and 20 rows of cellsprintset.ColEnd = 20printset.ColStart = 1printset.RowStart = 1printset.RowEnd = 20printset.PrintType = FarPoint.Win.Spread.PrintType.CellRange' Assign the printer settings to the sheet and print itFpSpread1.Sheets(0).PrintInfo = printsetFpSpread1.PrintSheet(0)
Printing a Sheet with Cell Notes
Youcanprintcellnotesaswellasthedata.UsethePrintNotes('PrintNotesProperty'intheon-linedocumentation)propertyinthePrintInfo('PrintInfoClass'intheon-linedocumentation)objecttoprintnotes.Thenotescanbeprintedonapageeitherafterthedataisprintedorasdisplayedonthesheet.
Thefollowingfigureshowshowprintingastickynoteasdisplayedmightlook.
Forinformationaboutaddingcellnotes,refertoAddingaNotetoaCell.
UsingCode
1. UsethePrintNotes('PrintNotesProperty'intheon-linedocumentation)propertytoprintnotes.2. UsethePrintSheet('PrintSheetMethod'intheon-linedocumentation)methodtoprint.
Example
Thisexampleprintsnotes.
C#private void Form1_Load(object sender, System.EventArgs e){ fpSpread1.Sheets[0].RowCount = 20; fpSpread1.Sheets[0].ColumnCount = 5; fpSpread1.TextTipPolicy = FarPoint.Win.Spread.TextTipPolicy.Fixed; FpSpread1.Sheets[0].Cells[0, 0].NoteStyle = FarPoint.Win.Spread.NoteStyle.StickyNote; fpSpread1.Sheets[0].Cells[0, 0].Note = "test";}
Spread Windows Forms Developer’s Guide 556
Copyright © GrapeCity, Inc. All rights reserved.
private void button1_Click(object sender, System.EventArgs e){ FarPoint.Win.Spread.PrintInfo pi = new FarPoint.Win.Spread.PrintInfo(); pi.PrintNotes =FarPoint.Win.Spread.PrintNotes.AsDisplayed; fpSpread1.Sheets[0].PrintInfo = pi; fpSpread1.PrintSheet(-1);}
VBPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load FpSpread1.Sheets(0).RowCount = 20 FpSpread1.Sheets(0).ColumnCount = 5 FpSpread1.TextTipPolicy = FarPoint.Win.Spread.TextTipPolicy.Fixed FpSpread1.Sheets(0).Cells(0, 0).NoteStyle = FarPoint.Win.Spread.NoteStyle.StickyNote FpSpread1.Sheets(0).Cells(0, 0).Note = "test"End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim pi As New FarPoint.Win.Spread.PrintInfo() pi.PrintNotes = FarPoint.Win.Spread.PrintNotes.AsDisplayed FpSpread1.Sheets(0).PrintInfo = pi FpSpread1.PrintSheet(-1)End Sub
Printing a Sheet with Shapes
Youcanprintshapesaswellasthedata.UsethePrintShapes('PrintShapesProperty'intheon-linedocumentation)propertyinthePrintInfo('PrintInfoClass'intheon-linedocumentation)objecttoincludeprintingtheshapeswhenprintingasheet.
Formoreinformationonshapes,refertoCustomizingDrawing.
UsingCode
UsethePrintShapes('PrintShapesProperty'intheon-linedocumentation)propertytoprintshapes.
Example
Thisexampleprintsshapes.
C#private void button1_Click(object sender, System.EventArgs e){FarPoint.Win.Spread.PrintInfo pi = new FarPoint.Win.Spread.PrintInfo();pi.PrintShapes =true;fpSpread1.Sheets[0].PrintInfo = pi;fpSpread1.PrintSheet(0);}private void Form1_Load(object sender, System.EventArgs e){
Spread Windows Forms Developer’s Guide 557
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Spread.DrawingSpace.ArrowShape arrow = new FarPoint.Win.Spread.DrawingSpace.ArrowShape();arrow.BackColor = Color.Plum;arrow.ForeColor = Color.Pink;arrow.SetBounds(0,0,200,100);fpSpread1.Sheets[0].AddShape(arrow);}
VBPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.ClickDim pi as New FarPoint.Win.Spread.PrintInfo()pi.PrintShapes = TruefpSpread1.Sheets(0).PrintInfo = piFpSpread1.PrintSheet(0)End SubPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadDim arrow As New FarPoint.Win.Spread.DrawingSpace.ArrowShape()arrow.BackColor = Color.Plumarrow.ForeColor = Color.Pinkarrow.SetBounds(0, 0, 200, 100)FpSpread1.ActiveSheet.AddShape(arrow)End Sub
Customizing the Appearance of the Printing
TherearevariousaspectsoftheprintingofthespreadsheetthatcanbecustomizedandmostofthemresideinthePrintInfo('PrintInfoClass'intheon-linedocumentation)object.ForanoverviewofthePrintInfoobject,refertoUnderstandingthePrintingOptions.
Thetasksinvolvedwithcustomizingtheprintinginclude:
UnderstandingthePrintingOptionsCustomizingthePrintJobSettingsCustomizingthePrintedPageLayoutCustomizingthePrintedPageHeaderorFooterCustomizingthePrintPreviewDialog(on-linedocumentation)RepeatingRowsorColumnsonPrintedPagesAddingaPageBreakAddingaWatermarktoaPrintedPage
MostprintoptionsaresetonthePrintInfoobjectandapplyatthesheetlevel.Whenyouprint,youaresendingaspecifiedsheettotheprinter,whichusesthosesettings.Ifyouwantdifferentprintsettingsfordifferentsheets,youmaywanttoresetthePrintInfoobjectandthenmakethenecessarychangesbetweentheprintingofthesheets.
Understanding the Printing Options
YoucancustomizetheprintingbysettingthepropertiesofaPrintInfo('PrintInfoClass'intheon-linedocumentation)objectandsettingthePrintInfo('PrintInfoProperty'intheon-linedocumentation)propertyofasheettothatobject.ThePrintInfo('PrintInfoClass'intheon-linedocumentation)objecthasthesettingsforcustomizingtheprintingofasheet.
ThePrintInfo('PrintInfoClass'intheon-linedocumentation)objectprovidesthefollowingpropertiesfor
Spread Windows Forms Developer’s Guide 558
Copyright © GrapeCity, Inc. All rights reserved.
customizingtheprinting:
Property DescriptionAbortMessage('AbortMessageProperty'intheon-linedocumentation)
Getsorsetsthemessagetodisplayfortheabortdialog.SeeDisplayinganAbortMessagefortheUser.
BestFitCols('BestFitColsProperty'intheon-linedocumentation)
Getsorsetswhethercolumnwidthsareadjustedtofitthelongeststringwidthforprinting.SeeOptimizingthePrintingUsingSize.
BestFitRows('BestFitRowsProperty'intheon-linedocumentation)
Getsorsetswhetherrowheightsareadjustedtofitthetalleststringheightforprinting.SeeOptimizingthePrintingUsingSize.
Centering('CenteringProperty'intheon-linedocumentation)
Getsorsetswhethertocentertheprintout.SeeCustomizingthePrintedPageLayout.
Colors('ColorsProperty'intheon-linedocumentation)
Getsorsetsthelistofcolorsthatcanbeusedinacustomheaderorfootertext.SeeCustomizingthePrintedPageHeaderorFooter.
ColStart('ColStartProperty'intheon-linedocumentation)andColEnd('ColEndProperty'intheon-linedocumentation)
Usedforprintingaportionofthesheet.SeePrintingaRangeofCellsonaSheet.
FirstPageNumber('FirstPageNumberProperty'intheon-linedocumentation)
Getsorsetsthepagenumbertoprintonthefirstpage.SeeCustomizingthePrintedPageLayout.
Footer('FooterProperty'intheon-linedocumentation)
Usedforprovidingfootersonprintedpages.SeeCustomizingthePrintedPageHeaderorFooter.
Header('HeaderProperty'intheon-linedocumentation)
Usedforprovidingheadersonprintedpages.SeeCustomizingthePrintedPageHeaderorFooter.
Images('ImagesProperty'intheon-linedocumentation)
Getsorsetsthelistofimagesthatcanbeusedinacustomheadersorfooters.SeeCustomizingthePrintedPageHeaderorFooter.
JobName('JobNameProperty'intheon-linedocumentation)
Getsorsetsthenameoftheprintjob.SeeCustomizingthePrintJobSettings.
Margin('MarginProperty'intheon-linedocumentation)
Getsorsetsthemarginsforprinting.SeeCustomizingthePrintedPageLayout.
Opacity('OpacityProperty'intheon-linedocumentation)
Getsorsetstheopacityusedwhenprintingthissheet;thisisusedtoprintawatermarkfirstandthenthesheetcontents.SeeCustomizingthePrintedPageLayout.
Orientation('OrientationProperty'intheon-linedocumentation)
Getsorsetsthepageorientationusedforprinting.SeeCustomizingthePrintJobSettings.
PageStart('PageStartProperty'intheon-linedocumentation)andPageEnd('PageEndProperty'intheon-linedocumentation)
Usedforprintingapagerange.SeePrintingParticularPages.
PageOrder('PageOrderProperty'intheon-linedocumentation)
Getsorsetstheorderinwhichpagesprint.SeeCustomizingthePrintJobSettings.
PaperSize('PaperSizeProperty'intheon-line Getsorsetsthepapersizetouse.SeeCustomizing
Spread Windows Forms Developer’s Guide 559
Copyright © GrapeCity, Inc. All rights reserved.
documentation) thePrintJobSettings.
PaperSource('PaperSourceProperty'intheon-linedocumentation)
Getsorsetsthepapersourcetouse.SeeCustomizingthePrintJobSettings.
Preview('PreviewProperty'intheon-linedocumentation)
Usedtoprovideprintpreview.SeeProvidingaPreviewofthePrinting.
Printer('PrinterProperty'intheon-linedocumentation)
Getsorsetsthenameoftheprintertouseforprinting.SeeCustomizingthePrintJobSettings.
PrintNotes('PrintNotesProperty'intheon-linedocumentation)
Getsorsetswhethertoprintthecellnotes.SeePrintingaSheetwithCellNotes.
PrintShapes('PrintShapesProperty'intheon-linedocumentation)
Getsorsetswhethertoprintfloatingobjects.SeePrintingaSheetwithShapes.
PrintType('PrintTypeProperty'intheon-linedocumentation)
Getsorsetswhatistobeprinted.SeePrintingParticularPages.
RepeatColStart('RepeatColStartProperty'intheon-linedocumentation)andRepeatColEnd('RepeatColEndProperty'intheon-linedocumentation)
Getsorsetswhethertoprintthesamesetofcolumnsoneachpage.SeeCustomizingthePrintedPageHeaderorFooter.
RepeatRowStart('RepeatRowStartProperty'intheon-linedocumentation)andRepeatRowEnd('RepeatRowEndProperty'intheon-linedocumentation)
Getsorsetswhethertoprintthesamesetofrowsoneachpage.SeeCustomizingthePrintedPageHeaderorFooter.
RowStart('RowStartProperty'intheon-linedocumentation)andRowEnd('RowEndProperty'intheon-linedocumentation)
Usedforprintingaportionofthesheet.SeePrintingaRangeofCellsonaSheet.
ShowBorder('ShowBorderProperty'intheon-linedocumentation)
Getsorsetswhethertoprintaborderaroundthesheet.SeeCustomizingthePrintedPageLayout.
ShowColor('ShowColorProperty'intheon-linedocumentation)
Getsorsetswhethertoprintthecolorsastheyappearonthescreen.SeeCustomizingthePrintedPageLayout.
ShowColumnHeader('ShowColumnHeaderProperty'intheon-linedocumentation)andShowRowHeader('ShowRowHeaderProperty'intheon-linedocumentation)
Getsorsetswhethertoprintthecolumnheadersandrowheaders.SeeCustomizingthePrintedPageLayout.
ShowGrid('ShowGridProperty'intheon-linedocumentation)
Getsorsetswhethertoprintthesheetgridlines.SeeCustomizingthePrintedPageLayout.
ShowPrintDialog('ShowPrintDialogProperty'intheon-linedocumentation)
Getsorsetswhethertodisplayaprintdialogbeforeprinting.SeeDisplayingaPrintDialogfortheUser.
ShowShadows('ShowShadowsProperty'intheon-linedocumentation)
Getsorsetswhethertoprinttheheadershadows.SeeCustomizingthePrintedPageLayout.
SmartPrintPagesTall('SmartPrintPagesTallProperty'intheon-linedocumentation)
Getsorsetshowmanypagestalltoprint.SeeOptimizingthePrintingUsingRules.
SmartPrintPagesWide('SmartPrintPagesWideProperty'intheon-linedocumentation)
Getsorsetshowmanypageswidetoprint.SeeOptimizingthePrintingUsingRules.
SmartPrintRules('SmartPrintRulesProperty'inthe Usedforsettinguptherulesforoptimizingthe
Spread Windows Forms Developer’s Guide 560
Copyright © GrapeCity, Inc. All rights reserved.
on-linedocumentation) printing.SeeOptimizingthePrintingUsingRules.
UseMax('UseMaxProperty'intheon-linedocumentation)
Getsorsetswhethertoprintonlyrowscontainingdata.SeePrintinganAreaoftheSheet.
UseSmartPrint('UseSmartPrintProperty'intheon-linedocumentation)
Usedforturningontherulesforoptimizingtheprinting.SeeOptimizingthePrintingUsingRules.
ZoomFactor('ZoomFactorProperty'intheon-linedocumentation)
Getsorsetsthezoomfactorusedforprintingthissheet.SeeCustomizingthePrintedPageLayout.
EnhancePreview('EnhancePreviewProperty'intheon-linedocumentation)
GetsorsetsthestatetoshowtheenhancedPrintPreviewDialog(likeexcel).SeeCustomizingthePrintPreviewDialog(on-linedocumentation).
ShowPageSetupButton('ShowPageSetupButtonProperty'intheon-linedocumentation)
GetsorsetsthestatetoshowthePageSetUpButtonontoolbarofthePrintPreviewDialog.SeeProvidingaPreviewofthePrinting.
Duplex('DuplexProperty'intheon-linedocumentation)
Getsorsetswhethertoallowausertoprintonbothsidesofthepaper.SeePrintinginDuplexMode(on-linedocumentation).
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetforwhichtosettheprintoptions.5. Inthepropertieslist,double-clickthePrintInfopropertytodisplaythesettingsforthePrintInfoclass.6. Setthepropertieslistedaboveasneededtosetyourprintoptions.7. ClickOKtoclosetheeditor.
UsingaShortcut
1. CreateandsetpropertiesforaPrintInfo('PrintInfoClass'intheon-linedocumentation)object.2. SettheSheetshortcutobjectPrintInfo('PrintInfoProperty'intheon-linedocumentation)propertyto
thePrintInfo('PrintInfoClass'intheon-linedocumentation)objectyoujustcreated.
Example
ThisexamplecodecreatesaPrintInfo('PrintInfoClass'intheon-linedocumentation)object,setspropertiestospecifytonotprintgridlinesorrowheaders,andtoprintonlycellswithdatainthem.
C#// Create PrintInfo object and set properties.FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();printset.ShowGrid = false;printset.ShowRowHeader = FarPoint.Win.Spread.PrintHeader.Hide;printset.UseMax = true;// Set the PrintInfo property for the first sheet.fpSpread1.Sheets[0].PrintInfo = printset;// Print the sheet.
Spread Windows Forms Developer’s Guide 561
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.PrintSheet(0);
VB' Create PrintInfo object and set properties.Dim printset As New FarPoint.Win.Spread.PrintInfo()printset.ShowGrid = Falseprintset.ShowRowHeader = FarPoint.Win.Spread.PrintHeader.Hideprintset.UseMax = True' Set the PrintInfo property for the first sheet.FpSpread1.Sheets(0).PrintInfo = printset' Print the sheet.FpSpread1.PrintSheet(0)
UsingCode
1. CreateandsetpropertiesforaPrintInfo('PrintInfoClass'intheon-linedocumentation)object.2. SettheSheetViewobjectPrintInfo('PrintInfoProperty'intheon-linedocumentation)propertytothePrintInfo('PrintInfoClass'intheon-linedocumentation)objectyoujustcreated.
Example
ThisexamplecodecreatesaPrintInfo('PrintInfoClass'intheon-linedocumentation)object,setspropertiestospecifytonotprintgridlinesorrowheaders,andtoprintonlycellswithdatainthem.
C#// Create PrintInfo object and set properties.FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();printset.ShowGrid = false;printset.ShowRowHeader = FarPoint.Win.Spread.PrintHeader.Hide;printset.UseMax = true;// Create SheetView object and assign it to the first sheet.FarPoint.Win.Spread.SheetView SheetToPrint = new FarPoint.Win.Spread.SheetView();SheetToPrint.PrintInfo = printset;fpSpread1.Sheets[0] = SheetToPrint;// Print the sheet.fpSpread1.PrintSheet(0);
VB' Create PrintInfo object and set properties.Dim printset As New FarPoint.Win.Spread.PrintInfo()printset.ShowGrid = Falseprintset.ShowRowHeader = FarPoint.Win.Spread.PrintHeader.Hideprintset.UseMax = True' Create SheetView object and assign it to the first sheet.Dim SheetToPrint As New FarPoint.Win.Spread.SheetView()SheetToPrint.PrintInfo = printsetFpSpread1.Sheets(0) = SheetToPrint' Print the sheet.FpSpread1.PrintSheet(0)
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosetprintsettings.
Spread Windows Forms Developer’s Guide 562
Copyright © GrapeCity, Inc. All rights reserved.
2. SelectthePageLayoutoption.3. SelectthePrintTitlesicon,chooseGeneral.
TheSheetPrintdialogappears.
4. SettheprintoptionsusingtheGeneral,Output,Header/Footer,SmartPrint,Pagination,andMarginstaboptions.
5. ClickOKtoclosetheSheetPrintOptionsdialog.6. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Customizing the Print Job Settings
SheetsareprintedonthecurrentdefaultprinterinyourWindowsenvironmentunlessyouspecifyotherwise.YoucanprintsheetsonanyWindows-supportedprinter.
Theprintjobsettingsthatyoucancustomizeinclude:printer,source,andpagesize.SetthePrinter('PrinterProperty'intheon-linedocumentation),PaperSource('PaperSourceProperty'intheon-linedocumentation),orPaperSize('PaperSizeProperty'intheon-linedocumentation)onthePrintInfoobject.
UsingCode
1. Setvariousprintjobsettings.2. Printthesheet.
Example
Thisexamplecodesetsthepapersourcebasedonaselectionfromacomboboxandsetsthepapersizebeforeprintingallthesheets.
C#private void Form1_Load(object sender, System.EventArgs e){ int i; System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings(); for (i = 0; i <= ps.PaperSources.Count - 1; i++) { comboBox1.Items.Add(ps.PaperSources[i].SourceName); } comboBox1.Text = ps.PaperSources[0].SourceName;}
private void button1_Click(object sender, System.EventArgs e{ FarPoint.Win.Spread.PrintInfo pi = new FarPoint.Win.Spread.PrintInfo(); System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings(); pi.PaperSize = new System.Drawing.Printing.PaperSize("Letter", 600, 300); pi.PaperSource = ps.PaperSources[comboBox1.SelectedIndex]; fpSpread1.Sheets[0].PrintInfo = pi; fpSpread1.PrintSheet(-1);}
Spread Windows Forms Developer’s Guide 563
Copyright © GrapeCity, Inc. All rights reserved.
VBPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ps As New System.Drawing.Printing.PrinterSettings() Dim i As Integer For i = 0 To ps.PaperSources.Count - 1 ComboBox1.Items.Add(ps.PaperSources.Item(i).SourceName) Next ComboBox1.Text = ps.PaperSources.Item(0).SourceNameEnd Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim pi As New FarPoint.Win.Spread.PrintInfo() Dim ps As New System.Drawing.Printing.PrinterSettings() pi.PaperSize = New System.Drawing.Printing.PaperSize("Letter", 600, 300) pi.PaperSource = ps.PaperSources(ComboBox1.SelectedIndex) FpSpread1.Sheets(0).PrintInfo = pi FpSpread1.PrintSheet(-1)End Sub
Customizing the Printed Page Layout
Youcancustomizethelayoutoftheprintedpageinanyofseveralways.Thelayoutsettingsthatyoucancustomizeinclude:color,borders,gridlinesandopacity,centeringandmargins,orientation,shadows,andzooming.ThesecustomizationsarepossiblewithpropertiesofthePrintInfoobject.
SettingthePrintedPageColor,Border,andGrid
Thereareseveralappearancecustomizationsthatcanbesetfortheprintedpage,includingsettingthecolor,theborder,andthegrid.
YoucansetthePrintInfoShowColor('ShowColorProperty'intheon-linedocumentation),ShowBorder('ShowBorderProperty'intheon-linedocumentation),andShowGrid('ShowGridProperty'intheon-linedocumentation)properties.
SettingthePrintedPageOrientation
Thereareseveralwaystocontroltheorientation(landscapeorportrait)ofthepagewhenprinting.
YoucansetthePrintInfoOrientation('OrientationProperty'intheon-linedocumentation)property.
YoucanuseLandscapeRule,whichisaSmartPrintrule.Formoreinformation,refertoOptimizingthePrintingUsingRules.
SettingthePrintedPageWhiteSpace
Youcancustomizethemarginsoftheprintedpageandyoucancentertheprintedpage.
RefertothefollowingfigurefordefinitionsofthepropertiesofthePrintMargin('PrintMarginClass'intheon-linedocumentation)object.
Spread Windows Forms Developer’s Guide 564
Copyright © GrapeCity, Inc. All rights reserved.
ThePrintInfoMargin('MarginProperty'intheon-linedocumentation)propertyusesaPrintMargin('PrintMarginClass'intheon-linedocumentation)object.Whenyouusethisobjectincode,theunitsofmeasureare100-thsofaninch,so3/4ofaninchwouldbe75.
WhenyouusetheSpreadDesignerandsetthemarginsintheSheet>PrintSettings>Marginstab,theunitsofmeasureareinches,so3/4ofaninchwouldbe0.75.
Thereareseveralwaystocontrolthejustificationofcontentsonthepagewhenprinting.
YoucansetthePrintInfoCentering('CenteringProperty'intheon-linedocumentation)property.
CreatingaShadowforthePrintedPage
Oneofthecustomizationsofthepagelayoutistheabilitytoprintshadows.
YoucansetthePrintInfoShowShadows('ShowShadowsProperty'intheon-linedocumentation)property.
ScalingthePrinting
Thereareseveralwaystocontrolthescalingoftheprinting.
YoucansetthePrintInfoZoomFactor('ZoomFactorProperty'intheon-linedocumentation)property.
TheZoomFactorandthezoomwithinthepreviewaredifferentscalingmechanisms.TheZoomFactorintheprintlayouteffectsthesizeoftheactualdisplayandtheprintoutsize.Thezoomwithintheprintpreviewdialogissimplyatemporaryzoominthedisplaybutisnotsavedforanyprinting.
Currentlythereisnomeansofadjustingthedefaultzoominthepreview.
YoucanuseScaleRule,whichisaSmartPrintrule.Formoreinformation,refertoOptimizingthePrintingUsingRules.
Spread Windows Forms Developer’s Guide 565
Copyright © GrapeCity, Inc. All rights reserved.
Customizing the Printed Page Header or Footer
Youcanprovideheaderandfootersthatappearsontheprintedpages.UsingtheHeader('HeaderProperty'intheon-linedocumentation)propertyandFooter('FooterProperty'intheon-linedocumentation)propertyofthePrintInfo('PrintInfoClass'intheon-linedocumentation)class,whichmayincludespecialcontrolcommands,youcanspecifytextandvariables,suchaspagenumbers,aswellasspecifythefontsettings.Thefontrelatedcommandsbeginwith"f".
Thecontrolcommandsthatcanbeinsertedinheadersandfootersarelistedinthistable:
ControlCharacter
FullCommand
ActioninPrintedPageHeaderorFooter
/ / Insertsaliteralforwardslashcharacter(/)
/c /c Centerjustifiestheitem
/cl /cl"n" Setsthefontcolorfortext,withthezero-basedindexofthecolor,n,inquotes(ncanbe0ormore);seetheColors('ColorsProperty'intheon-linedocumentation)property
/dl /dl Insertsthedate,usingthelongform
/ds /ds Insertsthedate,usingtheshortform
/f /f"n" Recallsthepreviouslysavedfontsettings(see/fsinthistable),withthezero-basedindex,n,inquotes(ncanbe0ormore)
/fb /fb0 Turnsoffboldfonttype
/fb1 Turnsonboldfonttype
/fi /fi0 Turnsoffitalicsfonttype
/fi1 Turnsonitalicsfonttype
/fk /fk0 Turnsoffstrikethrough
/fk1 Turnsonstrikethrough
/fn /fn"name" Setsthenameofthefontface,withthenameofthefontinquotes
/fs /fs"n" Savesthefontsettingsforre-use,withthezero-basedindexofthefontsettings,n,inquotes(see/finthistable)
/fu /fu0 Turnsoffunderline
/fu1 Turnsonunderline
/fz /fz"n" Setthesizeofthefont
/g /g"n" Insertsagraphic(image),withthezero-basedindexoftheimage,n,inquotes(ncanbezeroormore);seetheImages('ImagesProperty'intheon-linedocumentation)property
/l /l Leftjustifiestheitem(thatistheletterlorL,asinLeft)
/n /n Insertsanewline
/p /p Insertsapagenumber
/pc /pc Insertsapagecount(thetotalnumberofpagesintheprintjob)
/r /r Rightjustifiestheitem
/sn /sn Insertsthesheetname
Spread Windows Forms Developer’s Guide 566
Copyright © GrapeCity, Inc. All rights reserved.
/tl /tl Insertsthetime,usingthelongform
/ts /ts Insertsthetime,usingtheshortform
Ifyouusemultiplecontrolcharacters,donotputspacesbetweenthem.Theletterscanbeloweroruppercase;allcommandsandexamplesareshownhereinlowercaseforsimplicity.
Definetheheadersandfooters(settheHeader('HeaderProperty'intheon-linedocumentation)andFooter('FooterProperty'intheon-linedocumentation)properties)beforeprintingthesheet(runningthePrintSheet('PrintSheetMethod'intheon-linedocumentation)method).
YoucanspecifyacolorforthetextfromalistofcolorsifthecolorispreviouslydefinedintheColorsproperty.
YoucanspecifyanimageiftheimageispreviouslydefinedintheImagesproperty.
Youcanaddtextincludingthepagenumberandthetotalnumberofpagesprinted.
Youcansavethefontsettingstore-usethemlaterintheheaderorfooter.
Hereistheresultoftheexamplecodegivenbelow.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetforwhichtosettheheaderandfootertext.5. Inthepropertieslist,double-clickthePrintInfopropertytodisplaythesettingsforthePrintInfoclass.6. SettheHeaderandFooterpropertiestosettheheaderandfootertext.7. ClickOKtoclosetheeditor.
UsingaShortcut
1. CreateandsettheHeader('HeaderProperty'intheon-linedocumentation)andFooter('FooterProperty'intheon-linedocumentation)propertiesforaPrintInfo('PrintInfoClass'intheon-linedocumentation)object.
2. SettheSheetshortcutobjectPrintInfo('PrintInfoProperty'intheon-linedocumentation)propertytothePrintInfo('PrintInfoClass'intheon-linedocumentation)objectyoujustcreated.
Spread Windows Forms Developer’s Guide 567
Copyright © GrapeCity, Inc. All rights reserved.
Example
Thisexamplecodeprintsthesheetwiththespecifiedheaderandfootertext.
C#// Create PrintInfo object and set properties.FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();printset.Colors = new Color[] {Color.Green, Color.Yellow, Color.Gold, Color.Indigo, Color.Brown};printset.Images = new Image[] {Image.FromFile("C:\\images\\point.jpg"), Image.FromFile("C:\\images\\logo.gif"), Image.FromFile("C:\\images\\icon.jpg")};printset.Header = "/fn\"Book Antiqua\" /fz\"14\" Print job for FarPoint Inc./n ";printset.Footer = "/g\"1\"/r/cl\"4\"This is page /p of /pc";// Set the PrintInfo property for the first sheet.fpSpread1.Sheets[0].PrintInfo = printset;// Print the sheet.fpSpread1.PrintSheet(0);
VB' Create PrintInfo object and set properties.Dim printset As New FarPoint.Win.Spread.PrintInfo()printset.Colors = New Color() {Color.Green, Color.Yellow, Color.Gold, Color.Indigo, Color.Brown}printset.Images = New Image() {Image.FromFile("D:\images\point.jpg"), Image.FromFile("D:\images\logo.gif"), Image.FromFile("C:\images\icon.jpg")}printset.Header = "/fn""Book Antiqua"" /fz""14"" Print job for FarPoint Inc./n "printset.Footer = "/g""1""/r/cl""4""This is page /p of /pc"' Set the PrintInfo property for the first sheet.FpSpread1.Sheets(0).PrintInfo = printset' Print the sheet.FpSpread1.PrintSheet(0)
UsingCode
1. CreateandsettheHeader('HeaderProperty'intheon-linedocumentation)andFooter('FooterProperty'intheon-linedocumentation)propertiesforaPrintInfo('PrintInfoClass'intheon-linedocumentation)object.
2. SettheSheetViewobjectPrintInfo('PrintInfoProperty'intheon-linedocumentation)propertytothePrintInfo('PrintInfoClass'intheon-linedocumentation)objectyoujustcreated.
Example
Thisexamplecodeprintsthesheetwiththespecifiedheaderandfootercolorsandimages.
C#// Create PrintInfo object and set properties.FarPoint.Win.Spread.PrintInfo pi = new FarPoint.Win.Spread.PrintInfo();pi.Footer = "This is Page /p/nof /pc Pages";pi.Header = "Print Job For /nFPT Inc.";pi.Colors = new Color[] {Color.Red, Color.Blue};pi.Images = new Image[] {Image.FromFile("D:\Corporate.jpg"), Image.FromFile("D:\Building.jpg")};pi.RepeatColEnd = 25;
Spread Windows Forms Developer’s Guide 568
Copyright © GrapeCity, Inc. All rights reserved.
pi.RepeatColStart = 1;pi.RepeatRowEnd = 25;pi.RepeatRowStart = 1;fpSpread1.ActiveSheet.PrintInfo = pi;
VB' Create PrintInfo object and set properties.Dim pi As New FarPoint.Win.Spread.PrintInfopi.Footer = "This is Page /p/nof /pc Pages"pi.Header = "Print Job For /nFPT Inc."pi.Colors = New Color() {Color.Red, Color.Blue}pi.Images = New Image() {Image.FromFile("D:\Corporate.jpg"), Image.FromFile("D:\Building.jpg")}pi.RepeatColEnd = 25pi.RepeatColStart = 1pi.RepeatRowEnd = 25pi.RepeatRowStart = 1FpSpread1.ActiveSheet.PrintInfo = pi
UsingCode
1. CreateandsettheHeader('HeaderProperty'intheon-linedocumentation)andFooter('FooterProperty'intheon-linedocumentation)propertiesforaPrintInfo('PrintInfoClass'intheon-linedocumentation)object.
2. SettheSheetViewobjectPrintInfo('PrintInfoProperty'intheon-linedocumentation)propertytothePrintInfo('PrintInfoClass'intheon-linedocumentation)objectyoujustcreated.
Example
Thisexamplecodeprintsthesheetwiththespecifiedheaderandfootertext.
C#// Create PrintInfo object and set properties.FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();printset.Header = "/lJobName";printset.Footer = "/r/p of /pc";// Create SheetView object and assign it to the first sheet.FarPoint.Win.Spread.SheetView SheetToPrint = new FarPoint.Win.Spread.SheetView();SheetToPrint.PrintInfo = printset;// Set the PrintInfo property for the first sheet.fpSpread1.Sheets[0] = SheetToPrint;// Print the sheet.fpSpread1.PrintSheet(0);
VB' Create PrintInfo object and set properties.Dim printset As New FarPoint.Win.Spread.PrintInfo()printset.Header = "/lJobName"printset.Footer = "/r/p of /pc"' Create SheetView object and assign it to the first sheet.Dim SheetToPrint As New FarPoint.Win.Spread.SheetView()SheetToPrint.PrintInfo = printsetFpSpread1.Sheets(0) = SheetToPrint
Spread Windows Forms Developer’s Guide 569
Copyright © GrapeCity, Inc. All rights reserved.
' Set the PrintInfo property for the first sheet.FpSpread1.Sheets(0).PrintInfo = printset' Print the sheet.FpSpread1.PrintSheet(0)
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosetprintsettings.2. SelectthePageLayoutoption.3. ChoosePrintTitles.
TheSheetPrintdialogappears.
4. ClicktheHeader/Footertab.5. SelecttheHeaderorFooterradiobuttontoindicatewhetheryouaresettingtheheaderorfootertext.6. Typethetextforyourheaderorfooterinthetextbox.
YoucaninsertcontrolcharactersinyourtextbyselectingthemfromtheControlCharactersdrop-downlistboxbelowthetextboxandthenclickingtheAddbutton.
7. ClickOKtoclosetheSheetPrintOptionsdialog.8. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Repeating Rows or Columns on Printed Pages
Youcanspecifythatrowsappearatthetopofeveryprintedpageorspecifythatcolumnsappearontheleftsideofeveryprintedpage.UsetheRepeatRowStart('RepeatRowStartProperty'intheon-linedocumentation),RepeatRowEnd('RepeatRowEndProperty'intheon-linedocumentation),RepeatColStart('RepeatColStartProperty'intheon-linedocumentation),andRepeatColEnd('RepeatColEndProperty'intheon-linedocumentation)propertiesofthePrintInfo('PrintInfoClass'intheon-linedocumentation)object.
UsingCode
1. UsetherepeatpropertiesofthePrintInfoobject.2. UsethePrintSheet('PrintSheetMethod'intheon-linedocumentation)methodtoprintthesheet.
Example
Thisexamplesetstherepeatoptionsandusesapreviewdialog.
C#FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();printset.RepeatColStart = 0;printset.RepeatColEnd = 2;printset.RepeatRowStart = 0;printset.RepeatRowEnd = 2;printset.Preview = true;fpSpread1.Sheets[0].PrintInfo = printset;fpSpread1.PrintSheet(0);
VBDim printset As New FarPoint.Win.Spread.PrintInfoprintset.RepeatColStart = 0printset.RepeatColEnd = 2
Spread Windows Forms Developer’s Guide 570
Copyright © GrapeCity, Inc. All rights reserved.
printset.RepeatRowStart = 0printset.RepeatRowEnd = 2printset.Preview = TrueFpSpread1.Sheets(0).PrintInfo = printsetFpSpread1.PrintSheet(0)
Adding a Page Break
Youcanaddaforcepagebreakbeforeaspecifiedcolumnorrow.Pagebreaksarenotdisplayedonthescreenbutforcepagebreakswhenthesheetisprinted.Acolumnpagebreakoccurstotheleftofthespecifiedcolumn.Arowpagebreakoccursabovethespecifiedrow.Toaddorsetthepagebreaks,usetheSetRowPageBreak('SetRowPageBreakMethod'intheon-linedocumentation)andSetColumnPageBreak('SetColumnPageBreakMethod'intheon-linedocumentation)methods.
Youcanalsoretrievethenumberofthenextcolumnorrowinthesheetwhereapagebreakoccurs.Tofindthepagebreaksthatarealreadyset,usetheGetRowPageBreaks('GetRowPageBreaksMethod'intheon-linedocumentation)methodtoreturnthenumberofrowpagebreaksandusetheGetColumnPageBreaks('GetColumnPageBreaksMethod'intheon-linedocumentation)methodtoreturnthenumberofcolumnpagebreaks.
YoucancalculatethenumberofprintedpagesforthesheetusingtheGetPrintPageCount('GetPrintPageCountMethod'intheon-linedocumentation)method.
UsingCode
1. UsetheSetRowPageBreak('SetRowPageBreakMethod'intheon-linedocumentation)methodonthesheettosettherowpagebreak.
2. UsetheGetRowPageBreaks('GetRowPageBreaksMethod'intheon-linedocumentation)methodtogetthepagebreaks.
Example
Thisexamplesetsarowpagebreakandgetstherownumbersfortherowpagebreaks.
C#// Add this code to the form load.FarPoint.Win.Spread.PrintInfo pi = new FarPoint.Win.Spread.PrintInfo();pi.UseMax =false;fpSpread1.Sheets[0].PrintInfo = pi;fpSpread1.Sheets[0].SetRowPageBreak(5,true);// Add this code to a button click event.int []i;i = fpSpread1.GetRowPageBreaks(0);foreach (object o in i){ listBox1.Items.Add(o);}
VB' Add this code to the form load event.Dim pi As New FarPoint.Win.Spread.PrintInfo()pi.UseMax = FalseFpSpread1.Sheets(0).PrintInfo = piFpSpread1.Sheets(0).SetRowPageBreak(5, True)
Spread Windows Forms Developer’s Guide 571
Copyright © GrapeCity, Inc. All rights reserved.
' Add this code to a button click event.Dim i() As IntegerDim o As Objecti = FpSpread1.GetRowPageBreaks(0)For Each o In i ListBox1.Items.Add(o)Next
Adding a Watermark to a Printed Page
Youcanprintabackgroundimageorawatermarkwhenthespreadsheetisprinted.
SetthePrintBackground('PrintBackgroundEvent'intheon-linedocumentation)eventtofirewhenprinting,andspecifythegraphicwiththePrintBackgroundevent,andtheopacitywiththePrintInfo.Opacity('OpacityProperty'intheon-linedocumentation)property,sotheprintingofthespreadsheethasnowatermarkifopacityishighest(transparencyislowest)andshowsthewatermarkthroughthespreadsheetiftheopacityislow(transparencyishigh).
UsingCode
UsethePrintInfo('PrintInfoClass'intheon-linedocumentation)objecttospecifytheopacityforprintingawatermark.
Example
Thisexampleshowshowtoprintawatermark.
C#private void fpSpread1_PrintBackground(object sender, FarPoint.Win.Spread.PrintBackgroundEventArgs e){ FarPoint.Win.Picture pic = new FarPoint.Win.Picture(System.Drawing.Image.FromFile("D:\\Files\\cover.jpg"), FarPoint.Win.RenderStyle.Normal); pic.AlignHorz = FarPoint.Win.HorizontalAlignment.Left; pic.AlignVert = FarPoint.Win.VerticalAlignment.Top; pic.Paint(e.Graphics, e.SheetRectangle);}
private void button1_Click(object sender, System.EventArgs e){ FarPoint.Win.Spread.PrintInfo pi = new FarPoint.Win.Spread.PrintInfo(); pi.Opacity = 100; fpSpread1.ActiveSheet.PrintInfo = pi; fpSpread1.PrintSheet(0);}
VBPrivate Sub FpSpread1_PrintBackground(ByVal sender As Object, ByVal e As FarPoint.Win.Spread.PrintBackgroundEventArgs) Handles FpSpread1.PrintBackground Dim pic As New FarPoint.Win.Picture(Image.FromFile("D:\Files\cover.jpg"), FarPoint.Win.RenderStyle.Normal) pic.AlignHorz = FarPoint.Win.HorizontalAlignment.Left
Spread Windows Forms Developer’s Guide 572
Copyright © GrapeCity, Inc. All rights reserved.
pic.AlignVert = FarPoint.Win.VerticalAlignment.Top pic.Paint(e.Graphics, e.SheetRectangle)End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim pi As New FarPoint.Win.Spread.PrintInfo() pi.Opacity = 100 FpSpread1.ActiveSheet.PrintInfo = pi FpSpread1.PrintSheet(0)End Sub
Optimizing the Printing
ThereareafewwaystoletSpreadhandletheprintingandoptimizetheprintingforyou.YoucanletSpreaddeterminetheoptimumwayusingrules,asetofalgorithmstocalculatethebestwaytoscaleandfityourprinting,orletSpreaddeterminethebiggestcolumnorrowandhandletheprintingbasedonthat.
Thetasksinvolvedwithoptimizingtheprintinginclude:
OptimizingthePrintingUsingRulesOptimizingthePrintingUsingSize
Optimizing the Printing Using Rules
Spreadprovidesawaytoautomaticallydeterminethebestwaytoprintyoursheet.Byusingrulesthatyoucanchoose,itcandecide,forexample,whetheritisbesttoprintyoursheetonlandscape-orportrait-orientedpages.
Therules,thatyoucanturnonoroff,thatoptimizetheprintingcanbecustomizedbysettingthepropertiesoftheseruleobjects:
RuleObject DescriptionLandscapeRule('LandscapeRuleClass'intheon-linedocumentation)
Determineswhethertoprintthesheetinlandscapeorportraitorientation.
ScaleRule('ScaleRuleClass'intheon-linedocumentation)
Determinesthebestscaleatwhichtoprintthesheet,startingwith100%(StartFactor=1),anddecreasingatsetintervalstoaminimumsize(EndFactor).DefaultsettingsareStartFactor=1,EndFactor=0.6,andInterval=0.1.
BestFitColumnRule('BestFitColumnRuleClass'intheon-linedocumentation)
Determineshowbesttofitthecolumnsinthesheetonthepage.
Bydefault,optimizingtheprintingofthesheetusesthefollowinglogic:
IftheinformationcanbeprintedwithoutmakinganychangestothesettingsthatyouhavedefinedinthePrintInfo('PrintInfoClass'intheon-linedocumentation)object,thesheetprintsinportraitmode.Ifthesheetiswiderthanaportraitpage,thesheetprintsinlandscapemode.Iftheinformationdoesnotfitinlandscapemode,butdoesfitinlandscapemodeifthesheetisreducedupto60%ofitsoriginalsize,thesheetisscaledtofitwithinthepage.Iftheinformationcannotbescaledtofit,thesheettriestoreducecolumnwidthstoaccommodatethewideststringwithineachcolumn.Ifallattemptstomakethesheetprintwithinapagefail,printingresumesnormallyinthecurrentprinter
Spread Windows Forms Developer’s Guide 573
Copyright © GrapeCity, Inc. All rights reserved.
orientationwithnoreductions.
Youcancustomizehowthislogicisappliedthroughtheruleobjects.Ifyoucustomizetheruleobject,thedefaultrulesareignoredandonlythecustomrulesareusedforprinting.YoucansetupacollectionoftheseruleswiththeSmartPrintRulesCollection('SmartPrintRulesCollectionClass'intheon-linedocumentation)objectandsetwhethertousetheseruleswiththeUseSmartPrint('UseSmartPrintProperty'intheon-linedocumentation)property.
UsingthePropertiesWindow
1. Atdesigntime,inthePropertieswindow,selecttheSpreadcomponent.2. SelecttheSheetsproperty.3. ClickthebuttontodisplaytheSheetViewCollectionEditor.4. IntheMemberslist,selectthesheetforwhichtouseSmartPrint.5. Inthepropertieslist,double-clickthePrintInfopropertytodisplaythesettingsforthePrintInfoclass.6. SettheUseSmartPrintpropertytotrue.7. IfyouwanttocustomizetheSmartPrintrules,selecttheSmartPrintRulesandclickthebuttontodisplaytheSmartPrintRuleCollectionEditor.Customizetherulesasyouwant,thenclickOKtoclosetheSmartPrintRuleCollectionEditor.
8. ClickOKtoclosetheSheetViewCollectioneditor.
UsingaShortcut
1. CreateaPrintInfo('PrintInfoClass'intheon-linedocumentation)object.2. IfyouwanttochangehowSmartPrintdetermineshowbesttoprintthesheet,createanewSmartPrintRulesCollection('SmartPrintRulesCollectionClass'intheon-linedocumentation)object.
3. SetthePrintInfo('PrintInfoClass'intheon-linedocumentation)objectUseSmartPrint('UseSmartPrintProperty'intheon-linedocumentation)propertytotrue.
4. SettheSheetsshortcutobjectPrintInfo('PrintInfoProperty'intheon-linedocumentation)propertytothePrintInfo('PrintInfoClass'intheon-linedocumentation)objectyoujustcreated.
Example
Thisexamplecodeprintsusingcustomizedprintrules,setupintheSmartPrintRulesCollection('SmartPrintRulesCollectionClass'intheon-linedocumentation)object.Inthisexample,ifthesheetdoesfitonapagebyshrinkingcolumnstothelongesttextstring,itprintswiththecolumnsshrunk.Ifitdoesnotfitwiththecolumnsshrunk,itkeepsthemshrunkandtriestoprintinlandscapeorientation.Ifitdoesnotfitwiththecolumnsshrunkandinlandscapeorientation,itkeepsthesesettingsandtriestoscalethesheet,startingat100%,thendecreasingby20%intervalsdownto40%.
C#// Create the print rules.FarPoint.Win.Spread.SmartPrintRulesCollection printrules = new FarPoint.Win.Spread.SmartPrintRulesCollection();printrules.Add(new FarPoint.Win.Spread.BestFitColumnRule(FarPoint.Win.Spread.ResetOption.None));printrules.Add(new FarPoint.Win.Spread.LandscapeRule(FarPoint.Win.Spread.ResetOption.None));printrules.Add(new FarPoint.Win.Spread.ScaleRule(FarPoint.Win.Spread.ResetOption.All, 1.0f, .4f, .2f));// Create a PrintInfo object and set the properties.FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();printset.SmartPrintRules = printrules;
Spread Windows Forms Developer’s Guide 574
Copyright © GrapeCity, Inc. All rights reserved.
printset.UseSmartPrint = true;// Set the PrintInfo property for the first sheet.fpSpread1.Sheets[0].PrintInfo = printset;// Print the sheet.fpSpread1.PrintSheet(0);
VB' Create the print rules.Dim printrules As New FarPoint.Win.Spread.SmartPrintRulesCollection()printrules.Add(New FarPoint.Win.Spread.BestFitColumnRule(FarPoint.Win.Spread.ResetOption.None))printrules.Add(New FarPoint.Win.Spread.LandscapeRule(FarPoint.Win.Spread.ResetOption.None))printrules.Add(New FarPoint.Win.Spread.ScaleRule(FarPoint.Win.Spread.ResetOption.All, 1.0F, 0.4F, 0.2F))' Create a PrintInfo object and set the properties.Dim printset As New FarPoint.Win.Spread.PrintInfo()printset.SmartPrintRules = printrulesprintset.UseSmartPrint = True' Set the PrintInfo property for the first sheet.FpSpread1.Sheets(0).PrintInfo = printset' Print the sheet.FpSpread1.PrintSheet(0)
UsingCode
1. CreateaPrintInfo('PrintInfoClass'intheon-linedocumentation)object.2. IfyouwanttochangehowSmartPrintdetermineshowbesttoprintthesheet,createanewSmartPrintRulesCollection('SmartPrintRulesCollectionClass'intheon-linedocumentation)object.
3. SetthePrintInfo('PrintInfoClass'intheon-linedocumentation)objectUseSmartPrint('UseSmartPrintProperty'intheon-linedocumentation)propertytotrue.
4. SettheSheetView('SheetViewClass'intheon-linedocumentation)objectPrintInfo('PrintInfoProperty'intheon-linedocumentation)propertytothePrintInfo('PrintInfoClass'intheon-linedocumentation)objectyoujustcreated.
Example
Thisexamplecodeprintsusingcustomizedprintrules,setupintheSmartPrintRulesCollection('SmartPrintRulesCollectionClass'intheon-linedocumentation)object.Inthisexample,ifthesheetdoesfitonapagebyshrinkingcolumnstothelongesttextstring,itprintswiththecolumnsshrunk.Ifitdoesnotfitwiththecolumnsshrunk,itkeepsthemshrunkandtriestoprintinlandscapeorientation.Ifitdoesnotfitwiththecolumnsshrunkandinlandscapeorientation,itkeepsthesesettingsandtriestoscalethesheet,startingat100%,thendecreasingby20%intervalsdownto40%.
C#// Create the print rules.FarPoint.Win.Spread.SmartPrintRulesCollection printrules = new FarPoint.Win.Spread.SmartPrintRulesCollection();printrules.Add(new FarPoint.Win.Spread.BestFitColumnRule(FarPoint.Win.Spread.ResetOption.None));printrules.Add(new FarPoint.Win.Spread.LandscapeRule(FarPoint.Win.Spread.ResetOption.None));printrules.Add(new FarPoint.Win.Spread.ScaleRule(FarPoint.Win.Spread.ResetOption.All,
Spread Windows Forms Developer’s Guide 575
Copyright © GrapeCity, Inc. All rights reserved.
1.0f, .4f, .2f));// Create a PrintInfo object and set the properties.FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();printset.SmartPrintRules = printrules;printset.UseSmartPrint = true;// Create a SheetView object and assign it to the first sheet.FarPoint.Win.Spread.SheetView SheetToPrint = new FarPoint.Win.Spread.SheetView();SheetToPrint.PrintInfo = printset;fpSpread1.Sheets[0] = SheetToPrint;// Print the sheet.fpSpread1.PrintSheet(0);
VB' Create the print rules.Dim printrules As New FarPoint.Win.Spread.SmartPrintRulesCollection()printrules.Add(New FarPoint.Win.Spread.BestFitColumnRule(FarPoint.Win.Spread.ResetOption.None))printrules.Add(New FarPoint.Win.Spread.LandscapeRule(FarPoint.Win.Spread.ResetOption.None))printrules.Add(New FarPoint.Win.Spread.ScaleRule(FarPoint.Win.Spread.ResetOption.All, 1.0F, 0.4F, 0.2F))' Create a PrintInfo object and set the properties.Dim printset As New FarPoint.Win.Spread.PrintInfo()printset.SmartPrintRules = printrulesprintset.UseSmartPrint = True' Create a SheetView object and assign it to the first sheet.Dim SheetToPrint As New FarPoint.Win.Spread.SheetView()SheetToPrint.PrintInfo = printsetFpSpread1.Sheets(0) = SheetToPrint' Print the sheet.FpSpread1.PrintSheet(0)
UsingtheSpreadDesigner
1. Selectthesheettabforthesheetforwhichyouwanttosetprintsettings.2. SelectthePageLayoutoption.3. ClicktheSmartPrinttab.4. SelecttheUseSmartPrintcheckboxifyouwanttoprintusingtheSmartPrintfeature.5. ThedefaultprintingrulesforSmartPrintarelistedinthetextbox.Ifyouwanttodoso,deletethoserulesbyclickingtheDeletebutton,thenusethecontrolsbelowthetextboxtoaddrulesandruleoptions.
6. ClickOKtoclosetheSheetPrintOptionsdialog.7. FromtheFilemenuchooseApplyandExittoapplyyourchangestothecomponentandexitSpreadDesigner.
Optimizing the Printing Using Size
Spreadprovidesawaytoautomaticallydeterminethebestwaytoprintyoursheet.Byusingrulesthatyoucanchoose,itcandecide,forexample,whetheritisbesttoprintyoursheetonlandscape-orportrait-orientedpages.SeeOptimizingthePrintingUsingRulesformoreinformation.
YoucansetBestFitCols('BestFitColsProperty'intheon-linedocumentation)andBestFitRows('BestFitRowsProperty'intheon-linedocumentation)properties.
Spread Windows Forms Developer’s Guide 576
Copyright © GrapeCity, Inc. All rights reserved.
Displaying Dialogs for Users
Spreadprovidesawayforyoutodisplayaprintdialogandaprintpreviewdialogtoallowyourenduserstosetvariousoptionsforprinting.
DisplayingaPrintDialogfortheUserDisplayinganAbortMessagefortheUserProvidingaPreviewofthePrinting
Displaying a Print Dialog for the User
Spreadprovidesawayforyoutodisplayaprintdialogtoallowyourendusertosetvariousoptionsontheprinting.SettheShowPrintDialog('ShowPrintDialogProperty'intheon-linedocumentation)propertyofthePrintInfo('PrintInfoClass'intheon-linedocumentation)object.
Displaying an Abort Message for the User
Spreadprovidesawayforyoutodisplayanabortmessagetoallowyourenduserachancetocancelorcontinuewiththeprinting.
Formoreinformation,refertothefollowing:
PrintAbortEventArgs('PrintAbortEventArgsClass'intheon-linedocumentation)classPrintMessageBoxEventArgs('PrintMessageBoxEventArgsClass'intheon-linedocumentation)classPrintInfo('PrintInfoClass'intheon-linedocumentation)class,AbortMessagepropertyFpSpread('FpSpreadClass'intheon-linedocumentation)class,PrintMessageBoxevent,PrintAbortEvent,andPrintCancelledEvent
UsingCode
1. CreateandsettheAbortMessagepropertyforaPrintInfo('PrintInfoClass'intheon-linedocumentation)object.
2. SettheSheetViewobjectPrintInfo('PrintInfoProperty'intheon-linedocumentation)propertytothePrintInfo('PrintInfoClass'intheon-linedocumentation)objectyoujustcreated.
Example
Thisexamplebringsupthecanceldialog.
C#FarPoint.Win.Spread.PrintInfo pi = new FarPoint.Win.Spread.PrintInfo();pi.AbortMessage = "Do you want to cancel printing??";fpSpread1.ActiveSheet.PrintInfo = pi;fpSpread1.PrintSheet(0);
VBDim pi As New FarPoint.Win.Spread.PrintInfopi.AbortMessage = "Do you want to cancel printing??"FpSpread1.Sheets(0).PrintInfo = pi' Print the sheetFpSpread1.PrintSheet(0)
Spread Windows Forms Developer’s Guide 577
Copyright © GrapeCity, Inc. All rights reserved.
Providing a Preview of the Printing
Youcanpreviewwhattheprintedpageswilllooklikeforasheetandyoucanallowyourendusertopreviewtheprinting.
YoucanusethePreview('PreviewProperty'intheon-linedocumentation)propertyinthePrintInfo('PrintInfoClass'intheon-linedocumentation)classtopreviewasheet.
ThefollowingimageshowsthebasicPrintPreviewDialogthatappearsonyourscreen.
UsetheOwnerPrintDraw('OwnerPrintDrawMethod'intheon-linedocumentation)methodoftheFpSpread('FpSpreadClass'intheon-linedocumentation)classtoprovideaprintpreviewdialogwithoptionsforpreviewingthepagesbeforeprinting.
UsetheShowPageSetupButton('ShowPageSetupButtonProperty'intheon-linedocumentation)propertyofthePrintInfo('PrintInfoClass'intheon-linedocumentation)classtoshowthePageSetUpbuttononthetoolbarofthePrintPreviewDialog.Withthisbutton,youcansettheorientation(portraitandlandscape)andmarginsetc.ofthepageyouwanttoprint.
Twoadditionalprintingfeaturesare:thePrintPreviewShowing('PrintPreviewShowingEvent'intheon-linedocumentation)eventandtheabilitytosetyourownprintpreviewdialogwiththeSetPrintPreview('SetPrintPreviewMethod'intheon-linedocumentation)method(andthecorrespondingGetPrintPreview('GetPrintPreviewMethod'intheon-linedocumentation)method),allmembersoftheFpSpread('FpSpreadClass'intheon-linedocumentation)class.ThePrintPreviewShowing('PrintPreviewShowingEvent'intheon-linedocumentation)eventfirespriortodisplayingthedialogandsuppliesyouwithboththePreviewDialogandthePreviewControlinitseventparameterlistsoyoucanmakeon-the-flymodificationstothePrintPreviewDialogandthePrintPreviewControlobjects.
Theprintpreviewdialogallowsyoutozoominandouttochangethescaleofwhatyouseeinthepreview.Youcansetthepreviewtodisplayone,two,four,orsixpagesofthespreadsheetperprintedpage.Youcanprintfromtheprintpreviewdialogorclosethedialogwhendone.
YoucanalsoprintandpreviewtheprintingwithintheSpreadDesigner.FormoreinformationonprintingandpreviewinginSpreadDesigner,refertoPrintingaSheetfromSpreadDesigner(on-linedocumentation)andPreviewingaSheetinSpreadDesigner(on-linedocumentation).
Spread Windows Forms Developer’s Guide 578
Copyright © GrapeCity, Inc. All rights reserved.
YoucanalsocustomizethePrintPreviewsettingstoshowthePrintPreviewDialoglikeExcel.Formoreinformation,refertoCustomizingthePrintPreviewDialog(on-linedocumentation).
UsingCode
SetthePreview('PreviewProperty'intheon-linedocumentation)propertyofthePrintInfo('PrintInfoClass'intheon-linedocumentation)classtotrueinordertoallowuserstopreviewspreadsheetsandseethemodificationsconcurrentlywhilethesettingsoftheprinterarebeingchanged.
Example
Thisexampleshowshowtoapplyprintersettingtoshowtheprintpreviewdialog.
C#//Code to show the print preview dialog
fpSpread1.ActiveSheet.Cells[1, 1].Value = "1,1";fpSpread1.ActiveSheet.Cells[10, 10].Value = "10,10";fpSpread1.ActiveSheet.PrintInfo.Preview = true;fpSpread1.PrintSheet(fpSpread1.ActiveSheet);
VB'Code to show print preview dialogfpSpread1.ActiveSheet.Cells(1, 1).Value = "1,1"fpSpread1.ActiveSheet.Cells(10, 10).Value = "10,10"fpSpread1.ActiveSheet.PrintInfo.Preview = TruefpSpread1.PrintSheet(fpSpread1.ActiveSheet)
Spread Windows Forms Developer’s Guide 579
Copyright © GrapeCity, Inc. All rights reserved.
Working with the Chart Control
ThefollowingtopicsexplainthebasicsoftheChartcontrolandhowtousethecontrol:
UnderstandingChartsCreatingCharts
Understanding Charts
Thefollowingtopicsexplainthevariouschartelementsandformattingoptions.
ChartUserInterfaceElementsChartObjectModelChartTypesandViewsPlotTypesPlotsandSeriesWallsAxisandOtherLinesFillEffectsChartLineStyleElevationandRotationLighting,Shapes,andBordersSize-Height,Width,andDepthLabelsLegends
Chart User Interface Elements
Hereisabriefsummaryoftheelementsofthecanvas(chartview)ofthechart.
Thisdiagramshowsthepartsofthecanvas:
Spread Windows Forms Developer’s Guide 580
Copyright © GrapeCity, Inc. All rights reserved.
Therearethreemainelementsinthechart:
LabelArea('LabelAreaClass'intheon-linedocumentation)-Labelscontaintheplottitleandtheaxislabels.LegendArea('LegendAreaClass'intheon-linedocumentation)-Legendscontainidentifiersforeachoftheseriesofdata.PlotArea('PlotAreaClass'intheon-linedocumentation)-Theplotconsistsofdatadisplayedinoneofseveralplottypes.Formoreinformationaboutplottypes,refertoPlotTypes.Ontheplotareseveralgraphicalelementssuchasgridlines,tickmarks,stripes,andwalls.
Elementsarepositionedusingarelativelocation,where(0,0)istheupperleftcornerofthechartand(1,1)isthelowerrightcornerofthechartandarelativealignment,where(0,0)istheupperleftcorneroftheelementand(1,1)isthelowerrightcorneroftheelement.
Chart Object Model
Hereisabriefsummaryoftheobjectmodelofthechart.
Thisdiagramshowstheobjectmodel:
Spread Windows Forms Developer’s Guide 581
Copyright © GrapeCity, Inc. All rights reserved.
Basicallythereisachartviewthatcanbeplatformspecific.Thischartviewisdependentonthechartmodel,whichisplatformindependent.
Themodelinturnismadeupoffourmajorobjects:
PlotAreaCollection('PlotAreaCollectionClass'intheon-linedocumentation)LegendAreaCollection('LegendAreaCollectionClass'intheon-linedocumentation)PlotAreaCollection('PlotAreaCollectionClass'intheon-linedocumentation)Fill('FillClass'intheon-linedocumentation)
Chart Types and Views
Thechartcontrolhasseveralcharttypesandeachtypehasadditionalviews.
Thefollowingisalistofthecharttypes:
AreaBar
Spread Windows Forms Developer’s Guide 582
Copyright © GrapeCity, Inc. All rights reserved.
BoxWhiskerBubbleColumnDoughnutFunnelHistogramLineParetoPiePolarRadarStockSunburstTreemapWaterfallXYXYZ
Thecolumntypehasthefollowingtypesofviews-ClusteredColumn,StackedColumn,100%StackedColumn,HighLowColumn,3DClusteredColumn,3DStackedColumn,100%3DStackedColumn,3DColumn,3DHighLowColumn,ClusteredCylinder,StackedCylinder,100%StackedCylinder,3DCylinder,HighLowColumnCylinder,ClusteredFullCone,StackedFullCone,100%StackedFullCone,3DFullCone,HighLowColumnFullCone,ClusteredFullPyramid,StackedFullPyramid,100%StackedFullPyramid,3DPyramid,andHighLowColumnPyramid.
Thelinetypehasthefollowingtypesofviews-Line,StackedLine,100%StackedLine,LinewithMarkers,StackedLinewithMarkers,100%StackedLinewithMarkers,and3DLine.
Thepietypehasthefollowingtypesofviews-2DPie,3DPie,2DExplodedPie,and3DExplodedPie.
Thebartypehasthefollowingtypesofviews-ClusteredBar,StackedBar,100%StackedBar,HighLowBar,3DClusteredBar,3DStackedBar,100%3DStackedBar,3DHighLowBar,ClusteredHorizontalCylinder,StackedHorizontalCylinder,100%StackedHorizontalCylinder,HighLowBarCylinder,ClusteredHorizontalFullCone,StackedHorizontalFullCone,100%StackedHorizontal,HighLowBarFullCone,ClusteredHorizontalFullPyramid,StackedHorizontalFullPyramid,100%StackedHorizontal,andHighLowBarPyramid.
Theareatypehasthefollowingtypesofviews-Area,StackedArea,100%StackedArea,HighLowArea,3DArea,3DStackedArea,100%3DStackedArea,and3DHighLowArea.
TheXYtypehasthefollowingtypesofviews-XYPoint,XYLine,andXYLinewithMarker.
Thebubbletypehasthefollowingtypesofviews-2DBubbleand3DBubble.
Thestocktypehasthefollowingtypesofviews-HighLowClose,OpenHighLowClose,andCandleStick.
TheXYZtypehasthefollowingtypesofviews-XYZLine,XYZLinewithMarker,XYZPoint,andSurface.
Thedoughnuttypehasthefollowingtypesofviews-DoughnutandExplodedDoughnut.
Theradartypehasthefollowingtypesofviews-RadarLine,RadarLinewithMarker,RadarPoint,andRadarArea.
Thepolartypehasthefollowingtypesofviews-PolarLine,PolarLinewithMarker,PolarPoint,andPolarArea.
Thereareseveralvisualelementstoachartsuchastheplot,legend,andlabelareas,theaxis,andtheseries.Thelabelareacontainsadditionalinformationaboutthechart.Thelegendcanbeusedtohelpendusersidentifydifferentchartelementssuchastheseries.Theaxisdisplaysthescaleforasingledimensionofaplotarea.Eachseriesisacollectionofdatapoints.Theplotareaistheareainwhichdatapointsaredrawn.
Spread Windows Forms Developer’s Guide 583
Copyright © GrapeCity, Inc. All rights reserved.
Plot Types
Aplotareaistheareainwhichdatapoints(bars,points,lines,etc)aredrawn.Aplotareawillcontainacollectionofseries.Eachseriesisacollectionofdatapoints.Aplotareamayalsocontainanaxis(s)andwall(s).Theaxis(s)andwall(s)enhancethevisualappearanceoftheplotareaandareusuallypaintedjustoutsidetheplotarea.
Aplotareacanbeassignedananchorviewlocationandaviewsize.Theanchorviewlocationisspecifiedinnormalizedunits((0,0)=leftuppercornerofchartview,(1,1)=rightlowercornerofchartview).Theviewsizeoftheplotareaisspecifiedinnormalizedunits((0,0)=zerosize,(1,1)=fullsizeofchartview).Thelefttopcorneroftheplotareaisalignedwiththeanchorlocation.
Aplotareacanbeassignedamodelsizeusingwidth,height,anddepthproperties.Thepropertiesusemodelunits.
Thereareseveralplottypes:Y,XY,XYZ,Pie,Polar,Radar,Data,Sunburst,andTreemap.
YPlotTypesXYPlotTypesXYZPlotTypesPiePlotTypesPolarPlotTypesRadarPlotTypesDataPlotTypes
Y Plot Types
Spread Windows Forms Developer’s Guide 584
Copyright © GrapeCity, Inc. All rights reserved.
TheYplotareacontainsseriesthathavevaluesinonedimension.
Whenvisualizedin2D,aYplotareatakestheformofarectanglewiththex-axisrepresentingcategoriesandthey-axisrepresentingvalues.
Whenvisualizedin3D,aYplotareatakestheformofacubewiththex-axisrepresentingcategories,they-axisrepresentingvalues,andthez-axis(depth)representingseries.
AYplotareacanbeorientedverticallyorhorizontally.Whenorientedvertically,thex-axisishorizontalandthey-axisisvertical.Whenorientedhorizontally,thex-axisisverticalandthey-axisishorizontal.
YoucanhaveanyofthesetypesofYplots.
AreaChartsBarChartsBoxWhiskerCharts(on-linedocumentation)FunnelCharts(on-linedocumentation)HistogramCharts(on-linedocumentation)LineChartsMarketData(High-Low)ChartsParetoCharts(on-linedocumentation)PointChartsStripeChartsWaterfallCharts(on-linedocumentation)
Area Charts
Theareachartcanbeabasicone-dimensionalCartesianplotsuchastheoneshowninthisfigure.
Spread Windows Forms Developer’s Guide 585
Copyright © GrapeCity, Inc. All rights reserved.
Youcanhaveanyofthesetypesofareacharts,whichrepresentdifferentwaysofdisplayingtheseriesdata.
(standard)AreaStackedAreaStacked100%(normalized)Area
AreaCharts
Eachpointinanareaseriescontainsasingledatavalue.Thedatavalueisvisualizedasapointonanarea.
Anareaseriescanhaveaborder,filleffect,depth,oranoriginforthearea.Youcanalsospecifywhethertheareaisjaggedorsmooth,andwhetherdroplinesaredisplayed.Assigningnullfortheborderorfilleffectindicatesthatthepropertyisunset.Depthismeasuredrelativetothefloorgridcell(0=nodepth,1=depthoffloorgridcell).Theorigincanbemarkedforautogenerationbythechartview,inwhichcasetheassignedoriginisignored.
Eachpointinanareaseriescanbeassignedaborderandafilleffectforthearea.
StackedAreaCharts
Thestackedareachartshowsthepointsverticallystacked:
Astackedareaseriesisacompositeseriesthatgroupstogethertwoormoreareaseries.
Astackedareaseriescanbeassignedaborder,filleffect,ordepthfortheareas.Youcanalsospecifywhethertheareaisjaggedorsmoothandwhetherdroplinesaredisplayed.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.Eachareaseriesinastackedareaseriescanbeassignedaborderandafilleffectforthearea.
Eachpointinanareaseriesinastackedareaserieshasasingledatavalue.Thedatavalueisvisualizedasapointonanarea.Eachpointinanareaseriesinastackedareaseriescanbeassignedaborderandafilleffectforthearea.
Stacked100%AreaCharts
Thestacked100%areachartshowsthepointsverticallystackedandspreadallthewaytothetop(100%)butspreadproportionately;otherwise,itissimilartoastackedareachart:
Spread Windows Forms Developer’s Guide 586
Copyright © GrapeCity, Inc. All rights reserved.
FormoreinformationontheareaseriesobjectintheAPI,refertotheAreaSeries('AreaSeriesClass'intheon-linedocumentation)class.
Bar Charts
Thebarchartisabasicone-dimensionalCartesianplotsuchastheoneshowninthisfigure.
Youcanhaveanyofthesetypesofbarcharts,whichrepresentdifferentwaysofdisplayingtheseriesdata.
(standard)BarMultipleBarClusterBarStackedBarStacked100%(normalized)Bar
BarCharts
Eachdatapointcontainsasinglevalue;howthebarforthatpointisdisplayedcanbecustomized.Barbordersandbarfilleffectscanbeassignedfortheseriesorforapointintheserieswithnull(NothinginVB)indicatingunassigned.Barwidthandbardeptharemeasuredrelativetothefloorgridcell(witharangeof0to1).Barorigincanbeautomaticallygeneratedormanuallyassigned.
YoucanalsodisplayanyofthebarchartsascolumnchartsbysettingtheVerticalpropertyintheYPlotArea('YPlotAreaClass'intheon-linedocumentation)classtoFalse.
ClusterBarCharts
Theclusterbarshowsthebarsalongsideeachotherhorizontally,clusteredbyseries:
Spread Windows Forms Developer’s Guide 587
Copyright © GrapeCity, Inc. All rights reserved.
Aclusterbarseriesisacompositeseriesthatgroupstogethertwoormorebarseries.Aclusterbarseriescanbeassignedaborder,filleffect,width,depth,andanoriginforthebarsaswellasawidthforthegroup.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.Groupwidthismeasuredrelativetothefloorgridcell(0=nowidth,1=widthoffloorgridcell).Barwidthismeasuredrelativetothewidthreservedforthegroupdividedbythenumberofseriesinthegroup(0=nowidth,1=widthreservedforthegroupdividedbythenumberofseriesinthegroup).Bardepthismeasuredrelativetothefloorgridcell(0=nodepth,1=depthoffloorgridcell).Theorigincanbemarkedforautogenerationbythechartview,inwhichcasetheassignedoriginisignored.
Eachbarseriesintheclusterbarseriescanbeassignedaborderandafilleffectforthebars.
Eachpointinabarseriesintheclusterbarserieshasasingledatavalue.Eachpointisvisualizedasabar.Allthebarsforagivencategoryareplacedsidebyside.Eachpointinabarseriesinaclusterbarseriescanhaveaborderandafilleffectforthebar.
StackedBarCharts
Thestackedbarshowsthebarsverticallystacked:
Spread Windows Forms Developer’s Guide 588
Copyright © GrapeCity, Inc. All rights reserved.
Astackedbarseriesisacompositeseriesthatgroupstogethertwoormorebarseries.Astackedbarseriescanbeassignedaborder,filleffect,width,andadepthforthebars.Youcanalsospecifywhetherthegroupshouldbedisplayed100%stacked.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.Widthanddeptharemeasuredrelativetothefloorgridcell(0=nowidthordepth,1=widthordepthoffloorgridcell).
Eachbarseriesinthestackedbarseriescanbeassignedaborderandafilleffectforthebars.
Eachpointinabarseriesinastackedbarserieshasasingledatavalue.Eachpointisvisualizedasabar.Allthebarsinagivencategoryarestackedvertically.Eachpointinabarseriesinastackedbarseriescanhaveaborderandafilleffectforthebar.
Stacked100%BarCharts
Thestacked100%barchartshowsthebarsverticallystackedandspreadallthewaytothetop(100%)butspreadproportionately;otherwise,itissimilartoastackedbarchart:
Spread Windows Forms Developer’s Guide 589
Copyright © GrapeCity, Inc. All rights reserved.
FormoreinformationonthebarseriesobjectintheAPI,refertotheBarSeries('BarSeriesClass'intheon-linedocumentation)class.
Line Charts
Thelinechartcanbeabasicone-dimensionalCartesianplotsuchastheoneshowninthisfigure.
Youcanhaveanyofthesetypesoflinecharts,whichrepresentdifferentwaysofdisplayingtheseriesdata.
(standard)LineStackedLineStacked100%(normalized)Line
LineCharts
Eachpointinalineseriescontainsasingledatavalue.Thedatavaluesarevisualizedaspointsonaline.
Alineseriescanbeassignedaborder,filleffect,ordepthfortheline.Thelinecanalsobejaggedorsmoothordisplaydroplines.Assigningnullfortheborderorfilleffectindicatesthatthepropertyisunset.Depthismeasuredrelativetothefloorgridcell(0=nodepth,1=depthoffloorgridcell).
Spread Windows Forms Developer’s Guide 590
Copyright © GrapeCity, Inc. All rights reserved.
Eachpointinalineseriescanhaveaborderorafilleffectfortheline.
StackedLineCharts
Thestackedlinechartshowsthepointsverticallystacked:
Astackedlineseriesisacompositeseriesthatgroupstogethertwoormorelineseries.Astackedlineseriescanhaveaborder,filleffect,ordepthforthelines.Youcanalsospecifywhetherthelineisjaggedorsmoothandwhetherdroplinesaredisplayed.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.Depthismeasuredrelativetothefloorgridcell(0=nodepth,1=depthoffloorgridcell).
Eachlineseriesinastackedlineseriescanbeassignedaborderandafilleffectfortheline.
Eachpointinalineseriesinastackedlineserieshasasingledatavalue.Thedatavalueisvisualizedasapointonaline.Eachpointinalineseriesinastackedlineseriescanbeassignedaborderandafilleffectfortheline.
Stacked100%LineCharts
Thestacked100%linechartshowsthepointsverticallystackedandspreadallthewaytothetop(100%)butspreadproportionately;otherwise,itissimilartoastackedlinechart:
FormoreinformationonthelineseriesobjectintheAPI,refertotheLineSeries('LineSeriesClass'intheon-linedocumentation)class.
Market Data (High-Low) Charts
Themarketdata(high-low)chartsareanotherversionoftheone-dimensionalCartesianplot(Yplot)specificallydesignedfordisplayingmarketdataoftenwithhighandlowvaluesaswellasmarketopenandmarketclosevalues.Forexample:
Spread Windows Forms Developer’s Guide 591
Copyright © GrapeCity, Inc. All rights reserved.
Thenormalhigh-lowseriesaredisplayedasverticallineswiththehighvaluebeingtheverticallyhighestpointonthelineandthelowvaluebeingthelowestpointontheline.Theopeningmarketvalueisthesmallhorizontaltickontheleftofthelineandtheclosingvalueisthesmallhorizontaltickontherightside.
Ahigh-lowbarseriescanhaveaborder,filleffect,width,anddepthforthebars.Eachpointcanbeassignedaborderandafilleffectforthebar.
Anopen-high-low-closeseriescanbeassignedalineforupordownpoints,andawidth.Thewidthismeasuredrelativetothefloorgridcell(0=nodepth,1=widthtoedgeofgridcell).
Eachpointinanopen-high-low-closeseriescontainsfourdatavalues:open,high,low,close.Eachpointisvisualizedasalineextendingfromthelowvaluetothehighvaluewithsmallermarkersattheopenandclosevalues.
CandlestickCharts
Thecandlestickhigh-lowseriesaredisplayedasbarswiththehighvaluebeingtheverticallyhighestpointonthebarandthelowvaluebeingthelowestpointonthebar.Ifitissolid,thentheopeningvaluewaslower;ifitishollow,theopeningvaluewashigher:
Spread Windows Forms Developer’s Guide 592
Copyright © GrapeCity, Inc. All rights reserved.
Acandlestickseriescanbeassignedaborderandafilleffectforupordownpoints.Youcanalsosetthewidthanddepthforthebars.
Eachpointinacandlestickseriescontainsfourvalues:open,high,low,andclose.Eachpointisvisualizedasalineextendingfromthelowvaluetothehighvalueandabarextendingfromtheopenvaluetotheclosevalue.
Eachpointcanbeassignedaborderforupanddownpoints.Youcanalsosetafilleffectforupanddownpoints.
FormoreinformationontheobjectsintheAPI,refertothese:
HighLowAreaSeries('HighLowAreaSeriesClass'intheon-linedocumentation)HighLowBarSeries('HighLowBarSeriesClass'intheon-linedocumentation)HighLowCloseSeries('HighLowCloseSeriesClass'intheon-linedocumentation)
Point Charts
Thepointchartcanbeabasicone-dimensionalCartesianplotsuchastheoneshowninthisfigure:
Youcanhaveanyofthesetypesofpointcharts,whichrepresentdifferentwaysofdisplayingtheseriesdata.
(standard)PointStackedPointStacked100%(normalized)Point
PointCharts
Apointmarkerisusedtovisualizeeachdatavalue.Eachpointinapointseriescontainsasingledatavalue.
Spread Windows Forms Developer’s Guide 593
Copyright © GrapeCity, Inc. All rights reserved.
Apointseriescanbeassignedaborder,filleffect,shape,size,anddepthforthepointmarkers.Assigninganullfortheborderorfilleffectindicatesthatthepropertyisunset.Sizeismeasuredinmodelunits.Depthismeasuredrelativetothefloorofthegridcell(0=nowidth,1=widthoffloorgridcell).
Eachpointinapointseriescanalsobeassignedaborderandafilleffectforthepointmarker.
StackedPointCharts
Thestackedpointchartshowsthepointsverticallystacked:
Astackedpointseriesisacompositeseriesthatgroupstogethertwoormorepointseries.
Astackedpointseriescanhaveaborder,filleffect,size,ordepthforthepointmarkers.Youcanalsospecifywhetherthegroupshouldbedisplayedas100%stacked.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.Sizeismeasuredinmodelunits.Depthismeasuredrelativetothedepthoffloorgridcell(0=nodepth,1=depthoffloorgridcell).
Eachpointseriesinastackedpointseriescanbeassignedaborderandfilleffectforpointmakers.Eachpointinapointserieshasasingledatavalue.Thedatavalueisvisualizedasapointmarker.
Eachpointinapointseriesinastackedpointseriescanbeassignedaborderandafilleffectforthepointmarker.
Stacked100%PointCharts
Thestacked100%pointchartshowsthepointsverticallystackedandspreadallthewaytothetop(100%)butspreadproportionately;otherwise,itissimilartoastackedpointchart:
FormoreinformationonthepointseriesobjectintheAPI,refertothePointSeries('PointSeriesClass'intheon-linedocumentation)class.
Stripe Charts
Spread Windows Forms Developer’s Guide 594
Copyright © GrapeCity, Inc. All rights reserved.
Stripescanbeusedinabasicone-dimensionalCartesianplotsuchastheoneshowninthisfigure:
Youcanspecifyastartandendvalueforthestripeonthechartaxis.Youcanalsospecifyafilltypeandcolorforthestripe.Astripecanbeaddedtoachartwiththeaxispropertiesintheappropriateplotareaclass.
FormoreinformationonthestripeobjectintheAPI,refertotheStripe('StripeClass'intheon-linedocumentation)class.
FormoreinformationonthevalueaxisseriesobjectintheAPI,refertotheValueAxisclass.
XY Plot Types
TheXYplotareacontainsseriesthathavevaluesintwodimensions.Whenvisualizedin2D,anXYplotareatakestheformofarectanglewithahorizontalx-axisrepresentingvaluesandaverticaly-axisrepresentingvalues.Whenvisualizedin3D,theXYplotareatakestheformofacubewithahorizontalx-axisrepresentingvalues,averticaly-axisrepresentingvalues,andadepthz-axisrepresentingseries.
Whenaplotareahasmultiplex-axesormultipley-axes,aseriescanbeassignedtoaspecificaxisusingtheaxis'sID.
YoucanhaveanyofthesetypesofXYplots.
XYBubbleChartsXYLineChartsXYPointChartsXYStripeCharts
XY Bubble Charts
ThebubblechartcanbeanXYplotsuchastheoneshowninthisfigure.
Spread Windows Forms Developer’s Guide 595
Copyright © GrapeCity, Inc. All rights reserved.
Eachpointcontainstwovalues:valueandsize.
Bubblebordersandfilleffectscanbeassignedfortheseriesorforapointintheseries.Null(NothinginVB)indicatesthatthepropertyisnotset.Bubblesizeismeasuredrelativetotheplotareawidth(witharangeof0to1).Bubbledepthismeasuredrelativetothefloorgrid(witharangeof0to1).
FormoreinformationonthebubbleseriesobjectintheAPI,refertotheXYBubbleSeries('XYBubbleSeriesClass'intheon-linedocumentation)class.
XY Line Charts
ThelinechartcanbeanXYplotsuchastheoneshowninthisfigure.
AnXZlineseriescanhaveaborder,filleffect,anddepthfortheline.Youcanalsospecifywhetherthelineisjaggedorsmoothandwhetherdroplinesaredisplayed.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.Depthismeasuredrelativetothefloorgridcell(0=nodepth,1=depthoffloorgridcell).
FormoreinformationonthelineseriesobjectintheAPI,refertotheXYLineSeries('XYLineSeriesClass'intheon-linedocumentation)class.
XY Point Charts
ThepointchartcanbeanXYplotsuchastheoneshowninthisfigure.
Spread Windows Forms Developer’s Guide 596
Copyright © GrapeCity, Inc. All rights reserved.
Apointmarkerisusedtovisualizeeachdatavalue.Eachpointinapointseriescontainsasingledatavalue.
AnXYpointseriescanhaveaborder,filleffect,shape,size,anddepthforthepointmarkers.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.Sizeismeasuredinmodelunits.Depthismeasuredrelativetothefloorgridcell(0=nowidth,1=widthoffloorgridcell).
EachpointinanXYpointseriescontainstwodatavalues:xandy.Eachpointisvisualizedasapointmarker.Eachpointcanbeassignedaborderandafilleffectforthepointmarker.
FormoreinformationonthepointseriesobjectintheAPI,refertothePointSeries('PointSeriesClass'intheon-linedocumentation)class.
XY Stripe Charts
ThestripechartcanbeanXYplotsuchastheoneshowninthisfigure.
Youcanspecifyastartandendvalueforthestripeonthechartaxis.Youcanalsospecifyafilltypeandcolorforthestripe.Astripecanbeaddedtoachartwiththeaxispropertiesintheappropriateplotareaclass.
FormoreinformationonthestripeobjectintheAPI,refertotheStripe('StripeClass'intheon-linedocumentation)class.
XYZ Plot Types
TheXYZplotareacontainsseriesthathavevaluesinthreedimensions.Whenvisualizedin2D,theXYZplotareatakestheformofarectanglewithahorizontalx-axisrepresentingvaluesandaverticaly-axisrepresentingvalues.Whenvisualizedin3D,theXYZplotareatakestheformofacubewithahorizontalx-axisrepresentingvalues,averticaly-axisrepresentingvalues,andadepthz-axisrepresentingvalues.
TheElevationandRotationpropertiesintheplotareaclasscanbeusedtomakethez-axisvisible.
Spread Windows Forms Developer’s Guide 597
Copyright © GrapeCity, Inc. All rights reserved.
IfanXYZplotareahasmultiplex,y,orz-axesthentheseriescanbeassignedtoaspecificaxisusingtheaxis'sID.TherearethreesubtypesofXYZseries:XYZpoint,XYZline,andXYZsurface.
YoucanhaveanyofthesetypesofXYZplots.
XYZPointChartsXYZLineChartsXYZSurfaceChartsXYZStripeCharts
FordetailsontheAPI,seetheXYZPlotArea('XYZPlotAreaClass'intheon-linedocumentation)class.
XYZ Point Charts
ThepointchartcanbeanXYZplotsuchastheoneshowninthisfigure.
Spread Windows Forms Developer’s Guide 598
Copyright © GrapeCity, Inc. All rights reserved.
EachpointinanXYZpointserieshasthreedatavalues:x,y,andz.Eachpointisvisualizedaspointmarker.
ThepointmarkersinanXYZseriesortheseriescanbeassignedaborder,filleffect,shape,andasize.Settingsatthepointlevelhaveprecedence.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.Sizeismeasuredinmodelunits.
FormoreinformationonthepointseriesobjectintheAPI,refertotheXYZPointSeries('XYZPointSeriesClass'intheon-linedocumentation)class.
XYZ Line Charts
ThelinechartcanbeanXYZplotsuchastheoneshowninthisfigure.
Spread Windows Forms Developer’s Guide 599
Copyright © GrapeCity, Inc. All rights reserved.
EachpointinanXYZlineserieshasthreedatavalues:x,y,andz.Eachpointisvisualizedasapointonaline.
AnXYZlineseriesoreachpointintheseriescanbeassignedaborderorafilleffectfortheline.Youcanalsospecifywhetherthelineisjaggedorsmoothandwhetherdroplinesaredisplayed.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.
FormoreinformationonthelineseriesobjectintheAPI,refertotheXYZLineSeries('XYZLineSeriesClass'intheon-linedocumentation)class.
XYZ Surface Charts
ThesurfacechartcanbeanXYZplotsuchastheoneshowninthisfigure.
EachpointinaXYZserieshasthreedatavalues:x,y,andz.Eachpointisvisualizedasapointonasurface.
AnXYZsurfaceseriescanbeassignedafilleffectforthesurface.Assigningnullforthefilleffectindicatesthatthe
Spread Windows Forms Developer’s Guide 600
Copyright © GrapeCity, Inc. All rights reserved.
propertyisunset.
FormoreinformationonthesurfaceseriesobjectintheAPI,refertotheXYZSurfaceSeries('XYZSurfaceSeriesClass'intheon-linedocumentation)class.
XYZ Stripe Charts
ThestripechartcanbeanXYZplotsuchastheoneshowninthisfigure.
Youcanspecifyastartandendvalueforthestripeonthechartaxis.Youcanalsospecifyafilltypeandcolorforthestripe.Astripecanbeaddedtoachartwiththeaxispropertiesintheappropriateplotareaclass.
FormoreinformationonthestripeobjectintheAPI,refertotheStripe('StripeClass'intheon-linedocumentation)class.
Pie Plot Types
Apieplotareacontainsseriesthathavevaluesinonedimension.Whenvisualizedintwodimensions,apieplotareatakestheformofacircle(orpartialcircle).Whenvisualizedinthreedimensions,apieplotareatakestheformofadisk(orpartialdisk).Thefollowingimagedisplaysathreedimensionalchart:
YoucanhaveanyofthesetypesofPieplots.
DoughnutChartsPieCharts
FordetailsontheAPI,seethePiePlotArea('PiePlotAreaClass'intheon-linedocumentation)class.
Doughnut Charts
Spread Windows Forms Developer’s Guide 601
Copyright © GrapeCity, Inc. All rights reserved.
Thedoughnutchartcanbeapieplotsuchastheoneshowninthisfigure.
Eachpointinapieserieshasasingledatavalue.Eachpointisvisualizedasapieslice.
TheHoleSizepropertyisusedtocreatethedoughnutchart.IfthispropertyisnotsetwhenusingthePieSeries('PieSeriesClass'intheon-linedocumentation)class,thechartwouldbeapiechart.
Apieseriescanbeassignedaborderandfilleffectforthepieslices.Assigningnullforaborderorfilleffectindicatesthatthepropertyisnull.
Eachpointcanbeassignedaborder,filleffect,andadetachmentdistanceforthepieslice.Detachmentdistanceismeasuredrelativetopieradius(0=nodetachment,1=detachmentislengthofpieradius).Thedetachmentdistance(PieDetachmentsproperty)isusedtocreateanexplodeddoughnutchart.
FormoreinformationonthepieseriesobjectintheAPI,refertothePieSeries('PieSeriesClass'intheon-linedocumentation)class.
Pie Charts
Thepiechartcanbeapieplotsuchastheoneshowninthisfigure.
Eachpointinapieserieshasasingledatavalue.Eachpointisvisualizedasapieslice.
Apieseriescanbeassignedaborderandfilleffectforthepieslices.Assigningnullforaborderorfilleffectindicatesthatthepropertyisnull.
Eachpointcanbeassignedaborder,filleffect,andadetachmentdistanceforthepieslice.Detachmentdistanceismeasuredrelativetopieradius(0=nodetachment,1=detachmentislengthofpieradius).Thedetachmentdistance(PieDetachmentsproperty)isusedtocreateanexplodedpiechart.
FormoreinformationonthepieseriesobjectintheAPI,refertothePieSeries('PieSeriesClass'intheon-linedocumentation)class.
Polar Plot Types
Spread Windows Forms Developer’s Guide 602
Copyright © GrapeCity, Inc. All rights reserved.
Apolarplotareacontainsseriesthathavevaluesintwodimensions(angleandradius).Whenvisualizedintwodimensions,apolarplotareatakestheformofacirclewithacircularx-axisrepresentinganglevaluesandaradialy-axisrepresentingradiusvalues.Whenvisualizedinthreedimensions,apolarplotareatakestheformofadiskwithacircularx-axisrepresentingananglevalueandaradialy-axisrepresentingaradiusvalue.
Apolarseriesisdisplayedinapolarplotarea.Pointshavevalue(s)intwodimensions:x(angle)andy(radius).Ifapolarplotareahasmultipley-axesthenaseriescanbeassignedtoaspecificaxisusingtheaxis'sID.Thereareseveralsubtypesofpolarseries:polarpoint,polarline,polararea,andpolarstripe.
ThefollowingimageshowsathreedimensionalpolarpointchartthatwascreatedbyusingtheElevation,Rotation,andViewTypeproperties.TheDepthpropertyintheplotareaclasswasusedtoadddepthtothepointmarkers.
YoucanhaveanyofthesetypesofPolarplots.
PolarPointChartsPolarLineChartsPolarAreaChartsPolarStripeCharts
FordetailsontheAPI,seethePolarPlotArea('PolarPlotAreaClass'intheon-linedocumentation)class.
Polar Point Charts
Thepointchartcanbeapolarplotsuchastheoneshowninthefigure:
Spread Windows Forms Developer’s Guide 603
Copyright © GrapeCity, Inc. All rights reserved.
Eachpointhastwodatavalues:x(angle)andy(radius).Eachpointisvisualizedasapointmarker.
Thepointmarkersinthepolarpointseriesortheseriescanbeassignedaborder,filleffect,shape,size,andadepth.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.Thesizeofthepointmarkerismeasuredinmodelunits.Thedepthofthepointmarkerismeasuredrelativetoplotareadepth(0=nodepth,1=fulldepthofplotarea).
FormoreinformationonthepointseriesobjectintheAPI,refertothePolarPointSeries('PolarPointSeriesClass'intheon-linedocumentation)class.
Polar Line Charts
Thelinechartcanbeapolarplotsuchastheoneshowninthefollowingfigure:
Spread Windows Forms Developer’s Guide 604
Copyright © GrapeCity, Inc. All rights reserved.
Eachpointhastwodatavalues:x(angle)andy(radius).Eachpointisvisualizedasapointonaline.
Apolarlineseriesoreachpointintheseriescanbeassignedaborder,filleffect,andadepthfortheline.Youcanalsospecifywhetherthelineisclosed.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.Depthismeasuredrelativetoplotareadepth(0=nodepth,1=fulldepthofplotarea).
FormoreinformationonthelineseriesobjectintheAPI,refertothePolarLineSeries('PolarLineSeriesClass'intheon-linedocumentation)class.
Polar Area Charts
Theareachartcanbeapolarplotsuchastheoneshowninthefollowingfigure:
Spread Windows Forms Developer’s Guide 605
Copyright © GrapeCity, Inc. All rights reserved.
Eachpointhastwodatavalues:x(angle)andy(radius).Eachpointisvisualizedasapointonanarea.
Apolarareaseriescanbeassignedaborder,filleffect,andadepthforthearea.Eachpointcanbeassignedaborderandafilleffectforthearea.Youcanalsospecifywhethertheareaisclosed.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.Depthismeasuredrelativetotheplotareadepth(0=nodepth,1=fulldepthofplotarea).
FormoreinformationontheareaseriesobjectintheAPI,refertothePolarAreaSeries('PolarAreaSeriesClass'intheon-linedocumentation)class.
Polar Stripe Charts
Thestripechartcanbeapolarplotsuchastheoneshowninthisfigure.
Youcanspecifyastartandendvalueforthestripeonthechartaxis.Youcanalsospecifyafilltypeandcolorforthestripe.Astripecanbeaddedtoachartwiththeaxispropertiesintheappropriateplotareaclass.
FormoreinformationonthestripeobjectintheAPI,refertotheStripe('StripeClass'intheon-linedocumentation)class.
Spread Windows Forms Developer’s Guide 606
Copyright © GrapeCity, Inc. All rights reserved.
Radar Plot Types
Aradarplotareacontainsseriesthathavevaluesinonedimension.Whenvisualizedintwodimensions,aradarplotareatakestheformofann-sidedpolygonwithacircularx-axisrepresentingcategoriesandaradialy-axisrepresentingvalues.Whenvisualizedinthreedimensions,aradarplotareatakestheformofann-sideddiskwithacircularx-axisrepresentingcategoriesandaradialy-axisrepresentingvalues.
Aradarseriesisdisplayedinaradarplotarea.Eachpointhasvalue(s)inonedimension:y(radius).Ifaplotareahasmultipley-axesthenaseriescanbeassignedtoaspecificaxisusingtheaxis'sID.Thereareseveralsubtypesofradarseries:radarpoint,radarline,radararea,andradarstripe.
YoucanhaveanyofthesetypesofRadarplots.
RadarPointChartsRadarLineChartsRadarAreaChartsRadarStripeCharts
FordetailsontheAPI,seetheRadarPlotArea('RadarPlotAreaClass'intheon-linedocumentation)class.
Radar Point Charts
Thepointchartcanbearadarplotsuchastheoneshowninthisfigure:
Spread Windows Forms Developer’s Guide 607
Copyright © GrapeCity, Inc. All rights reserved.
Eachpointhasasingledatavalue:y.Eachpointisvisualizedasapointmarker.
Thepointmarkersinaradarpointseriesortheseriescanbeassignedaborder,filleffect,shape,size,andadepth.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.Sizeismeasuredinmodelunits.Depthismeasuredrelativetotheplotareadepth(0=nodepth,1=depthofplotarea).
FormoreinformationonthepointseriesobjectintheAPI,refertotheRadarPointSeries('RadarPointSeriesClass'intheon-linedocumentation)class.
Radar Line Charts
Thelinechartcanbearadarplotsuchastheoneshowninthisfigure:
Spread Windows Forms Developer’s Guide 608
Copyright © GrapeCity, Inc. All rights reserved.
Eachpointhasasingledatavalue:y.Eachpointisvisualizedaspointonaline.
Aradarlineseriescanbeassignedaborder,filleffect,andadepthfortheline.Eachpointcanbeassignedaborderandafilleffectfortheline.Assigningnullforaborderorfilleffectindicatesthatthepropertyisunset.Depthismeasuredrelativetotheplotareadepth(0=nodepth,1=depthofplotarea).
FormoreinformationonthelineseriesobjectintheAPI,refertotheRadarLineSeries('RadarLineSeriesClass'intheon-linedocumentation)class.
Radar Area Charts
Theareachartcanbearadarplotsuchastheoneshowninthisfigure:
Eachpointhasasingledatavalue:y.Eachpointisvisualizedasapointonanarea.
Aradarareaseriescanbeassignedaborder,filleffect,andadepthforthearea.Eachpointcanbeassignedaborderandafilleffectforthearea.Assigningnullfortheborderorfilleffectindicatesthatthepropertyisunset.Depthismeasuredrelativetotheplotareadepth(0=nodepth,1=depthofplotarea).
FormoreinformationonthelineseriesobjectintheAPI,refertotheRadarAreaSeries('RadarAreaSeriesClass'intheon-linedocumentation)class.
Radar Stripe Charts
Thestripechartcanbearadarplotsuchastheoneshowninthisfigure.
Spread Windows Forms Developer’s Guide 609
Copyright © GrapeCity, Inc. All rights reserved.
Youcanspecifyastartandendvalueforthestripeonthechartaxis.Youcanalsospecifyafilltypeandcolorforthestripe.Astripecanbeaddedtoachartwiththeaxispropertiesintheappropriateplotareaclass.
FormoreinformationonthestripeobjectintheAPI,refertotheStripe('StripeClass'intheon-linedocumentation)class.
Data Plot Types
Datachartsarechartsthatcanbebound.Anyseriesinanyoftheplottypescanbeboundtoadatasourceusingthedatasourcepropertyintheseriesclass.Youcanuseanyofthesetypesofdatasources.
ArrayListTable
Thearraydatachartcanbeaone-dimensionalplotsuchastheoneshowninthisfigure.Thisarraychartshowsthebarsalongsideeachothervertically.
Thefollowingisanexampleofabarchartboundtoalistdatasource:
Spread Windows Forms Developer’s Guide 610
Copyright © GrapeCity, Inc. All rights reserved.
Thefollowingisanexampleofabarchartboundtoatabledatasource:
Plots and Series
Aplotareaistheareainwhichdatapoints(bars,points,lines,etc)aredrawn.Aplotareawillcontainacollectionofseries.Eachseriesisacollectionofdatapoints.Aplotareamayalsocontainanaxis(s)andwall(s).Theaxis(s)andwall(s)enhancethevisualappearanceoftheplotareaandareusuallypaintedjustoutsidetheplotarea.
Aplotareacanbeassignedananchorviewlocationandaviewsize.Theanchorviewlocationisspecifiedinnormalizedunits((0,0)=leftuppercornerofchartview,(1,1)=rightlowercornerofchartview).Theviewsizeoftheplotareaisspecifiedinnormalizedunits((0,0)=zerosize,(1,1)=fullsizeofchartview).Thelefttopcorneroftheplotareaisalignedwiththeanchorlocation.
Aplotareacanbeassignedamodelsizeusingwidth,height,anddepthproperties.Thepropertiesusemodelunits.
Thereareseveralsubtypesofplotareas:Y,XY,XYZ,Pie,Polar,Radar,Data,Sunburst,andTreemap.
Aseriesisacollectionofdatapointsthataredisplayedintheplotarea.Area,Line,andPointseriescanhavedroplines.Droplinesextendfromthedatapointdowntotheseriesoriginorcategoryaxis.Thiscanbeusedtohighlightthexvalueofthepoint.Thereareseveralsubtypesofseriessuchas:Y,XY,XYZ,Pie,Polar,andRadar.Thesesubtypesofseriescorrespondtothesubtypesofplotareas.
Whenacharthasmultiplelegends,aseriescanbeassignedtoaspecificlegendusingthelegend'sID.Manyoftheserieshaveproperties(e.g.borderorfilleffect)thatcanbeassignedtobothaseriesandapoint.Ifthepropertyissetforboththeseriesandthepointthenthepointsettingoverridestheseriessetting.Ifthepropertyisunsetforboththeseriesandthepointthenthechartviewwillprovideadefaultsetting.
Seethefollowingclassesformoreinformation:
AreaSeries('AreaSeriesClass'intheon-linedocumentation)BarSeries('BarSeriesClass'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 611
Copyright © GrapeCity, Inc. All rights reserved.
BoxWhiskerSeries('BoxWhiskerSeriesClass'intheon-linedocumentation)FunnelSeries('FunnelSeriesClass'intheon-linedocumentation)HighLowAreaSeries('HighLowAreaSeriesClass'intheon-linedocumentation)HighLowBarSeries('HighLowBarSeriesClass'intheon-linedocumentation)HighLowCloseSeries('HighLowCloseSeriesClass'intheon-linedocumentation)HistogramSeries('HistogramSeriesClass'intheon-linedocumentation)LineSeries('LineSeriesClass'intheon-linedocumentation)ParetoSeries('ParetoSeriesClass'intheon-linedocumentation)PieSeries('PieSeriesClass'intheon-linedocumentation)PolarSeries('PolarSeriesClass'intheon-linedocumentation)PointSeries('PointSeriesClass'intheon-linedocumentation)RadarSeries('RadarSeriesClass'intheon-linedocumentation)SunburstSeries('SunburstSeriesClass'intheon-linedocumentation)TreemapSeries('TreemapSeriesClass'intheon-linedocumentation)WaterfallSeries('WaterfallSeriesClass'intheon-linedocumentation)XYSeriesXYZSeries('XYZSeriesClass'intheon-linedocumentation)YSeries('YSeriesClass'intheon-linedocumentation)
UsingCode
Thefollowingexampleaddsaseriestoaplotarea.
Example
Thefollowingexampleaddsaseriestoaplotarea.
C#BarSeries series = new BarSeries();series.SeriesName = "Series 0";series.Values.Add(2.0);series.Values.Add(4.0);series.Values.Add(3.0);series.Values.Add(5.0);YPlotArea plotArea = new YPlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.Series.Add(series);
VBDim series As New FarPoint.Win.Chart.BarSeries()series.SeriesName = "Series 0"series.Values.Add(2.0)series.Values.Add(4.0)series.Values.Add(3.0)series.Values.Add(5.0)Dim plotArea As New FarPoint.Win.Chart.YPlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.Series.Add(series)
Spread Windows Forms Developer’s Guide 612
Copyright © GrapeCity, Inc. All rights reserved.
UsingtheChartDesigner
1. SelectthePlotAreaCollectioneditor.2. SelecttheSeriesCollectioneditor.3. Setpropertiesasneeded.
Walls
Awallisthearea(orplane)behind,below,ortothesideofachart.
Awallcanhaveaborder,filleffect,orwidth(measuredinmodelunits).Thewallcanbevisibleorhidden.Theaxisgrids(majorandminor)andstripesarepaintedonthewalls.Theaxisgridlines(majorandminor)arepaintedovertheaxisstripes.
Thefollowingimagedisplaysachartwithback,bottom,andsidewalls.
Seethefollowingformoreinformationonhowtosetpropertiesforwalls:
Wall('WallClass'intheon-linedocumentation)XYPlotArea
UsingCode
Usepropertiesintheplotareaclassestosetoptionsforthewalls.
Example
Thefollowingexamplesetspropertiesforthewall.
C#YPlotArea plotArea = new YPlotArea();plotArea.BackWall.Visible = true;
VBDim plotArea As New FarPoint.Win.Chart.YPlotArea()
Spread Windows Forms Developer’s Guide 613
Copyright © GrapeCity, Inc. All rights reserved.
plotArea.BackWall.Visible = True
UsingtheChartDesigner
1. SelectthePlotAreaCollectioneditor.2. Clickthedrop-downbuttonontherightsideoftheAddbutton(lower,leftsideofdialog)tochangetheplottype.3. Setthewallpropertiesasneeded.
Axis and Other Lines
Anaxisisusedtodisplaythescaleforasingledimensionofaplotarea.Anaxiscanhaveatitle,arulerline,majorandminortickmarks,tickmarklabels,majorandminorgridlines,andstripes.Thedirectionoftheaxiscanbereversed.Theminimum,maximum,majororminortick,andlabelunitscanbeautomaticallygeneratedormanuallyassigned.Thescalecanbelinearorlogarithmic.
Tickmarksandgridsareusedtomarkindividualvaluesontheruler.Tickmarksarepaintedontherulerwhilecorrespondinggridsarepaintedonthewall(s).Stripesareusedtohighlightrangesofvalues.Stripesarepaintedonthewall(s).
Thetitle,ruler,tickmarks(majorandminor),tickmarklabels,andgrids(majorandminor)canbehidden.
Afontcanbesetforthetitleandtickmarksandthetitlecanbecustomized.Thetitleandtickmarklabelscanhavefilleffects.
Theaxiscanhavelinesfortheruler,major,andminorgridsaswellasaminimumandmaximumvalue.Theminimumandmaximumvaluescanbeautomaticallygeneratedbythechartview.
Unitscanbeassignedformajorandminortickmarksandtickmarklabels.Theunitscanalsobeautomaticallygeneratedforthechartview.Length(measuredinmodelunits),canalsobesetformajorandminortickmarks.Theunitscanbeautomaticallygenerated.
Anaxiscanbeassignedacollectionofstripes.Astriperepresentsarangeofvaluesontheaxisandisusedtohighlightarangeofvaluesonagivenaxis.Astripeisassociatedwithanaxis,butispaintedonawall.
Anindexaxisisusedtodisplayintegervaluessuchasacategoryorseriesindex.Tickmarks,tickmarklabels,andgridlinescanbedisplayedontheintegervaluesorbetweentheintegervalues.Avalueaxisisusedtodisplaydoublevalues(datavalues).Thevalueaxiscanhavealinearorlogarithmicscale(whenusingalogarithmicscale,thevalueaxiscanusealogarithmicbase).Formoreinformation,seethefollowingclasses:
Spread Windows Forms Developer’s Guide 614
Copyright © GrapeCity, Inc. All rights reserved.
IndexAxis('IndexAxisClass'intheon-linedocumentation)ValueAxis
Markersrepresentadatapointandcanhavemanyshapes.Formoreinformation,seetheMarkerShape('MarkerShapeEnumeration'intheon-linedocumentation)enumeration.
Stripesareusedtohighlightarangeofvaluesonagivenaxis.Astripeisassociatedwithanaxis,butispaintedonawall.
UsingCode
Usepropertiesintheplotareaclassestosetaxisoptions.
Example
Thefollowingexamplesetsatitlefortheaxis.
C#YPlotArea plotArea = new YPlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.XAxis.Title = "Categories";plotArea.YAxis[0].Title = "Values";
VBDim plotArea As New FarPoint.Win.Chart.YPlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.XAxis.Title = "Categories"plotArea.YAxis(0).Title = "Values"
UsingtheChartDesigner
1. SelectthePlotAreafromtheFormatmenu.2. SelecttheXAxisandYAxisCollections.3. SettheTitleandotherpropertiesasneeded.
Fill Effects
Afilleffectiswhentheinteriorofanobjectispainted.Twotypesoffilleffectsaresolidandgradient.Asolidfilleffectusesasinglecolorandagradientfillusestwocolorsandadirection.Theelementsinthechartthatcanhavefilleffectsarelabel,legend,wall,stripe,andthechartitself.
ThefollowingfilleffectsareavailableintheFill('FillClass'intheon-linedocumentation)class:
NoFillSolidFillImageFillGradientFill
YoucanfillelementsusingtheFillpropertyinthefollowingclasses:
ChartModel('ChartModelClass'intheon-linedocumentation)LabelArea('LabelAreaClass'intheon-linedocumentation)LegendArea('LegendAreaClass'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 615
Copyright © GrapeCity, Inc. All rights reserved.
Stripe('StripeClass'intheon-linedocumentation)Wall('WallClass'intheon-linedocumentation)
Tosetthefilleffectfortheentireplotarea,youcansettheFillpropertyofthewallfortheplotarea.Forexample,foray-plot,youcansetthefillofthewallsetbytheBackWallpropertyintheYPlotArea('YPlotAreaClass'intheon-linedocumentation)class.
UsingCode
Usepropertiestosetfilleffects.
Example
Thefollowingexamplesetsafilleffectforabar.
C#BarSeries series = new BarSeries();series.BarFill = new SolidFill(Color.Red);series.Values.Add(2.0);series.Values.Add(4.0);series.Values.Add(3.0);series.Values.Add(5.0);YPlotArea plotArea = new YPlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.Series.Add(series);ChartModel model = new ChartModel();model.PlotAreas.Add(plotArea);fpChart1.Model = model;
VBDim series As New FarPoint.Win.Chart.BarSeries()series.BarFill = New SolidFill(Color.Red)series.Values.Add(2.0)series.Values.Add(4.0)series.Values.Add(3.0)series.Values.Add(5.0)Dim plotArea As New YPlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.Series.Add(series)Dim model As New ChartModel()model.PlotAreas.Add(plotArea)fpChart1.Model = model
UsingCode
Usepropertiestosetfilleffects.
Example
Youcansetthefilleffectbeforeorafteraddingthedatapointsifyousetthefilleffectfortheentireseries.
C#
Spread Windows Forms Developer’s Guide 616
Copyright © GrapeCity, Inc. All rights reserved.
BarSeries series = new BarSeries();series.BarFill = new SolidFill(Color.Red);series.Values.Add(2.0);\\ ORBarSeries series = new BarSeries();series.Values.Add(2.0);series.BarFill = new SolidFill(Color.Red);
VBDim series As New FarPoint.Win.Chart.BarSeries()series.BarFill = New SolidFill(Color.Red)series.Values.Add(2.0)' ORDim series As New FarPoint.Win.Chart.BarSeries()series.Values.Add(2.0)series.BarFill = New SolidFill(Color.Red)
UsingCode
Usepropertiestosetfilleffects.
Example
Ifyousetthefilleffectforasingledatapoint,thenyouneedtoassignthefilleffectafteryouaddthedatapoint,sothereisadatapointtostorethefilleffectin.Forexample:
C#BarSeries series = new BarSeries();series.Values.Add(2.0);series.Values.Add(4.0);series.BarFills.Add(new SolidFill(Color.Green));
VBDim series As New FarPoint.Win.Chart.BarSeries()series.Values.Add(2.0)series.Values.Add(4.0)series.BarFills.Add(New SolidFill(Color.Green))
UsingCode
Usepropertiestosetfilleffects.
Example
Youcanassignfilleffectsforlinesandmarkersaswell.Forexample:
C#PointSeries series = new PointSeries();series.PointFill = new SolidFill(Color.Lime);series.PointBorder = new SolidLine(Color.Red);series.PointMarker = new BuiltinMarker(MarkerShape.Triangle, 10.0f);series.Values.Add(2.0);
Spread Windows Forms Developer’s Guide 617
Copyright © GrapeCity, Inc. All rights reserved.
series.Values.Add(4.0);series.Values.Add(3.0);series.Values.Add(5.0);
VBDim series As New PointSeries()series.PointFill = New SolidFill(Color.Lime)series.PointBorder = New SolidLine(Color.Red)series.PointMarker = New BuiltinMarker(MarkerShape.Triangle, 10F)series.Values.Add(2.0)series.Values.Add(4.0)series.Values.Add(3.0)series.Values.Add(5.0)
UsingtheChartDesigner
1. SelecttheFilloption.2. Setpropertiesasneeded.
Chart Line Style
YoucancreatealinestylewithspecialoptionssuchasopenandendarrowsforthelinechartwiththeLineBorder('LineBorderProperty'intheon-linedocumentation)propertyandtheEnhancedSolidLine('EnhancedSolidLineClass'intheon-linedocumentation)class.Youcanalsospecifylinestyleoptionssuchasdash,captype,andsoon.
UsingCode
1. Createalinechart.2. CreateanEnhancedSolidLine('EnhancedSolidLineClass'intheon-linedocumentation)object.3. SettheLineBorder('LineBorderProperty'intheon-linedocumentation)property.
Example
Thisexamplecodecreatesalinechartwithalinestylethatcontainsarrows.
C#FarPoint.Win.Chart.EnhancedSolidLine eh = new
Spread Windows Forms Developer’s Guide 618
Copyright © GrapeCity, Inc. All rights reserved.
FarPoint.Win.Chart.EnhancedSolidLine(System.Drawing.Color.Green, 1, FarPoint.Win.Chart.CompoundType.Double, FarPoint.Win.Chart.DashType.Dash, FarPoint.Win.Chart.CapType.Flat, FarPoint.Win.Chart.JoinType.Round, FarPoint.Win.Chart.ArrowType.Arrow, FarPoint.Win.Chart.ArrowType.OpenArrow, 1, 2);FarPoint.Win.Chart.LineSeries series1 = new FarPoint.Win.Chart.LineSeries();series1.PointMarker = new FarPoint.Win.Chart.BuiltinMarker(FarPoint.Win.Chart.MarkerShape.Circle, 7.0f);series1.PointFill = new FarPoint.Win.Chart.GradientFill(System.Drawing.Color.Coral, System.Drawing.Color.Crimson);series1.PointBorder = new FarPoint.Win.Chart.SolidLine(System.Drawing.Color.Yellow);series1.LineBorder = eh;series1.Values.Add(8.0);series1.Values.Add(12.0);series1.Values.Add(14.0);series1.Values.Add(15.0);FarPoint.Win.Chart.YPlotArea plotArea = new FarPoint.Win.Chart.YPlotArea();plotArea.Location = new System.Drawing.PointF(0.2f, 0.2f);plotArea.Size = new System.Drawing.SizeF(0.6f, 0.6f);plotArea.Series.Add(series1);FarPoint.Win.Chart.LabelArea labelArea = new FarPoint.Win.Chart.LabelArea();labelArea.Location = new System.Drawing.PointF(0.5f, 0.02f);labelArea.AlignmentX = 0.5f;labelArea.AlignmentY = 0.0f;labelArea.Text = "Chart";FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();model.LabelAreas.Add(labelArea);model.PlotAreas.Add(plotArea);FarPoint.Win.Spread.Chart.SpreadChart chart = new FarPoint.Win.Spread.Chart.SpreadChart();chart.Size = new Size(200, 200);chart.Location = new Point(100, 100);chart.Model = model;fpSpread1.Sheets[0].Charts.Add(chart);
VBDim eh As New FarPoint.Win.Chart.EnhancedSolidLine(System.Drawing.Color.Green, 1, FarPoint.Win.Chart.CompoundType.Double, FarPoint.Win.Chart.DashType.Dash, FarPoint.Win.Chart.CapType.Flat, FarPoint.Win.Chart.JoinType.Round, FarPoint.Win.Chart.ArrowType.Arrow, FarPoint.Win.Chart.ArrowType.OpenArrow, 1, 2)Dim series1 As New FarPoint.Win.Chart.LineSeries()series1.PointMarker = New FarPoint.Win.Chart.BuiltinMarker(FarPoint.Win.Chart.MarkerShape.Circle, 7.0F)series1.PointFill = New FarPoint.Win.Chart.GradientFill(System.Drawing.Color.Coral, System.Drawing.Color.Crimson)series1.PointBorder = New FarPoint.Win.Chart.SolidLine(System.Drawing.Color.Yellow)series1.LineBorder = ehseries1.Values.Add(8.0)series1.Values.Add(12.0)series1.Values.Add(14.0)series1.Values.Add(15.0)Dim plotArea As New FarPoint.Win.Chart.YPlotArea()plotArea.Location = New System.Drawing.PointF(0.2F, 0.2F)plotArea.Size = New System.Drawing.SizeF(0.6F, 0.6F)plotArea.Series.Add(series1)Dim labelArea As New FarPoint.Win.Chart.LabelArea()labelArea.Location = New System.Drawing.PointF(0.5F, 0.02F)
Spread Windows Forms Developer’s Guide 619
Copyright © GrapeCity, Inc. All rights reserved.
labelArea.AlignmentX = 0.5FlabelArea.AlignmentY = 0.0FlabelArea.Text = "Chart"Dim model As New FarPoint.Win.Chart.ChartModel()model.LabelAreas.Add(labelArea)model.PlotAreas.Add(plotArea)Dim chart As New FarPoint.Win.Spread.Chart.SpreadChart()chart.Size = New Size(200, 200)chart.Location = New Point(100, 100)chart.Model = modelFpSpread1.Sheets(0).Charts.Add(chart)
UsingtheChartDesigner
1. Right-clickonthelineintheLinechart.2. SelecttheFormatSeriesmenu.3. SelecttheLineBorderoption.4. SelectSolidLine.5. Setpropertiesandclosethedialog.
Elevation and Rotation
Youcanspecifytheelevationorrotationforachart.
Theelevationrotatesthegraphcounterclockwisearoundthehorizontalaxis.Thefollowingimagedisplaysagraphwithachangedelevation.
ForAPIinformation,seetheElevation('ElevationProperty'intheon-linedocumentation)property.
Therotationrotatesthegraphcounterclockwisearoundtheverticalaxis.Thefollowingimagedisplaysagraphwithachangedrotation.
Spread Windows Forms Developer’s Guide 620
Copyright © GrapeCity, Inc. All rights reserved.
ForAPIinformation,seetheRotation('RotationProperty'intheon-linedocumentation)property.
Lighting, Shapes, and Borders
Youcansetbordersformostareasofthechart.SeetheLineBorderandPointBorderpropertiesintheLineSeries('LineSeriesClass'intheon-linedocumentation)classformoreinformation.TheXYBubbleSeries('XYBubbleSeriesClass'intheon-linedocumentation)classhasadditionalbordersettingssuchasNegativeBorderandPositiveBorder.
Youcansetshapessuchasthebarshape.SeetheBarShape('BarShapeProperty'intheon-linedocumentation)propertyformoreinformation.
Youcanapplyadditionaleffectstothe3Dchartcontrolsuchascolor,directionallighting,andpositionallighting.Directionallightingmimicsadistantlightsourcesuchasraysfromthesun(parallelpaths).Positionallightingmimicsacloselightsourcesuchasalampwherethelightradiatesoutfromasinglepoint.
Thefollowingimagedisplaysagraphthatuseslightcolors,direction,andposition:
Thefollowingcoloreffectsareavailable:
AmbientColor('AmbientColorProperty'intheon-linedocumentation)DiffuseColor('DiffuseColorProperty'intheon-linedocumentation)SpecularColor('SpecularColorProperty'intheon-linedocumentation)
Youcanspecifythepositionandthedirectionofthelightwiththefollowingproperties:
PositionX('PositionXProperty'intheon-linedocumentation)PositionY('PositionYProperty'intheon-linedocumentation)PositionZ('PositionZProperty'intheon-linedocumentation)DirectionX('DirectionXProperty'intheon-linedocumentation)DirectionY('DirectionYProperty'intheon-linedocumentation)DirectionZ('DirectionZProperty'intheon-linedocumentation)
Spread Windows Forms Developer’s Guide 621
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
1. Createaseries.2. Addvaluestotheseries.3. Createaplotarea.4. SettheAmbientColor,DiffuseColor,andSpecularColorinthePositionalLight('PositionalLightClass'intheon-linedocumentation)class.
5. SetthePositionX,PositionY,andPositionZpropertiesinthePositionalLight('PositionalLightClass'intheon-linedocumentation)class.
6. SettheAmbientColor,DiffuseColor,andSpecularColorintheDirectionalLight('DirectionalLightClass'intheon-linedocumentation)class.
7. SetthePositionX,PositionY,andPositionZpropertiesintheDirectionalLight('DirectionalLightClass'intheon-linedocumentation)class.
8. Addthelightsettingstotheplotarea.9. Createachartmodelandassigntheplotareasettingstoit.10. Createachartandassignthechartmodeltoit.
Example
Thefollowingexampledemonstratesusinglightcolors,direction,andposition.
C#FarPoint.Win.Chart.PieSeries series = new FarPoint.Win.Chart.PieSeries();series.SeriesName = "Series 1";series.TopBevel = new FarPoint.Win.Chart.CircleBevel(12.0f, 12.0f);series.BottomBevel = new FarPoint.Win.Chart.CircleBevel(12.0f, 12.0f);series.Values.Add(1.0);series.Values.Add(2.0);series.Values.Add(4.0);series.Values.Add(8.0);FarPoint.Win.Chart.PiePlotArea plotArea = new FarPoint.Win.Chart.PiePlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.Series.Add(series);FarPoint.Win.Chart.PositionalLight light0 = new FarPoint.Win.Chart.PositionalLight();light0.AmbientColor = Color.FromArgb(64, 64, 64);light0.DiffuseColor = Color.FromArgb(64, 64, 64);light0.SpecularColor = Color.FromArgb(128, 128, 128);light0.PositionX = 0.0f;light0.PositionY = 0.0f;light0.PositionZ = 100.0f;FarPoint.Win.Chart.DirectionalLight light1 = new FarPoint.Win.Chart.DirectionalLight();light1.AmbientColor = Color.FromArgb(64, 64, 64);light1.DiffuseColor = Color.FromArgb(64, 64, 64);light1.SpecularColor = Color.FromArgb(128, 128, 128);light1.DirectionX = 1.0f;light1.DirectionY = 0.0f;light1.DirectionZ = 1.0f;FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();model.PlotAreas.Add(plotArea);model.PlotAreas[0].Lights.Clear();model.PlotAreas[0].Lights.Add(light0);model.PlotAreas[0].Lights.Add(light1);
Spread Windows Forms Developer’s Guide 622
Copyright © GrapeCity, Inc. All rights reserved.
fpChart1.Model = model;
VBDim series As New FarPoint.Win.Chart.PieSeries()series.SeriesName = "Series 1"series.TopBevel = New FarPoint.Win.Chart.CircleBevel(12.0F, 12.0F)series.BottomBevel = New FarPoint.Win.Chart.CircleBevel(12.0F, 12.0F)series.Values.Add(1.0)series.Values.Add(2.0)series.Values.Add(4.0)series.Values.Add(8.0)Dim plotArea As New FarPoint.Win.Chart.PiePlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.Series.Add(series)Dim light0 As New FarPoint.Win.Chart.PositionalLight()light0.AmbientColor = Color.FromArgb(64, 64, 64)light0.DiffuseColor = Color.FromArgb(64, 64, 64)light0.SpecularColor = Color.FromArgb(128, 128, 128)light0.PositionX = 0.0Flight0.PositionY = 0.0Flight0.PositionZ = 100.0FDim light1 As New FarPoint.Win.Chart.DirectionalLight()light1.AmbientColor = Color.FromArgb(64, 64, 64)light1.DiffuseColor = Color.FromArgb(64, 64, 64)light1.SpecularColor = Color.FromArgb(128, 128, 128)light1.DirectionX = 1.0Flight1.DirectionY = 0.0Flight1.DirectionZ = 1.0FDim model As New FarPoint.Win.Chart.ChartModel()model.PlotAreas.Add(plotArea)model.PlotAreas(0).Lights.Clear()model.PlotAreas(0).Lights.Add(light0)model.PlotAreas(0).Lights.Add(light1)fpChart1.Model = model
UsingtheChartDesigner
1. SelectthePlotAreasCollection.2. SelecttheLightCollectioneditor.3. Setpropertiesasneeded.
Size - Height, Width, and Depth
Youcansettheheight,width,anddepthfortheplotareaofthechart.Theheightofthechartisthedistancefromthetoptothebottomoftheplotarea.Thewidthofthechartisthedistancefromtherighttotheleftoftheplotarea.Thedepthoftheplotareaisthedistancefromthebacktothefrontofthechart.
Intwodimensions,theheightandwidthwouldbetherectanglethatmakesuptheplotarea.Inthreedimensions,theheight,width,anddepthwouldbethecubethatmakesuptheplotarea.Thedepthisthesizeofthecubealongthez-axis.Thefollowingimageshowsa3Dchart.
Spread Windows Forms Developer’s Guide 623
Copyright © GrapeCity, Inc. All rights reserved.
Seethefollowingformoreinformation:
Size('SizeProperty'intheon-linedocumentation)(widthandheight)Depth('DepthProperty'intheon-linedocumentation)
UsingCode
Usepropertiestosetthesizeanddepth.
Example
Thefollowingexamplesetsthesizeforaplotarea.
C#PiePlotArea plotArea = new PiePlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.Series.Add(series);
VBDim plotArea As New FarPoint.Win.Chart.PiePlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.Series.Add(series)
UsingtheChartDesigner
1. SelectthePlotAreaCollectioneditor.2. Setpropertiesasneeded.
Labels
Spread Windows Forms Developer’s Guide 624
Copyright © GrapeCity, Inc. All rights reserved.
Thelabelscontaintheplottitleandtheaxislabels.YoucansetthemaintitleforthechartusingtheTextpropertyintheLabelArea('LabelAreaClass'intheon-linedocumentation)class.
Youcansetthetext,alignment,andotherformattingpropertiesfortheaxislabels.ThelabeltextcanbeboundtoadatasourcewiththeTitleDataSourceandTitleDataFieldproperties.Seethefollowingformoreinformation:
YPlotArea('YPlotAreaClass'intheon-linedocumentation)IndexAxis('IndexAxisClass'intheon-linedocumentation)ValueAxis
UsingCode
1. Createaplotarea.2. Tosetthetitleintheplotareaclassforthex-axis,settheIndexAxis.Titleproperty.3. SetTitleTextFillandTitleTextFontforadditionalformatting.YoucanalsosettheTitleOffset.4. Tosetthetitleintheplotareaforthey-axis,settheValueAxis.Titleproperty.5. SetTitleTextFillandTitleTextFontforadditionalformatting.YoucanalsosettheTitleOffset.
Example
Thefollowingexamplesetsatitlefortheaxis.
C#YPlotArea plotArea = new YPlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.XAxis.Title = "Categories";plotArea.XAxis.TitleTextFont = new System.Drawing.Font("Arial", 12);plotArea.XAxis.TitleTextFill = new FarPoint.Win.Chart.SolidFill(Drawing.Color.Crimson);plotArea.YAxes[0].Title = "Values";plotArea.YAxes[0].TitleTextFont = new System.Drawing.Font("Comic Sans MS", 12);plotArea.YAxes[0].TitleTextFill = new FarPoint.Win.Chart.SolidFill(Drawing.Color.Chartreuse);
VBDim plotArea As New FarPoint.Win.Chart.YPlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.XAxis.Title = "Categories"plotArea.XAxis.TitleTextFont = New System.Drawing.Font("Arial", 12)plotArea.XAxis.TitleTextFill = New FarPoint.Win.Chart.SolidFill(Drawing.Color.Crimson)plotArea.YAxes(0).Title = "Values"plotArea.YAxes(0).TitleTextFont = New System.Drawing.Font("Comic Sans MS", 12)plotArea.YAxes(0).TitleTextFill = New FarPoint.Win.Chart.SolidFill(Drawing.Color.Chartreuse)
UsingtheChartDesigner
1. SelectthePlotAreafromtheFormatmenu.2. SelecttheXAxisandYAxisCollections.3. SettheTitleandotherpropertiesasneeded
Spread Windows Forms Developer’s Guide 625
Copyright © GrapeCity, Inc. All rights reserved.
Legends
Thelegendcontainsidentifiersforeachoftheseriesofthedata.Thelegendareacancontainlegenditems,abackground,andborders.Thelegendareaispositionedusingarelativelocation(where(0,0)=theleftuppercornerofthechartand(1,1)=therightlowercornerofthechart)andarelativealignment(where(0,0)=theleftuppercornerofthelabelareaand(1,1)=therightlowercornerofthelabelarea).
Seethefollowingformoreinformationonhowtosetpropertiesforthelegend:
LegendArea('LegendAreaClass'intheon-linedocumentation)LegendAreaCollection('LegendAreaCollectionClass'intheon-linedocumentation)
UsingCode
Uselocationandalignmentpropertiesinthelegendareaclassestosetthelegend.
Example
Thefollowingexamplesetspropertiesforthelegend.
C#LegendArea legend = new LegendArea();legend.Location = new PointF(0.98f, 0.5f);legend.AlignmentX = 1.0f;legend.AlignmentY = 0.5f;
VBDim legend As New FarPoint.Win.Chart.LegendArea()legend.Location = New PointF(0.98F, 0.5F)legend.AlignmentX = 1.0Flegend.AlignmentY = 0.5F
UsingtheChartDesigner
1. SelecttheLegendAreaCollectioneditor.2. Setpropertiesasneeded.
Creating Charts
Youcanaddchartsusingcode,theSpreaddesigner,ortheChartdesigner.Youcanalsobindchartsandlettheendusermakechangestothechartatruntime.Formoreinformation,seethefollowingtopics:
CreatingPlotTypesConnectingtoDataSavingorLoadingaChartUsingtheChartDesignerUsingtheChartControl
Creating Plot Types
Thefollowingtopicsexplainhowtocreatedifferentplottypes:
Spread Windows Forms Developer’s Guide 626
Copyright © GrapeCity, Inc. All rights reserved.
CreatingaYPlotCreatinganXYPlotCreatinganXYZPlotCreatingaPiePlotCreatingaPolarPlotCreatingaRadarPlotCombiningPlotTypesCreatingaSunburstChart(on-linedocumentation)CreatingaTreemapChart(on-linedocumentation)
Creating a Y Plot
YoucancreateaYPlotchartusingcodeorthedesigner.ThefollowingimageshowsaYPlotbartypechart.
FordetailsontheAPI,seetheYPlotArea('YPlotAreaClass'intheon-linedocumentation)class.
ThefollowingclassesarealsoavailablewhencreatingYplottypecharts:
AreaSeries('AreaSeriesClass'intheon-linedocumentation)BarSeries('BarSeriesClass'intheon-linedocumentation)BoxWhiskerSeries('BoxWhiskerSeriesClass'intheon-linedocumentation)FunnelSeries('FunnelSeriesClass'intheon-linedocumentation)HighLowAreaSeries('HighLowAreaSeriesClass'intheon-linedocumentation)HighLowBarSeries('HighLowBarSeriesClass'intheon-linedocumentation)HighLowCloseSeries('HighLowCloseSeriesClass'intheon-linedocumentation)HistogramSeries('HistogramSeriesClass'intheon-linedocumentation)LineSeries('LineSeriesClass'intheon-linedocumentation)ParetoSeries('ParetoSeriesClass'intheon-linedocumentation)PointSeries('PointSeriesClass'intheon-linedocumentation)WaterfallSeries('WaterfallSeriesClass'intheon-linedocumentation)YSeries('YSeriesClass'intheon-linedocumentation)
UsingCode
1. UsetheBarSeries('BarSeriesClass'intheon-linedocumentation)classtoadddatatoaChartcontrol.2. UsetheYPlotArea('YPlotAreaClass'intheon-linedocumentation)classtocreateaplotarea.3. Setthelocationandsizeoftheplotarea.4. Addtheseriestotheplotarea.5. Createalabelandlegendforthechart.
Spread Windows Forms Developer’s Guide 627
Copyright © GrapeCity, Inc. All rights reserved.
6. Createachartmodelandaddtheplotarea,label,andlegendtothemodel.7. Createachartandaddthechartmodeltoit.
Example
ThefollowingexampledemonstratescreatingaYPlotchartandaddingunbounddatatothecontrol.
C#BarSeries series = new BarSeries();series.SeriesName = "Series 0";series.Values.Add(2.0);series.Values.Add(4.0);series.Values.Add(3.0);series.Values.Add(5.0);YPlotArea plotArea = new YPlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.Series.Add(series);LabelArea label = new LabelArea();label.Text = "Bar Chart";label.Location = new PointF(0.5f, 0.02f);label.AlignmentX = 0.5f;label.AlignmentY = 0.0f;LegendArea legend = new LegendArea();legend.Location = new PointF(0.98f, 0.5f);legend.AlignmentX = 1.0f;legend.AlignmentY = 0.5f;ChartModel model = new ChartModel();model.LabelAreas.Add(label);model.LegendAreas.Add(legend);model.PlotAreas.Add(plotArea);chart2DControl1.Model = model;
VBDim series As New FarPoint.Win.Chart.BarSeries()series.SeriesName = "Series 0"series.Values.Add(2.0)series.Values.Add(4.0)series.Values.Add(3.0)series.Values.Add(5.0)Dim plotArea As New FarPoint.Win.Chart.YPlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.Series.Add(series)Dim label As New FarPoint.Win.Chart.LabelArea()label.Text = "Bar Chart"label.Location = New PointF(0.5F, 0.02F)label.AlignmentX = 0.5Flabel.AlignmentY = 0.0FDim legend As New FarPoint.Win.Chart.LegendArea()legend.Location = New PointF(0.98F, 0.5F)legend.AlignmentX = 1.0Flegend.AlignmentY = 0.5FDim model As New FarPoint.Win.Chart.ChartModel()model.LabelAreas.Add(label)
Spread Windows Forms Developer’s Guide 628
Copyright © GrapeCity, Inc. All rights reserved.
model.LegendAreas.Add(legend)model.PlotAreas.Add(plotArea)chart2DControl1.Model = model
UsingtheChartDesigner
1. SelectthePlotAreaCollectioneditor.2. Setpropertiesasneeded.
Creating an XY Plot
YoucancreateanXYPlotchartusingcodeorthedesigner.ThefollowingimageshowsanXYPlotpointtypechart.
FordetailsontheAPI,seetheXYPlotAreaclass.
ThefollowingclassesarealsoavailablewhencreatingXYplottypecharts:
XYBubbleSeries('XYBubbleSeriesClass'intheon-linedocumentation)XYPointSeries('XYPointSeriesClass'intheon-linedocumentation)XYLineSeries('XYLineSeriesClass'intheon-linedocumentation)
UsingCode
1. UsetheXYPointSeries('XYPointSeriesClass'intheon-linedocumentation)classtoadddatatoaChartcontrol.
2. UsetheXYPlotArea('XYPlotAreaClass'intheon-linedocumentation)classtocreatetheplotarea.3. Setthelocationandsizeoftheplotarea.4. Addtheseriestotheplotarea.5. Createalabelandlegendforthechart.6. Createachartmodelandaddtheplotarea,label,andlegendtothemodel.7. Createachartandaddthechartmodeltoit.
Example
ThefollowingexampledemonstratesusingunbounddatatocreateanXYpointchart.
C#XYPointSeries series0 = new XYPointSeries();series0.SeriesName = "Series 0";series0.XValues.Add(1.0);series0.XValues.Add(2.0);
Spread Windows Forms Developer’s Guide 629
Copyright © GrapeCity, Inc. All rights reserved.
series0.XValues.Add(4.0);series0.XValues.Add(8.0);series0.YValues.Add(2.0);series0.YValues.Add(4.0);series0.YValues.Add(3.0);series0.YValues.Add(5.0);XYPointSeries series1 = new XYPointSeries();series1.SeriesName = "Series 1";series1.XValues.Add(1.0);series1.XValues.Add(3.0);series1.XValues.Add(5.0);series1.XValues.Add(7.0);series1.YValues.Add(1.0);series1.YValues.Add(2.0);series1.YValues.Add(4.0);series1.YValues.Add(8.0);XYPlotArea plotArea = new XYPlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.Series.Add(series0);plotArea.Series.Add(series1);LabelArea label = new LabelArea();label.Text = "XY Point Chart";label.Location = new PointF(0.5f, 0.02f);label.AlignmentX = 0.5f;label.AlignmentY = 0.0f;LegendArea legend = new LegendArea();legend.Location = new PointF(0.98f, 0.5f);legend.AlignmentX = 1.0f;legend.AlignmentY = 0.5f;ChartModel model = new ChartModel();model.LabelAreas.Add(label);model.LegendAreas.Add(legend);model.PlotAreas.Add(plotArea);chart2DControl1.Model = model;
VBDim series0 As New FarPoint.Win.Chart.XYPointSeries()series0.SeriesName = "Series 0"series0.XValues.Add(1.0)series0.XValues.Add(2.0)series0.XValues.Add(4.0)series0.XValues.Add(8.0)series0.YValues.Add(2.0)series0.YValues.Add(4.0)series0.YValues.Add(3.0)series0.YValues.Add(5.0)Dim series1 As New FarPoint.Win.Chart.XYPointSeries()series1.SeriesName = "Series 1"series1.XValues.Add(1.0)series1.XValues.Add(3.0)series1.XValues.Add(5.0)series1.XValues.Add(7.0)series1.YValues.Add(1.0)series1.YValues.Add(2.0)series1.YValues.Add(4.0)
Spread Windows Forms Developer’s Guide 630
Copyright © GrapeCity, Inc. All rights reserved.
series1.YValues.Add(8.0)Dim plotArea As New FarPoint.Win.Chart.XYPlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.Series.Add(series0)plotArea.Series.Add(series1)Dim label As New FarPoint.Win.Chart.LabelArea()label.Text = "XY Point Chart"label.Location = New PointF(0.5F, 0.02F)label.AlignmentX = 0.5Flabel.AlignmentY = 0.0FDim legend As New FarPoint.Win.Chart.LegendArea()legend.Location = New PointF(0.98F, 0.5F)legend.AlignmentX = 1.0Flegend.AlignmentY = 0.5FDim model As New FarPoint.Win.Chart.ChartModel()model.LabelAreas.Add(label)model.LegendAreas.Add(legend)model.PlotAreas.Add(plotArea)Chart2DControl1.Model = model
UsingtheChartDesigner
1. SelectthePlotAreaCollectioneditor.2. Clickthedrop-downbuttonontherightsideoftheAddbutton(lower,leftsideofdialog).3. SelecttheXYPlotAreaoptionandsetpropertiesasneeded.
Creating an XYZ Plot
YoucancreateanXYZPlotchartusingcodeorthedesigner.ThefollowingimageshowsanXYZPlotpointtypechart.
Spread Windows Forms Developer’s Guide 631
Copyright © GrapeCity, Inc. All rights reserved.
FordetailsontheAPI,seetheXYZPlotArea('XYZPlotAreaClass'intheon-linedocumentation)class.
ThefollowingclassesarealsoavailablewhencreatingXYZplottypecharts:
XYZSeries('XYZSeriesClass'intheon-linedocumentation)XYZPointSeries('XYZPointSeriesClass'intheon-linedocumentation)XYZSurfaceSeries('XYZSurfaceSeriesClass'intheon-linedocumentation)XYZLineSeries('XYZLineSeriesClass'intheon-linedocumentation)
UsingCode
1. UsetheXYZPointSeries('XYZPointSeriesClass'intheon-linedocumentation)classtoadddatatoaChartcontrol.
2. UsetheXYZPlotArea('XYZPlotAreaClass'intheon-linedocumentation)classtocreatetheplotarea.3. Setthelocationandsizeoftheplotarea.4. Addtheseriestotheplotarea.5. Createalabelandlegendforthechart.6. Createachartmodelandaddtheplotarea,label,andlegendtothemodel.7. Createachartandaddthechartmodeltoit.
Example
ThefollowingexampledemonstratesusingunbounddatatocreateanXYZpointchart.
C#FarPoint.Win.Chart.XYZPointSeries series0 = new FarPoint.Win.Chart.XYZPointSeries();series0.SeriesName = "Series 0";
Spread Windows Forms Developer’s Guide 632
Copyright © GrapeCity, Inc. All rights reserved.
series0.XValues.Add(1.0);series0.XValues.Add(2.0);series0.XValues.Add(4.0);series0.XValues.Add(8.0);series0.YValues.Add(2.0);series0.YValues.Add(4.0);series0.YValues.Add(3.0);series0.YValues.Add(5.0);series0.ZValues.Add(1.0);series0.ZValues.Add(2.0);series0.ZValues.Add(1.0);series0.ZValues.Add(2.0);FarPoint.Win.Chart.XYZPointSeries series1 = new FarPoint.Win.Chart.XYZPointSeries();series1.SeriesName = "Series 1";series1.XValues.Add(1.0);series1.XValues.Add(3.0);series1.XValues.Add(5.0);series1.XValues.Add(8.0);series1.YValues.Add(1.0);series1.YValues.Add(2.0);series1.YValues.Add(4.0);series1.YValues.Add(8.0);series1.ZValues.Add(4.0);series1.ZValues.Add(3.0);series1.ZValues.Add(4.0);series1.ZValues.Add(3.0);FarPoint.Win.Chart.XYZPlotArea plotArea = new FarPoint.Win.Chart.XYZPlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.Rotation = -21;plotArea.Elevation = 15;plotArea.Series.Add(series0);plotArea.Series.Add(series1);FarPoint.Win.Chart.LabelArea label = new FarPoint.Win.Chart.LabelArea();label.Text = "XYZ Point Chart";label.Location = new PointF(0.5f, 0.02f);label.AlignmentX = 0.5f;label.AlignmentY = 0.0f;FarPoint.Win.Chart.LegendArea legend = new FarPoint.Win.Chart.LegendArea();legend.Location = new PointF(0.98f, 0.5f);legend.AlignmentX = 1.0f;legend.AlignmentY = 0.5f;FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();model.LabelAreas.Add(label);model.LegendAreas.Add(legend);model.PlotAreas.Add(plotArea);fpChart1.Model = model;
VBDim series0 As New FarPoint.Win.Chart.XYZPointSeries()series0.SeriesName = "Series 0"series0.XValues.Add(1.0)series0.XValues.Add(2.0)series0.XValues.Add(4.0)series0.XValues.Add(8.0)series0.YValues.Add(2.0)
Spread Windows Forms Developer’s Guide 633
Copyright © GrapeCity, Inc. All rights reserved.
series0.YValues.Add(4.0)series0.YValues.Add(3.0)series0.YValues.Add(5.0)series0.ZValues.Add(1.0)series0.ZValues.Add(2.0)series0.ZValues.Add(1.0)series0.ZValues.Add(2.0)Dim series1 As New FarPoint.Win.Chart.XYZPointSeries()series1.SeriesName = "Series 1"series1.XValues.Add(1.0)series1.XValues.Add(3.0)series1.XValues.Add(5.0)series1.XValues.Add(8.0)series1.YValues.Add(1.0)series1.YValues.Add(2.0)series1.YValues.Add(4.0)series1.YValues.Add(8.0)series1.ZValues.Add(4.0)series1.ZValues.Add(3.0)series1.ZValues.Add(4.0)series1.ZValues.Add(3.0)Dim plotArea As New FarPoint.Win.Chart.XYZPlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.Elevation = 15plotArea.Rotation = -21plotArea.Series.Add(series0)plotArea.Series.Add(series1)Dim label As New FarPoint.Win.Chart.LabelArea()label.Text = "XYZ Point Chart"label.Location = New PointF(0.5F, 0.02F)label.AlignmentX = 0.5Flabel.AlignmentY = 0.0FDim legend As New FarPoint.Win.Chart.LegendArea()legend.Location = New PointF(0.98F, 0.5F)legend.AlignmentX = 1.0Flegend.AlignmentY = 0.5FDim model As New FarPoint.Win.Chart.ChartModel()model.LabelAreas.Add(label)model.LegendAreas.Add(legend)model.PlotAreas.Add(plotArea)fpChart1.Model = model
UsingtheChartDesigner
1. SelectthePlotAreaCollectioneditor.2. Clickthedrop-downbuttonontherightsideoftheAddbutton(lower,leftsideofdialog).3. SelecttheXYZPlotAreaoptionandsetpropertiesasneeded.
Creating a Pie Plot
Youcancreateapieplotchartusingcodeorthedesigner.ThefollowingimageshowsaPiePlottypechart.
Spread Windows Forms Developer’s Guide 634
Copyright © GrapeCity, Inc. All rights reserved.
FordetailsontheAPI,seethePiePlotArea('PiePlotAreaClass'intheon-linedocumentation)class.
ThefollowingclassisalsoavailablewhencreatingPieplottypecharts:
PieSeries('PieSeriesClass'intheon-linedocumentation)
UsingCode
1. UsethePieSeries('PieSeriesClass'intheon-linedocumentation)classtoadddatatoaChartcontrol.2. UsethePiePlotArea('PiePlotAreaClass'intheon-linedocumentation)classtocreatetheplotarea.3. Setthelocationandsizeoftheplotarea.4. Addtheseriestotheplotarea.5. Createalabelandlegendforthechart.6. Createachartmodelandaddtheplotarea,label,andlegendtothemodel.7. Createachartandaddthechartmodeltoit.
Example
ThefollowingexampledemonstratesusingunbounddatatocreateaPiechart.
C#PieSeries series = new PieSeries();series.SeriesName = "Series 0";series.Values.Add(1.0);series.Values.Add(2.0);series.Values.Add(4.0);series.Values.Add(8.0);PiePlotArea plotArea = new PiePlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.Series.Add(series);LabelArea label = new LabelArea();label.Text = "Pie Chart";label.Location = new PointF(0.5f, 0.02f);label.AlignmentX = 0.5f;label.AlignmentY = 0.0f;LegendArea legend = new LegendArea();legend.Location = new PointF(0.98f, 0.5f);legend.AlignmentX = 1.0f;legend.AlignmentY = 0.5f;ChartModel model = new ChartModel();model.LabelAreas.Add(label);model.LegendAreas.Add(legend);model.PlotAreas.Add(plotArea);
Spread Windows Forms Developer’s Guide 635
Copyright © GrapeCity, Inc. All rights reserved.
chart2DControl1.Model = model;
VBDim series As New FarPoint.Win.Chart.PieSeries()series.SeriesName = "Series 0"series.Values.Add(1.0)series.Values.Add(2.0)series.Values.Add(4.0)series.Values.Add(8.0)Dim plotArea As New FarPoint.Win.Chart.PiePlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.Series.Add(series)Dim label As New FarPoint.Win.Chart.LabelArea()label.Text = "Pie Chart"label.Location = New PointF(0.5F, 0.02F)label.AlignmentX = 0.5Flabel.AlignmentY = 0.0FDim legend As New FarPoint.Win.Chart.LegendArea()legend.Location = New PointF(0.98F, 0.5F)legend.AlignmentX = 1.0Flegend.AlignmentY = 0.5FDim model As New FarPoint.Win.Chart.ChartModel()model.LabelAreas.Add(label)model.LegendAreas.Add(legend)model.PlotAreas.Add(plotArea)chart2DControl1.Model = model
UsingtheChartDesigner
1. SelectthePlotAreaCollectioneditor.2. Clickthedrop-downbuttonontherightsideoftheAddbutton(lower,leftsideofdialog).3. SelectthePiePlotAreaoptionandsetpropertiesasneeded.
Creating a Polar Plot
Youcancreateapolarplotchartusingcodeorthedesigner.ThefollowingimageshowsaPolarPlottypechart.
Spread Windows Forms Developer’s Guide 636
Copyright © GrapeCity, Inc. All rights reserved.
FordetailsontheAPI,seethePolarPlotArea('PolarPlotAreaClass'intheon-linedocumentation)class.
ThefollowingclassesarealsoavailablewhencreatingPolarplottypecharts:
PolarSeries('PolarSeriesClass'intheon-linedocumentation)PolarAreaSeries('PolarAreaSeriesClass'intheon-linedocumentation)PolarPointSeries('PolarPointSeriesClass'intheon-linedocumentation)PolarLineSeries('PolarLineSeriesClass'intheon-linedocumentation)PolarAngleAxis('PolarAngleAxisClass'intheon-linedocumentation)PolarRadiusAxis('PolarRadiusAxisClass'intheon-linedocumentation)
UsingCode
1. UsethePolarPointSeries('PolarPointSeriesClass'intheon-linedocumentation)classtoadddatatoaChartcontrol.
2. UsethePolarPlotArea('PolarPlotAreaClass'intheon-linedocumentation)classtocreatetheplotarea.
3. Setthelocationandsizeoftheplotarea.4. Addtheseriestotheplotarea.5. Createalabelandlegendforthechart.6. Createachartmodelandaddtheplotarea,label,andlegendtothemodel.7. Createachartandaddthechartmodeltoit.
Example
Thefollowingexampledemonstratesusingunbounddatatocreateapolarpointserieschart.
C#FarPoint.Win.Chart.PolarPointSeries series0 = new FarPoint.Win.Chart.PolarPointSeries();
Spread Windows Forms Developer’s Guide 637
Copyright © GrapeCity, Inc. All rights reserved.
series0.SeriesName = "Series 0";series0.XValues.Add(0.0);series0.XValues.Add(45.0);series0.XValues.Add(90.0);series0.XValues.Add(180.0);series0.XValues.Add(270.0);series0.YValues.Add(1.0);series0.YValues.Add(2.0);series0.YValues.Add(3.0);series0.YValues.Add(4.0);series0.YValues.Add(5.0);FarPoint.Win.Chart.PolarPointSeries series1 = new FarPoint.Win.Chart.PolarPointSeries();series1.SeriesName = "Series 1";series1.XValues.Add(0.0);series1.XValues.Add(45.0);series1.XValues.Add(90.0);series1.XValues.Add(180.0);series1.XValues.Add(270.0);series1.YValues.Add(2.0);series1.YValues.Add(3.0);series1.YValues.Add(4.0);series1.YValues.Add(5.0);series1.YValues.Add(6.0);FarPoint.Win.Chart.PolarPlotArea plotArea = new FarPoint.Win.Chart.PolarPlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.Series.Add(series0);plotArea.Series.Add(series1);FarPoint.Win.Chart.LabelArea label = new FarPoint.Win.Chart.LabelArea();label.Text = "Polar Point Chart";label.Location = new PointF(0.5f, 0.02f);label.AlignmentX = 0.5f;label.AlignmentY = 0.0f;FarPoint.Win.Chart.LegendArea legend = FarPoint.Win.Chart.new LegendArea();legend.Location = new PointF(0.98f, 0.5f);legend.AlignmentX = 1.0f;legend.AlignmentY = 0.5f;FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();model.LabelAreas.Add(label);model.LegendAreas.Add(legend);model.PlotAreas.Add(plotArea);chart2DControl1.Model = model;
VBDim series0 As New FarPoint.Win.Chart.PolarPointSeries()series0.SeriesName = "Series 0"series0.XValues.Add(0.0)series0.XValues.Add(45.0)series0.XValues.Add(90.0)series0.XValues.Add(180.0)series0.XValues.Add(270.0)series0.YValues.Add(1.0)series0.YValues.Add(2.0)series0.YValues.Add(3.0)series0.YValues.Add(4.0)
Spread Windows Forms Developer’s Guide 638
Copyright © GrapeCity, Inc. All rights reserved.
series0.YValues.Add(5.0)Dim series1 As New FarPoint.Win.Chart.PolarPointSeries()series1.SeriesName = "Series 1"series1.XValues.Add(0.0)series1.XValues.Add(45.0)series1.XValues.Add(90.0)series1.XValues.Add(180.0)series1.XValues.Add(270.0)series1.YValues.Add(2.0)series1.YValues.Add(3.0)series1.YValues.Add(4.0)series1.YValues.Add(5.0)series1.YValues.Add(6.0)Dim plotArea As New FarPoint.Win.Chart.PolarPlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.Series.Add(series0)plotArea.Series.Add(series1)Dim label As New FarPoint.Win.Chart.LabelArea()label.Text = "Polar Point Chart"label.Location = New PointF(0.5F, 0.02F)label.AlignmentX = 0.5Flabel.AlignmentY = 0FDim legend As New FarPoint.Win.Chart.LegendArea()legend.Location = New PointF(0.98F, 0.5F)legend.AlignmentX = 1Flegend.AlignmentY = 0.5FDim model As New FarPoint.Win.Chart.ChartModel()model.LabelAreas.Add(label)model.LegendAreas.Add(legend)model.PlotAreas.Add(plotArea)chart2DControl1.Model = model
UsingtheChartDesigner
1. SelectthePlotAreaCollectioneditor.2. Clickthedrop-downbuttonontherightsideoftheAddbutton(lower,leftsideofdialog).3. SelectthePolarPlotAreaoptionandsetpropertiesasneeded.
Creating a Radar Plot
Youcancreatearadarplotchartusingcodeorthedesigner.ThefollowingimageshowsaRadarpointtypechart.
Spread Windows Forms Developer’s Guide 639
Copyright © GrapeCity, Inc. All rights reserved.
FordetailsontheAPI,seetheRadarPlotArea('RadarPlotAreaClass'intheon-linedocumentation)class.
ThefollowingclassesarealsoavailablewhencreatingRadarplottypecharts:
RadarSeries('RadarSeriesClass'intheon-linedocumentation)PolarLineSeries('PolarLineSeriesClass'intheon-linedocumentation)RadarAreaSeries('RadarAreaSeriesClass'intheon-linedocumentation)RadarPointSeries('RadarPointSeriesClass'intheon-linedocumentation)RadarIndexAxis('RadarIndexAxisClass'intheon-linedocumentation)RadarValueAxis('RadarValueAxisClass'intheon-linedocumentation)
UsingCode
1. UsetheRadarPointSeries('RadarPointSeriesClass'intheon-linedocumentation)classtoadddatatoaChartcontrol.
2. UsetheRadarPlotArea('RadarPlotAreaClass'intheon-linedocumentation)classtocreatetheplotarea.
3. Setthelocationandsizeoftheplotarea.4. Addtheseriestotheplotarea.5. Createalabelandlegendforthechart.6. Createachartmodelandaddtheplotarea,label,andlegendtothemodel.7. Createachartandaddthechartmodeltoit.
Example
ThefollowingexampledemonstratesusingunbounddatatocreateaRadarchart.
C#FarPoint.Win.Chart.RadarPointSeries series0 = new FarPoint.Win.Chart.RadarPointSeries();series0.SeriesName = "Series 0";series0.Values.Add(1.0);
Spread Windows Forms Developer’s Guide 640
Copyright © GrapeCity, Inc. All rights reserved.
series0.Values.Add(2.0);series0.Values.Add(3.0);series0.Values.Add(4.0);series0.Values.Add(5.0);FarPoint.Win.Chart.RadarPointSeries series1 = new FarPoint.Win.Chart.RadarPointSeries();series1.SeriesName = "Series 1";series1.Values.Add(2.0);series1.Values.Add(3.0);series1.Values.Add(4.0);series1.Values.Add(5.0);series1.Values.Add(6.0);FarPoint.Win.Chart.RadarPlotArea plotArea = new FarPoint.Win.Chart.RadarPlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.Series.Add(series0);plotArea.Series.Add(series1);FarPoint.Win.Chart.LabelArea label = new FarPoint.Win.Chart.LabelArea();label.Text = "Radar Point Chart";label.Location = new PointF(0.5f, 0.02f);label.AlignmentX = 0.5f;label.AlignmentY = 0.0f;FarPoint.Win.Chart.LegendArea legend = new FarPoint.Win.Chart.LegendArea();legend.Location = new PointF(0.98f, 0.5f);legend.AlignmentX = 1.0f;legend.AlignmentY = 0.5f;FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();model.LabelAreas.Add(label);model.LegendAreas.Add(legend);model.PlotAreas.Add(plotArea);chart2DControl1.Model = model;
VBDim series0 As New FarPoint.Win.Chart.RadarPointSeries()series0.SeriesName = "Series 0"series0.Values.Add(1.0)series0.Values.Add(2.0)series0.Values.Add(3.0)series0.Values.Add(4.0)series0.Values.Add(5.0)Dim series1 As New FarPoint.Win.Chart.RadarPointSeries()series1.SeriesName = "Series 1"series1.Values.Add(2.0)series1.Values.Add(3.0)series1.Values.Add(4.0)series1.Values.Add(5.0)series1.Values.Add(6.0)Dim plotArea As New FarPoint.Win.Chart.RadarPlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.Series.Add(series0)plotArea.Series.Add(series1)Dim label As New FarPoint.Win.Chart.LabelArea()label.Text = "Radar Point Chart"label.Location = New PointF(0.5F, 0.02F)label.AlignmentX = 0.5F
Spread Windows Forms Developer’s Guide 641
Copyright © GrapeCity, Inc. All rights reserved.
label.AlignmentY = 0FDim legend As New FarPoint.Win.Chart.LegendArea()legend.Location = New PointF(0.98F, 0.5F)legend.AlignmentX = 1Flegend.AlignmentY = 0.5FDim model As New FarPoint.Win.Chart.ChartModel()model.LabelAreas.Add(label)model.LegendAreas.Add(legend)model.PlotAreas.Add(plotArea)chart2DControl1.Model = model
UsingtheChartDesigner
1. SelectthePlotAreaCollectioneditor.2. Clickthedrop-downbuttonontherightsideoftheAddbutton(lower,leftsideofdialog).3. SelecttheRadarPlotAreaoptionandsetpropertiesasneeded.
Combining Plot Types
Multipleseriesfromthesamemajorcategoryarecompatiblewitheachotherandcanbecombinedinasingleplotarea.Forexample,abarseriesandalineseriescanbecombinedtogetherinaYPlotArea.
FordetailsontheAPI,seetheYPlotArea('YPlotAreaClass'intheon-linedocumentation)class.
Thefollowingclassesareusedtocreatethebarandlineseriesexample:
BarSeries('BarSeriesClass'intheon-linedocumentation)LineSeries('LineSeriesClass'intheon-linedocumentation)
UsingCode
1. UsetheBarSeries('BarSeriesClass'intheon-linedocumentation)andLineSeries('LineSeriesClass'intheon-linedocumentation)classestoadddatatotheChartcontrol.
2. UsetheYPlotArea('YPlotAreaClass'intheon-linedocumentation)classtocreatetheplotarea.3. Setthelocationandsizeoftheplotarea.4. Addbothseriestotheplotarea.5. Createalabelforthechart.
Spread Windows Forms Developer’s Guide 642
Copyright © GrapeCity, Inc. All rights reserved.
6. Createachartmodelandaddtheplotareaandlabeltothemodel.7. Createachartandaddthechartmodeltoit.
Example
Thefollowingexampledemonstratesusingunbounddatatocreateachartthatusesabarseriesandalineseries.
C#BarSeries series0 = new BarSeries();series0.Values.Add(8.0);series0.Values.Add(4.0);series0.Values.Add(2.0);series0.Values.Add(1.0);LineSeries series1 = new LineSeries();series1.PointMarker = new BuiltinMarker(MarkerShape.Circle, 7.0f);series1.Values.Add(8.0);series1.Values.Add(12.0);series1.Values.Add(14.0);series1.Values.Add(15.0);YPlotArea plotArea = new YPlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.Series.Add(series0);plotArea.Series.Add(series1);LabelArea label = new LabelArea();label.Location = new PointF(0.5f, 0.02f);label.AlignmentX = 0.5f;label.AlignmentY = 0.0f;label.Text = "Pareto Chart";ChartModel model = new ChartModel();model.LabelAreas.Add(label);model.PlotAreas.Add(plotArea);chart2DControl1.Model = model;
VBDim series0 As New FarPoint.Win.Chart.BarSeries()series0.Values.Add(8.0)series0.Values.Add(4.0)series0.Values.Add(2.0)series0.Values.Add(1.0)Dim series1 As New FarPoint.Win.Chart.LineSeries()series1.PointMarker = New FarPoint.Win.Chart.BuiltinMarker(FarPoint.Win.Chart.MarkerShape.Circle, 7.0F)series1.Values.Add(8.0)series1.Values.Add(12.0)series1.Values.Add(14.0)series1.Values.Add(15.0)Dim plotArea As New FarPoint.Win.Chart.YPlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.Series.Add(series0)plotArea.Series.Add(series1)Dim labelArea As New FarPoint.Win.Chart.LabelArea()labelArea.Location = New PointF(0.5F, 0.02F)labelArea.AlignmentX = 0.5F
Spread Windows Forms Developer’s Guide 643
Copyright © GrapeCity, Inc. All rights reserved.
labelArea.AlignmentY = 0.0FlabelArea.Text = "Pareto Chart"Dim model As New FarPoint.Win.Chart.ChartModel()model.LabelAreas.Add(labelArea)model.PlotAreas.Add(plotArea)Chart2DControl1.Model = model
Connecting to Data
Thechartcontrolcanbeboundorunbound.Ifthecontrolisunbound,providethevaluesasdoublevalues.
Whenthechartisbound,thevaluescananydatatypethatcanbeconvertedtoadoublevalue(includingint,double,decimal,string,andsoon).
FormoreinformationonaddingdatatoaChartcontrol,seethefollowingtopics:
UsingaBoundDataSourceUsinganUnBoundDataSourceUsingRawandRepresentedData
Using a Bound Data Source
Youcanbindthecharttothefollowingdatasources:
ArrayArrayList(IList)ListCollectionTable
Whenthechartisboundtodata,itdynamicallyplotsthedatawhenitpaints.Asinglechartcansupport(anddisplay)datafrommultipledatasourcesandmultipledatafieldswithinadatasource.FormoreinformationabouttheDataSourceproperty,refertothespecificcharttypeintheAssemblyReference(forexample:SeriesNameDataSourceintheRadarLineSeries('RadarLineSeriesClass'intheon-linedocumentation)class).
UsingCode
Createadatasourceandthenbindthecontrol.
Example
Thefollowingexampledemonstrateshowtobindthecontroltoadatasource.
C#// Create an array and bind the controlobject[] values = new object[] { 2, 4.0, 3.0m, "5.0" };BarSeries series = new BarSeries();series.Values.DataSource = values;
VB' Create an array and bind the controlDim values() As Object = {2, 4.0, 3.0D, "5.0"}Dim series As New BarSeries()series.Values.DataSource = values
Spread Windows Forms Developer’s Guide 644
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
Createadatasourceandthenbindthecontrol.
Example
Thefollowingexampledemonstrateshowtobindthecontroltoadatatable.
C#DataTable dt = new DataTable("Test");DataRow dr = default(DataRow);dt.Columns.Add("Series0");dt.Columns.Add("Series1");dr = dt.NewRow();dr[0] = 2;dr[1] = 1;dt.Rows.Add(dr);dr = dt.NewRow();dr[0] = 4;dr[1] = 2;dt.Rows.Add(dr);dr = dt.NewRow();dr[0] = 3;dr[1] = 4;FarPoint.Win.Chart.BarSeries series = new FarPoint.Win.Chart.BarSeries();series.Values.DataSource = dt;series.Values.DataField = dt.Columns[0].ColumnName;FarPoint.Win.Chart.YPlotArea plotArea = new FarPoint.Win.Chart.YPlotArea();FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();plotArea.Location = new PointF(0.2F, 0.2F);plotArea.Size = new SizeF(0.6F, 0.6F);plotArea.Series.Add(series);model.PlotAreas.Add(plotArea);fpChart1.Model = model;
VBDim dt As New DataTable("Test")Dim dr As DataRowdt.Columns.Add("Series0")dt.Columns.Add("Series1")dr = dt.NewRow()dr(0) = 2dr(1) = 1dt.Rows.Add(dr)dr = dt.NewRow()dr(0) = 4dr(1) = 2dt.Rows.Add(dr)dr = dt.NewRow()dr(0) = 3dr(1) = 4dt.Rows.Add(dr)Dim series As New FarPoint.Win.Chart.BarSeriesseries.Values.DataSource = dtseries.Values.DataField = dt.Columns(0).ColumnName
Spread Windows Forms Developer’s Guide 645
Copyright © GrapeCity, Inc. All rights reserved.
Dim model As New FarPoint.Win.Chart.ChartModel()Dim plotArea As New FarPoint.Win.Chart.YPlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.Series.Add(series)model.PlotAreas.Add(plotArea)FpChart1.Model = model
Using an UnBound Data Source
Youcanadddoublevaluestothechartcontrolwithoutusingadatasource.
UsingCode
Adddatatotheseries.
Example
Thefollowingexampledemonstratesaddingunbounddatatothecontrol.
C#BarSeries series = new BarSeries();series.Values.Add(2.0);series.Values.Add(4.0);series.Values.Add(3.0);series.Values.Add(5.0);
VBDim series As New BarSeries()series.Values.Add(2.0)series.Values.Add(4.0)series.Values.Add(3.0)series.Values.Add(5.0)
UsingtheChartDesigner
1. SelectthePlotAreaCollectioneditor.2. SelecttheSeriesCollectioneditor.3. SelecttheValuesCollectioneditor.4. Setvaluesasneeded.
Using Raw and Represented Data
Youcansetthescaleofthedatabeforedisplayingthedata.
Forexample,ifthedatavaluesareinthemillions,youmaywishtodisplaythemusingamuchsmallerscalesuchashundreds(100,000,000vs100).UsetheDisplayUnitspropertyintheValueAxisclasstosetthescale.
UsingCode
UsetheDisplayUnitspropertytocreateasmallerscaleontheaxis.
Spread Windows Forms Developer’s Guide 646
Copyright © GrapeCity, Inc. All rights reserved.
Example
ThefollowingexampleusestheDisplayUnitsproperty.
C#FarPoint.Win.Chart.BarSeries series = new FarPoint.Win.Chart.BarSeries();series.Values.Add(10000.0);series.Values.Add(20000.0);series.Values.Add(40000.0);series.Values.Add(80000.0);FarPoint.Win.Chart.YPlotArea plotArea = new FarPoint.Win.Chart.YPlotArea();plotArea.Location = new PointF(0.2F, 0.2F);plotArea.Size = new SizeF(0.6F, 0.6F);plotArea.XAxis.Title = "Entry";plotArea.XAxis.TitleVisible = true;plotArea.YAxes[0].DisplayUnits = 1000.0;plotArea.Series.Add(series);FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();model.PlotAreas.Add(plotArea);FarPoint.Win.Spread.Chart.SpreadChart chart = new FarPoint.Win.Spread.Chart.SpreadChart();chart.Size = new Size(200, 200);chart.Location = new Point(100, 100);chart.Model = model;fpSpread1.Sheets[0].Charts.Add(chart);
VBDim series As New FarPoint.Win.Chart.BarSeries()series.Values.Add(10000.0)series.Values.Add(20000.0)series.Values.Add(40000.0)series.Values.Add(80000.0)Dim plotArea As New FarPoint.Win.Chart.YPlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.XAxis.Title = "Entry" 'IndexAxisplotArea.XAxis.TitleVisible = True 'IndexAxisplotArea.YAxes(0).DisplayUnits = 1000.0 'ValueAxisplotArea.Series.Add(series)Dim model As New FarPoint.Win.Chart.ChartModel()model.PlotAreas.Add(plotArea)Dim chart As New FarPoint.Win.Spread.Chart.SpreadChart()chart.Size = New Size(200, 200)chart.Location = New Point(100, 100)chart.Model = modelFpSpread1.Sheets(0).Charts.Add(chart)
Saving or Loading a Chart
YoucanreadorwritetoafileorstreamusingtheIXmlSerializableinterface.
Youcanalsosaveandloadxmlfilesatdesigntime.Selectthearrowiconatthetoprightedgeofthecontrolafterdrawingthecontrolontheformtoseethemenuoptions.
Spread Windows Forms Developer’s Guide 647
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
Usegeneralmethodstosavetoafile.
Example
Thefollowingcodewritestoafile.
C#ChartModel model = fpChart1.Model;XmlTextWriter writer = new XmlTextWriter("c:\\home\\temp\\test.xml", null);model.WriteXml(writer);writer.Close();
VBDim model As ChartModel = fpChart1.ModelDim writer As New XmlTextWriter("c:\home\temp\test.xml", Nothing)model.WriteXml(writer)writer.Close()
UsingCode
Usegeneralmethodstoreadfromafile.
Example
Thefollowingcodereadsfromafile.
C#ChartModel model = fpChart1.Model;XmlTextReader reader = new XmlTextReader("c:\\home\\temp\\test.xml");model.ReadXml(reader);reader.Close();
VBDim model As ChartModel = fpChart1.ModelDim reader As New XmlTextReader("c:\home\temp\test.xml")model.ReadXml(reader)reader.Close()
UsingtheDesigner
1. Selectthearrowiconatthetoprightedgeofthecontrolafterdrawingthecontrolontheformtoseethemenuoptions.
2. ChooseSavetoXMLorLoadfromXML.
Using the Chart Designer
Thechartdesignergraphicalinterfacesavestimeandeffortandprovidesavisualrepresentationofthechartcontrolasyouchangesettingsinthedesigner.YoucanapplythechangestothecontrolorsavethechangestoanXMLformattedfile.
Spread Windows Forms Developer’s Guide 648
Copyright © GrapeCity, Inc. All rights reserved.
HerearetopicstohelpyouusetheChartDesigner:
OpeningtheChartDesignerCreatingaChartControlChartCollectionEditorsChartDesignerToolbar
Opening the Chart Designer
YoucanopenthedesignerbyclickingonthearrowatthetoprightedgeofthecontrolwhenitisonaforminVisualStudio.ThenclickontheDesignermenuoptiontoloadthechartdesigner.
Thisopensthedesignerwiththevariouseditorsthatcanbeusedtocustomizethechartcontrol.
Spread Windows Forms Developer’s Guide 649
Copyright © GrapeCity, Inc. All rights reserved.
Creating a Chart Control
ThefollowingstepsshowhowtocreateaPiechartusingthedesigner.
1.Openthedesigner(clickonthearrowatthetoprightedgeofthecontrolwhenitisonaforminVisualStudioorclickontheDesignermenuoptiontoloadthechartdesigner).
2.ClickonthePlotAreaCollectiondrop-downbutton.TheYPlotAreaisalreadyselected.ClickRemove.ThenclickAddandselectthePiePlotArea.
3.SelecttheSeriesCollectiondrop-downbutton.
Spread Windows Forms Developer’s Guide 650
Copyright © GrapeCity, Inc. All rights reserved.
4.ClicktheAddbuttonintheSeriesCollectionEditor.ThenselecttheValuesCollectiondrop-downbutton.
5.ClicktheAddbuttonandaddmultipledatavalues.Typeadoublevalueinthetextareaontherightsideoftheeditor.
Spread Windows Forms Developer’s Guide 651
Copyright © GrapeCity, Inc. All rights reserved.
6.SelectOKonthethreedialogs.ClickApplyandOKtoapplythedesignerchangestothecontrolandclosethedesigner.TheLabelAreaCollectioneditorcanbeusedtochangethetextofthelegend(fromBartoPie,forexample).
Spread Windows Forms Developer’s Guide 652
Copyright © GrapeCity, Inc. All rights reserved.
Chart Collection Editors
Thereareseveraleditorsthatcanbeusedtoeditareasofthechartcontrol.Openthechartdesignerandselecttheappropriatecollectiondrop-downundertheMiscsection.
LabelCollectionEditorLegendCollectionEditorPlotCollectionEditorLightCollectionEditorSeriesCollectionEditor
Label Collection Editor
TheLabelAreaCollectionEditorcanbeusedtocreatelabelsforthechartandappearsasfollows:
Spread Windows Forms Developer’s Guide 653
Copyright © GrapeCity, Inc. All rights reserved.
Legend Collection Editor
TheLegendAreaCollectionEditorcanbeusedtocreatelegendsforthechartandappearsasfollows:
Plot Collection Editor
Spread Windows Forms Developer’s Guide 654
Copyright © GrapeCity, Inc. All rights reserved.
ThePlotAreaCollectionEditorcanbeusedtocreateplotsforthechartandappearsasfollows:
Light Collection Editor
TheLightCollectionEditorcanbeusedtocreatelightingeffectsforthechartandappearsasfollows:
Spread Windows Forms Developer’s Guide 655
Copyright © GrapeCity, Inc. All rights reserved.
TheLightCollectionEditorisundertheAppearancesectionafteryouselectthePlotAreasCollection.YoucanalsoselectaplotareafromthediagramontheleftsideofthedesignerandthenselecttheLightCollectionundertheAppearancesection.
Series Collection Editor
TheSeriesCollectionEditorcanbeusedtosetborders,barshapes,andfilloptions,addchartdata,specifylabelsandnames,andotheroptions.Theeditorappearsasfollows:
TheSeriesCollectionEditorisundertheDatasectionafteryouselectthePlotAreasCollection.YoucanalsoselectaplotareafromthediagramontheleftsideofthedesignerandthenselecttheSeriesCollectionundertheDatasection.
Chart Designer Toolbar
TheChartDesignericonscanbeusedtosavethecharttoafile,changethechartviewtype,addorremoveitems,elevateorrotatethechart,andeditdatapoints.
Spread Windows Forms Developer’s Guide 656
Copyright © GrapeCity, Inc. All rights reserved.
Icon DescriptionOpen ThisallowsyoutoopenthechartcontrolfromanXMLfile.
Save ThisallowsyoutoopenthechartcontroltoanXMLfile.
ChartViewType
Thisallowsyoutochangetheviewtypeto2Dor3D.
AddItems Thisallowsyoutoadditemstothechart(drop-downlistundertheAddoption).
RemoveItems
Thisallowsyoutomoveupordownthelistifyouhavecreatedmultipleseries.
Elevation Thisallowsyoutorotatethegraphcounterclockwisearoundthehorizontalaxis.
Rotation Thisallowsyoutorotatethegraphcounterclockwisearoundtheverticalaxis.
EndPointData
Thisallowsyoutobringupthedatapointsinthechart(addedwiththeDoubleCollectionEditorunderPlotAreas,Series,andValues).
Using the Chart Control
Youcanaddchartsusingcode,theSpreaddesigner,ortheChartdesigner.Youcanalsobindchartsandlettheendusermakechangestothechartatruntime.Formoreinformation,seethefollowingtopics:
AddingaChartControlChangingChartOptionsUsingtheChartDesignerBindingtheChartControlAllowingtheUsertoChangetheChartAddingaContextMenu
Adding a Chart Control
YoucanaddachartcontroltothesheetusingcodeortheSpreaddesigner.Youcanalsoallowtheusertoresizethechartandtherangeofdatausedinthechartcontrol.ThefollowingimageshowstheChartsectionintheSpreadDesignerundertheInsertmenu.ThesecondimageshowstheChartToolsmenuoptionwhichisdisplayedafterachartisadded.
Spread Windows Forms Developer’s Guide 657
Copyright © GrapeCity, Inc. All rights reserved.
UsingtheSpreadDesignerorEditChartVerb
1. OpentheSpreadDesignerandtypechartdatainthecells(similartothedatainthecodeexampleafterthissection).
2. Selectarangeofcellswithdata.3. ClickontheInsertmenuoptionandthenpickthecharttype(seetheaboveimage).4. TheChartToolmenuwillappearwithadditionaloptions.5. ClosetheSpreadDesignerandsavethechanges.
or
1. ClickontheFpSpread1_Sheet1objectatthebottomofthepage.2. ClickonthearrowatthetoprightoftheobjectandselectEditCharts.
3. ThisbringsuptheSpreadChartCollectionEditor.ClickAddtoaddachartandthensetthechartproperties.
Spread Windows Forms Developer’s Guide 658
Copyright © GrapeCity, Inc. All rights reserved.
4. TheAddbuttonhasadrop-downmenuwithcharttypeoptions(bar,forexample).
Spread Windows Forms Developer’s Guide 659
Copyright © GrapeCity, Inc. All rights reserved.
5. SelectModelintheSpreadChartCollectionEditortobringupthechartdesignerorchoosethePlotAreasCollectionunderModel.UsetheAddbuttondrop-downmenutoselectaplotareatype(YPlotArea,forexample).
6. UsetheSeriesCollectiontoaddaseriestype(BarSeries,forexample).TheAddbuttonhasadrop-downforthetypesofseriesyoucanadd.
7. UsetheValuesCollectiontobringuptheDoubleCollectionEditorthatcanbeusedtoadddatatothechart.
Spread Windows Forms Developer’s Guide 660
Copyright © GrapeCity, Inc. All rights reserved.
8. SelectOKforeachdialog.
UsingCode
YoucanaddachartcontroltotheSpreadcontrolusingcode.Thisexamplecreatesdataincellsandthenaddsthechartcontrol.
Example
C#fpSpread1.Sheets[0].Cells[0, 1].Value = "c1";fpSpread1.Sheets[0].Cells[0, 2].Value = "c2";fpSpread1.Sheets[0].Cells[0, 3].Value = "c3";fpSpread1.Sheets[0].Cells[1, 0].Value = "s1";fpSpread1.Sheets[0].Cells[2, 0].Value = "s2";fpSpread1.Sheets[0].Cells[3, 0].Value = "s3";fpSpread1.Sheets[0].Cells[4, 0].Value = "s4";fpSpread1.Sheets[0].Cells[5, 0].Value = "s5";fpSpread1.Sheets[0].Cells[6, 0].Value = "s6";fpSpread1.Sheets[0].Cells[1, 1].Value = 1;fpSpread1.Sheets[0].Cells[2, 1].Value = 2;fpSpread1.Sheets[0].Cells[3, 1].Value = 3;fpSpread1.Sheets[0].Cells[4, 1].Value = 4;fpSpread1.Sheets[0].Cells[5, 1].Value = 5;fpSpread1.Sheets[0].Cells[6, 1].Value = 6;
Spread Windows Forms Developer’s Guide 661
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.Sheets[0].Cells[1, 2].Value = 7;fpSpread1.Sheets[0].Cells[2, 2].Value = 8;fpSpread1.Sheets[0].Cells[3, 2].Value = 9;fpSpread1.Sheets[0].Cells[4, 2].Value = 10;fpSpread1.Sheets[0].Cells[5, 2].Value = 11;fpSpread1.Sheets[0].Cells[6, 2].Value = 12;fpSpread1.Sheets[0].Cells[1, 3].Value = 13;fpSpread1.Sheets[0].Cells[2, 3].Value = 14;fpSpread1.Sheets[0].Cells[3, 3].Value = 15;fpSpread1.Sheets[0].Cells[4, 3].Value = 16;fpSpread1.Sheets[0].Cells[5, 3].Value = 17;fpSpread1.Sheets[0].Cells[6, 3].Value = 18;FarPoint.Win.Spread.Model.CellRange range = new FarPoint.Win.Spread.Model.CellRange(0, 0, 7, 4);fpSpread1.Sheets[0].AddChart(range, typeof(FarPoint.Win.Chart.BarSeries), 400, 300, 0, 0, FarPoint.Win.Chart.ChartViewType.View3D, false);
VBFpSpread1.Sheets(0).Cells(0, 1).Value = "c1"FpSpread1.Sheets(0).Cells(0, 2).Value = "c2"FpSpread1.Sheets(0).Cells(0, 3).Value = "c3"FpSpread1.Sheets(0).Cells(1, 0).Value = "s1"FpSpread1.Sheets(0).Cells(2, 0).Value = "s2"FpSpread1.Sheets(0).Cells(3, 0).Value = "s3"FpSpread1.Sheets(0).Cells(4, 0).Value = "s4"FpSpread1.Sheets(0).Cells(5, 0).Value = "s5"FpSpread1.Sheets(0).Cells(6, 0).Value = "s6"FpSpread1.Sheets(0).Cells(1, 1).Value = 1FpSpread1.Sheets(0).Cells(2, 1).Value = 2FpSpread1.Sheets(0).Cells(3, 1).Value = 3FpSpread1.Sheets(0).Cells(4, 1).Value = 4FpSpread1.Sheets(0).Cells(5, 1).Value = 5FpSpread1.Sheets(0).Cells(6, 1).Value = 6FpSpread1.Sheets(0).Cells(1, 2).Value = 7FpSpread1.Sheets(0).Cells(2, 2).Value = 8FpSpread1.Sheets(0).Cells(3, 2).Value = 9FpSpread1.Sheets(0).Cells(4, 2).Value = 10FpSpread1.Sheets(0).Cells(5, 2).Value = 11FpSpread1.Sheets(0).Cells(6, 2).Value = 12FpSpread1.Sheets(0).Cells(1, 3).Value = 13FpSpread1.Sheets(0).Cells(2, 3).Value = 14FpSpread1.Sheets(0).Cells(3, 3).Value = 15FpSpread1.Sheets(0).Cells(4, 3).Value = 16FpSpread1.Sheets(0).Cells(5, 3).Value = 17FpSpread1.Sheets(0).Cells(6, 3).Value = 18Dim range As New FarPoint.Win.Spread.Model.CellRange(0, 0, 7, 4)FpSpread1.Sheets(0).AddChart(range, GetType(FarPoint.Win.Chart.BarSeries), 400, 300, 0, 0, FarPoint.Win.Chart.ChartViewType.View3D, False)
UsingCode
YoucanaddachartcontroltotheSpreadcontrolusingcode.Thisexamplecreatesachartcontrol,addsdatatothechartcontrol,andthenaddsthechartcontroltoSpread.
Example
Spread Windows Forms Developer’s Guide 662
Copyright © GrapeCity, Inc. All rights reserved.
ThisexamplehascodefortheAddmethodusedtoaddachartcontroltoSpreadandtheModelpropertyusedforthechartcontroloutsideoftheSpreadcontrol.
C#FarPoint.Win.Chart.BarSeries series = new FarPoint.Win.Chart.BarSeries();series.Values.Add(2.0);series.Values.Add(4.0);series.Values.Add(3.0);series.Values.Add(5.0);FarPoint.Win.Chart.YPlotArea plotArea = new FarPoint.Win.Chart.YPlotArea();plotArea.Location = new PointF(0.2f, 0.2f);plotArea.Size = new SizeF(0.6f, 0.6f);plotArea.Series.Add(series);FarPoint.Win.Chart.LabelArea label = new FarPoint.Win.Chart.LabelArea();label.Text = "Bar Chart";label.Location = new PointF(0.5f, 0.02f);label.AlignmentX = 0.5f;label.AlignmentY = 0.0f;FarPoint.Win.Chart.LegendArea legend = new FarPoint.Win.Chart.LegendArea();legend.Location = new PointF(0.98f, 0.5f);legend.AlignmentX = 1.0f;legend.AlignmentY = 0.5f;FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();model.LabelAreas.Add(label);model.LegendAreas.Add(legend);model.PlotAreas.Add(plotArea);//How to add the Chart to Spread, requires the chart assembly//FarPoint.Win.Spread.Chart.SpreadChart chart = new FarPoint.Win.Spread.Chart.SpreadChart();//chart.Size = new Size(200, 200);//chart.Location = new Point(100, 100);//chart.Model = model;//fpSpread1.Sheets[0].Charts.Add(chart);//Or//How to use the chart outside of Spread, requires a chart control//fpChart1.Model = model;
VBDim series As New FarPoint.Win.Chart.BarSeries()series.Values.Add(2.0)series.Values.Add(4.0)series.Values.Add(3.0)series.Values.Add(5.0)Dim plotArea As New FarPoint.Win.Chart.YPlotArea()plotArea.Location = New PointF(0.2F, 0.2F)plotArea.Size = New SizeF(0.6F, 0.6F)plotArea.Series.Add(series)Dim label As New FarPoint.Win.Chart.LabelArea()label.Text = "Bar Chart"label.Location = New PointF(0.5F, 0.02F)label.AlignmentX = 0.5Flabel.AlignmentY = 0.0FDim legend As New FarPoint.Win.Chart.LegendArea()legend.Location = New PointF(0.98F, 0.5F)legend.AlignmentX = 1.0F
Spread Windows Forms Developer’s Guide 663
Copyright © GrapeCity, Inc. All rights reserved.
legend.AlignmentY = 0.5FDim model As New FarPoint.Win.Chart.ChartModel()model.LabelAreas.Add(label)model.LegendAreas.Add(legend)model.PlotAreas.Add(plotArea)'How to add the Chart to Spread, requires the chart assembly'Dim chart As New FarPoint.Win.Spread.Chart.SpreadChart()'chart.Size = New Size(200, 200)'chart.Location = New Point(100, 100)'chart.Model = model'FpSpread1.Sheets(0).Charts.Add(chart)'Or'How to use the chart outside of Spread, requires a chart control'fpChart1.Model = model;
Changing Chart Options
ManyoftheoptionsintheChartToolstabintheSpreadDesignerarealsoavailablewhenyouright-clickonachartcontrolthathasbeenaddedtotheSpreadcontrol.Youcanaccesstheseoptionsatdesigntimeorruntime.
Thefollowingoptionsareavailable:
TheCut,Copy,andPasteoptionsallowyoutocut,copy,andpastethechartcontrol.Deleteallowsyoutodeletethechartcontrol.TheChangeChartTypeoptionallowsyoutochangethecharttype(bartopie,forexample).TheSelectDatadialogallowsyoutochangetherangeofdatainthechartaswellasedittheseriesorcategorynames.TheSwitchRow/Columnoptionswapsthecategoryandseriesnamesandswapstherowsandcolumnsofdata.TheMoveChartoptionbringsupaMoveChartdialogthatallowsyoutomovethecharttoanothersheet
Spread Windows Forms Developer’s Guide 664
Copyright © GrapeCity, Inc. All rights reserved.
vieworanewsheet.TheFormatChartAreaoptionallowsyoutosetbackcolor,seriesshapes,etc.Theareathatyoucanformatdependsonwhatwasselectedbeforeyouright-clickedonthechart.TheChartDesigneroptionbringsupthechartdesigner.TheViewoptionallowsyoutosetthecharttoa3Dor2Dview.
TheChangeChartTypeoptionappearsasfollows:
TheSelectDatadialogappearsasfollows:
TheMoveChartdialogappearsasfollows:
Spread Windows Forms Developer’s Guide 665
Copyright © GrapeCity, Inc. All rights reserved.
TheFormatChartAreadialogappearsasfollows:
Using the Chart Designer
Youcanaddachartwiththechartdesigner.
UsingtheChartDesigner
Spread Windows Forms Developer’s Guide 666
Copyright © GrapeCity, Inc. All rights reserved.
1. UsetheEditChartsverbtoaddachartcontrol(orusetheInsertmenuintheSpreadDesigner).ThiscreatesaSpreadChartobjectontheform.
2. ClickthesmarttagorverboftheSpreadChartobject.3. SelecttheChartDesigner.
4. TheChartDesignerallowsyoutocreateachartandsetadditionaloptions.UsethePlotAreasCollectiontocreateplots,series,andadddata.UsetheLegendAreasCollectiontocreatealegendforthechart.UsetheLabelAreasCollectiontocreatelabelsforthechart.
5. ClickApplytosavethechanges.
Binding the Chart Control
Spread Windows Forms Developer’s Guide 667
Copyright © GrapeCity, Inc. All rights reserved.
Aseriescontainsthreeparts(category,seriesname,anddata).Youcanbindeachparttoaninstanceoftheseriesdatafield.Theentirechartcontrolcannotbebound;however,youcanuseacellrangeoraformulatoputdatainthechart.
UsingCode
YoucanaddvaluestoSpreadwithanarrayordatasetandthenuseacellrangetoputthosevaluesinachartcontrol.Thisexampleusesanarraytoputdatainthecontrol.
Example
C#private void Form1_Load(object sender, System.EventArgs e){object[,] values = { { "lg1", "lg2", "lg3" }, { "tt1", 2.0, 5.0 }, {"tt2",4.0,5.0 } };fpSpread1.Sheets[0].SetArray(0, 0, values);FarPoint.Win.Spread.Model.CellRange cellRange = new FarPoint.Win.Spread.Model.CellRange(0,0,values.GetLength(0),values.GetLength(1));fpSpread1.Sheets[0].AddChart(cellRange, typeof(FarPoint.Win.Chart.BarSeries), 400, 400, 0, 0);}private void button1_Click(object sender, EventArgs e){FarPoint.Win.Chart.BarSeries series = (FarPoint.Win.Chart.BarSeries)fpSpread1.Sheets[0].Charts[0].Model.PlotAreas[0].Series[0];FarPoint.Win.Spread.Chart.SeriesDataField data = (FarPoint.Win.Spread.Chart.SeriesDataField)series.Values.DataSource;data.Formula = "Sheet1!$B$2:$E$1";}
VBPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadDim values As Object(,) = {{"lg1", "lg2", "lg3"}, {"tt1", 2.0R, 5.0R}, {"tt2", 4.0R, 5.0R}}FpSpread1.Sheets(0).SetArray(0, 0, values)Dim cellRange As New FarPoint.Win.Spread.Model.CellRange(0, 0, values.GetLength(0), values.GetLength(1))FpSpread1.Sheets(0).AddChart(cellRange, GetType(FarPoint.Win.Chart.BarSeries), 400, 400, 0, 0)End SubPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.ClickDim series As FarPoint.Win.Chart.BarSeries = DirectCast(FpSpread1.Sheets(0).Charts(0).Model.PlotAreas(0).Series(0), FarPoint.Win.Chart.BarSeries)Dim data As FarPoint.Win.Spread.Chart.SeriesDataField = DirectCast(series.Values.DataSource, FarPoint.Win.Spread.Chart.SeriesDataField)data.Formula = "Sheet1!$B$2:$E$1"End Sub
UsingCode
YoucanaddvaluestoSpreadwithanarrayordatasetandthenuseacellrangetoputthosevaluesinachartcontrol.Thisexampleusesadatatabletoputdatainthecontrol.
Spread Windows Forms Developer’s Guide 668
Copyright © GrapeCity, Inc. All rights reserved.
Example
C#DataTable dt = new DataTable("Test");DataRow dr = default(DataRow);dt.Columns.Add("Series1");dt.Columns.Add("Series2");dr = dt.NewRow();dr[0] = 1;dr[1] = 4;dt.Rows.Add(dr);dr = dt.NewRow();dr[0] = 2;dr[1] = 5;dr = dt.NewRow();dt.Rows.Add(dr);dr[0] = 3;dr[1] = 6;dt.Rows.Add(dr);fpSpread1.DataSource = dt;FarPoint.Win.Spread.Model.CellRange cellRange = new FarPoint.Win.Spread.Model.CellRange(0,0,2,2);fpSpread1.Sheets[0].AddChart(cellRange, typeof(FarPoint.Win.Chart.BarSeries), 400,400,0,0);
VBDim dt As New DataTable("Test")Dim dr As DataRowdt.Columns.Add("Series1")dt.Columns.Add("Series2")dr = dt.NewRow()dr(0) = 1dr(1) = 4dt.Rows.Add(dr)dr = dt.NewRow()dr(0) = 2dr(1) = 5dt.Rows.Add(dr)dr = dt.NewRow()dr(0) = 3dr(1) = 6dt.Rows.Add(dr)FpSpread1.DataSource = dtDim cellRange As New FarPoint.Win.Spread.Model.CellRange(0, 0, 2, 2)FpSpread1.Sheets(0).AddChart(cellRange, GetType(FarPoint.Win.Chart.BarSeries), 400, 400, 0, 0)
Allowing the User to Change the Chart
Youcanallowtheuserstoresize,move,orchangetherangeofelementsdisplayedbythechart.TheusercanalsoselectelementsonthechartandtherelatedcellrangeintheSpreadcontrolwillbeselected.
Theusercanmakethefollowingchangesatruntime.
Spread Windows Forms Developer’s Guide 669
Copyright © GrapeCity, Inc. All rights reserved.
Theusercanselectthechartandthenmoveorresizethechart.Theusercanselectthechartandthentherangeofdatausedbythechart.Thentheycanresizetheblockofselecteddatatochangetherangeofdatainthechart.Theusercaneditthecellsusedbythecharttochangethevalues.
Thefollowingimageshowsaselectedrangeofdatausedbythechart.Putthemousepointeroverthebluesquaretogetresizearrows.
Youcanpreventtheuserfrommovingorresizingthechart.TheLockedpropertypreventstheuserfrommovingandresizingthechartcontrol.
UsingCode
ThisexamplesetstheLocked,CanMove,andCanResizeproperties.
Example
C#FarPoint.Win.Spread.Chart.SpreadChart chart;chart = fpSpread1.Sheets[0].AddChart(0, 0, typeof(FarPoint.Win.Chart.BarSeries), 400, 400, 200, 80, FarPoint.Win.Chart.ChartViewType.View2D, true);chart.Locked = true;//chart.CanSize = FarPoint.Win.Spread.DrawingSpace.Sizing.None;//chart.CanMove = FarPoint.Win.Spread.DrawingSpace.Moving.Horizontal;
VBDim chart As FarPoint.Win.Spread.Chart.SpreadChartDim range As New FarPoint.Win.Spread.Model.CellRange(0, 0, 7, 4)chart = FpSpread1.Sheets(0).AddChart(range, GetType(FarPoint.Win.Chart.BarSeries), 400, 300, 300, 80, FarPoint.Win.Chart.ChartViewType.View3D, False)chart.Locked = True'chart.CanSize = FarPoint.Win.Spread.DrawingSpace.Sizing.None'chart.CanMove = FarPoint.Win.Spread.DrawingSpace.Moving.Horizontal
Spread Windows Forms Developer’s Guide 670
Copyright © GrapeCity, Inc. All rights reserved.
Adding a Context Menu
Youcanaddacontextmenutotheformforthechartcontrolsothatwhenyouright-clickonthechart,youseethecontextmenu.Youcanaddthecontextmenuatdesigntimeorwithcode.Formoreinformationonusingcode,seetheContextMenuStrip('ContextMenuStripProperty'intheon-linedocumentation)property.
UsingtheDesigner
1. Addacontextmenucontroltotheform.2. AddachartcontroltotheformusingtheSpreadDesigner.3. ClickontheSpreadChartsmarttagorverb.
4. Selectthecontextmenuyouwishtoassociatewiththechartcontrol.
Spread Windows Forms Developer’s Guide 671
Copyright © GrapeCity, Inc. All rights reserved.
Using Touch Support with the Component
Spreadsupportstouchgesturesinmanyareasofthecontrol.Youcanusetouchgestureswithfiltering,grouping,sorting,andwithmanyothertypesofinteractionsinSpread.Atouchscreenisrequired(eitheratouchmonitororasmartbook-typelaptopwithatouchscreen).
Thefollowingtopicsprovideinformationabouttouchsupportandtheareaswheretouchsupportisavailable:
UnderstandingTouchSupportUsingTouchSupport
Understanding Touch Support
Touchsupportrequiresthatthecontrolsupportbasictouchgestures.Touchmessagesareprocessedbythecontrolwhentouchgesturesareused.
Thefollowingtopicsprovideadditionalinformation:
UnderstandingTouchGesturesUnderstandingTouchMessages
Understanding Touch Gestures
Thereareseveraltypesoftouchgesturessuchasbasicorcommonandpinchorstretch.
Basictouchgesturesincludethefollowing:
Gesture Description
Tap Onefingertouchesthescreenandliftsup.
Pressandhold Onefingertouchesthescreenandstaysinplace.
Slide Oneormorefingerstouchthescreenandmoveinthesamedirection.
Swipe Oneormorefingerstouchthescreenandmoveashortdistanceinthesamedirection.
Pinch Twoormorefingerstouchthescreenandmovefartherapartorclosertogether.
Rotate Twoormorefingerstouchthescreenandmoveinaclockwiseorcounter-clockwisearc.
Switch Twoormorefingerstouchthescreenandmovefartherapart.
FpSpreadusesstandardpinchandstretchgestureswhenzooming.Formoreinformation,seehttp://msdn.microsoft.com/en-us/library/windows/apps/hh465415.aspx.
Understanding Touch Messages
Touchmessagesareprocessedincellareas(Tap,Panning,Pinch,andsoon);however,inheaderandfooterareas(columnheader,rowheader,corner,andcolumnfooter)andthescrollbararea,touchmessagesaretreatedasmousemessages.
Forexample,apanningoperationonthecolumnheaderbecomesacolumnselectionaction(similartousingthemouse).Spreaddoesnotscroll.
FpSpreadprovidesanInputDeviceType('InputDeviceTypeProperty'intheon-linedocumentation)propertythatreturnsthemessage'sdevicetype.
Spread Windows Forms Developer’s Guide 672
Copyright © GrapeCity, Inc. All rights reserved.
Using Touch Support
YoucanusetouchsupportinmanyareasandinmanytypesofinteractionswiththeSpreadcontrol.
Thefollowingtopicsexplainwheretouchsupportisavailable:UsingaTouchKeyboardUsingtheTouchMenuBarUsingTouchSupportwithAutoFitUsingTouchSupportwithCellNotesUsingTouchSupportwithChartsUsingTouchSupportwithClipboardOperationsUsingTouchSupportwithDragandFillUsingTouchSupportwithDrop-DownElementsUsingTouchSupportwithEditableCellsUsingTouchSupportwithInputManCellsUsingTouchSupportwithFilteringUsingTouchSupportwithGroupingUsingTouchSupportwithRangeGroupingUsingTouchSupportwhenMovingColumnsorRowsUsingTouchSupportwhenResizingColumnsorRowsUsingTouchSupportwithScrollingUsingTouchSupportwithSelectionsUsingTouchSupportwithShapesUsingTouchSupportwhenSortingUsingTouchSupportwiththeTabStripUsingTouchSupportwithViewportsUsingTouchSupportwithZooming
Using a Touch Keyboard
Youcandisplayatouchkeyboardwheneditingacell.
UsetheShowTouchKeyboard('ShowTouchKeyboardMethod'intheon-linedocumentation)methodtodisplaythekeyboardasinthefollowingimage.
YoucanalsospecifywhetherthecellbeingeditedscrollsintoviewwhenthetouchkeyboardisdisplayedbysettingtheAutoScrollWhenKeyboardShowing('AutoScrollWhenKeyboardShowingProperty'intheon-linedocumentation)property.FpSpreadwillscrollupassoonaspossible,butifthereisnotenoughspacetoscroll,theactivecellmaynotbevisible.Forexample,ifthecontroliscompletelycoveredbythetouchkeyboard,thecontrolscrolls
Spread Windows Forms Developer’s Guide 673
Copyright © GrapeCity, Inc. All rights reserved.
theactivecelltothefirstrow(cellstillhiddenbykeyboard).
FpSpreadprovidesanInputScope('InputScopeProperty'intheon-linedocumentation)propertythatcanbeusedtospecifythetouchkeyboard'slayout.ThispropertyissupportedinMicrosoftWindows8andWindowsServer2012.
YoucanusetheShowTouchKeyboard('ShowTouchKeyboardMethod'intheon-linedocumentation)andHideTouchKeyboard('HideTouchKeyboardMethod'intheon-linedocumentation)methodsintheEditModeOn('EditModeOnEvent'intheon-linedocumentation)eventtoshowthetouchkeyboardwhenthecellgoesintoeditmode.
UsingCode
Thefollowingexampledisplaysthetouchkeyboardwhenthecellisineditmodeandhidesitwhenthecellisnolongerineditmode.
CSprivate void Form1_Load(object sender, EventArgs e) { fpSpread1.AutoScrollWhenKeyboardShowing = true; fpSpread1.InputScope = FarPoint.Win.InputScopeNameValue.Default; }
private void fpSpread1_EditModeOn(object sender, EventArgs e) { fpSpread1.ShowTouchKeyboard(); }
private void fpSpread1_EditModeOff(object sender, EventArgs e) { fpSpread1.HideTouchKeyboard(); }
VBPrivate Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load FpSpread1.AutoScrollWhenKeyboardShowing = True FpSpread1.InputScope = FarPoint.Win.InputScopeNameValue.DefaultEnd Sub
Private Sub FpSpread1_EditModeOn(sender As Object, e As System.EventArgs) Handles FpSpread1.EditModeOn FpSpread1.ShowTouchKeyboard()End Sub
Private Sub FpSpread1_EditModeOff(sender As Object, e As System.EventArgs) Handles FpSpread1.EditModeOff FpSpread1.HideTouchKeyboard()End Sub
Using the Touch Menu Bar
Youcanusethedefaulttouchmenubarortouchstriptocut,copy,andpastecells.Youcanalsocustomizethetouchstriptoprovideadditionaloptions.
Tapaselectedrangetodisplaythetouchmenubarstrip.
Spread Windows Forms Developer’s Guide 674
Copyright © GrapeCity, Inc. All rights reserved.
YoucanusetheTouchStripOpening('TouchStripOpeningEvent'intheon-linedocumentation)eventtodisplayacustomizedtouchstrip.Youcanalsoaddmenuitemstothetouchstrip.
UsingCode
Youcanaddadrop-downmenuitemwithfollowingcode.Thisexamplealsohidesthe"Cut"optioninthetouchstrip.
1. CancelthedefaulttouchstripintheTouchStripOpening('TouchStripOpeningEvent'intheon-linedocumentation)event.
2. Createacustomizedtouchstripitem.3. Createandaddamenuitem4. Addthenewitemstothetouchstrip.
CSvoid autoFill_Click(object sender, EventArgs e) { FarPoint.Win.Spread.SpreadView activeView = fpSpread1.GetRootWorkbook().GetActiveWorkbook(); if (activeView != null) { activeView.ShowAutoFillIndicator(); } }
private void fpSpread1_TouchStripOpening(object sender, FarPoint.Win.Spread.TouchStripOpeningEventArgs e) { e.Cancel = true; FarPoint.Win.Spread.CellTouchStrip touchStrip = new FarPoint.Win.Spread.CellTouchStrip(this.fpSpread1); touchStrip.Items["Cut"].Visible = false; ToolStripSeparator separator1 = new ToolStripSeparator(); FarPoint.Win.Spread.TouchStripButton autoFill = new FarPoint.Win.Spread.TouchStripButton("AutoFill", System.Drawing.Image.FromFile("C:\\SpreadWin7\\dragfill.png")); autoFill.Click += autoFill_Click;
ToolStripSeparator separator2 = new ToolStripSeparator(); ToolStripDropDownButton dropDownMenu = new ToolStripDropDownButton(System.Drawing.Image.FromFile("C:\\SpreadWin7\\dropdown.png")); dropDownMenu.ShowDropDownArrow = false; dropDownMenu.ImageScaling = ToolStripItemImageScaling.None; ContextMenuStrip menu = new System.Windows.Forms.ContextMenuStrip(); menu.Items.Add("Item1"); dropDownMenu.DropDown = menu;
touchStrip.Items.AddRange(new ToolStripItem[] { separator1, autoFill, separator2, dropDownMenu }); touchStrip.Show(new Point(e.X - 20, e.Y - 35 - touchStrip.Height));
Spread Windows Forms Developer’s Guide 675
Copyright © GrapeCity, Inc. All rights reserved.
}
VBPrivate Sub autoFill_Click(sender As Object, e As EventArgs)Dim activeView As FarPoint.Win.Spread.SpreadView = fpSpread1.GetRootWorkbook().GetActiveWorkbook()If activeView IsNot Nothing ThenactiveView.ShowAutoFillIndicator()End IfEnd Sub
Private Sub fpSpread1_TouchStripOpening(sender As Object, e As FarPoint.Win.Spread.TouchStripOpeningEventArgs)e.Cancel = TrueDim touchStrip As New FarPoint.Win.Spread.CellTouchStrip(Me.fpSpread1)touchStrip.Items("Cut").Visible = FalseDim separator1 As New ToolStripSeparator()Dim autoFill As New FarPoint.Win.Spread.TouchStripButton("AutoFill", System.Drawing.Image.FromFile("C:\SpreadWin7\dragfill.png")) AddHandler autoFill.Click, AddressOf autoFill_Click
Dim separator2 As New ToolStripSeparator()Dim dropDownMenu As New ToolStripDropDownButton(System.Drawing.Image.FromFile("C:\SpreadWin7\dropdown.png"))dropDownMenu.ShowDropDownArrow = FalsedropDownMenu.ImageScaling = ToolStripItemImageScaling.NoneDim menu As ContextMenuStrip = New System.Windows.Forms.ContextMenuStrip()menu.Items.Add("Item1")dropDownMenu.DropDown = menu
touchStrip.Items.AddRange(New ToolStripItem() {separator1, autoFill, separator2, dropDownMenu})touchStrip.Show(New Point(e.X - 20, e.Y - 35 - touchStrip.Height))End Sub
Using Touch Support with AutoFit
Youcanusetouchsupportgestureswithautomaticfit.
Taptoselectacolumn(resizehandlerbecomesvisible).Double-taptoresizethecolumnautomatically.Taptoselectarowanddouble-taptoresizetherowautomatically.TheResizable('ResizableProperty'intheon-linedocumentation)propertymustbetrueforthecolumnandrow.
Using Touch Support with Cell Notes
Youcanusetouchgestureswitheditablecellnotes.
Tapacellnotetoselectit.Double-tapthecellnotetoeditit.Presstheedgeofthecellnoteandslidethenotetomoveit.
SettheCanMove('CanMoveProperty'intheon-linedocumentation)andCanSize('CanSizeProperty'intheon-linedocumentation)propertiestotrueinordertomoveorresizethecellnote.TheNoteStyle('NoteStyleProperty'intheon-linedocumentation)propertymustbesettoStickyNotefortouchsupport.
Using Touch Support with Charts
Spread Windows Forms Developer’s Guide 676
Copyright © GrapeCity, Inc. All rights reserved.
YoucanusetouchgestureswiththeChartcontrol.
TheChartcontrolusesthefollowingtouchgestures:
TouchGesture MouseAction Action
Tap Click Selectsacellnote,shape,orchart.
Double-tap Double-Click Editsacellnote,shape,orchartifeditingissupported.
Pressedgethenslide Pressleftbuttononedgethenmove Resizesacellnote,shape,orchartifCanSizeissettotrue.
Presschartthenslide Pressleftbuttononchartthenmove Movesacellnote,shape,orchartifCanMoveissettotrue.
Pressrotatedhandleandslide
Pressleftbuttononrotatedhandleandmove
RotatesashapeorchartifCanRotateissettotrue.
Using Touch Support with Clipboard Operations
Youcanusetouchgesturesandthetouchmenubartocut,copy,andpaste.
Selectarangeofcells.Taptheselectedrangetodisplaythetouchmenubaroptions.TaptheCut,Copy,orPastemenuitems.
TheClipboardOptions('ClipboardOptionsProperty'intheon-linedocumentation)propertyspecifieswhatareasarepartofthecut,copy,orpaste.
Using Touch Support with Drag and Fill
Spread Windows Forms Developer’s Guide 677
Copyright © GrapeCity, Inc. All rights reserved.
Youcanusetouchsupportgesturesandthetouchmenubarortoolbarwithdragandfill.
Selectarange.Taptherangetodisplaythetouchmenubar.TaptheAutoFillmenuitemtodisplaythedragfillhandleatthebottom-rightedgeoftheselectedrange.Pressandslidethehandletodragandfilltherange.TheAllowDragFill('AllowDragFillProperty'intheon-linedocumentation)propertymustbetruetodisplayandusethedragfillhandle.
ThefollowingimageshowstheDragFillDropDownContextMenu:
UsingCode
Thisexampleaddsthedragfillicontothetouchmenubar.
1. SettheAllowDragFill('AllowDragFillProperty'intheon-linedocumentation)propertytotrue.2. CreateanewtouchstripbuttonandseparatorintheTouchStripOpening('TouchStripOpeningEvent'intheon-linedocumentation)event.
3. Createanimageforthenewbutton.4. Addthenewitemstothetouchstrip.5. Createanduseaneventtodisplaytheautofillindicator.
CSvoid autoFill_Click(object sender, EventArgs e) { FarPoint.Win.Spread.SpreadView activeView = fpSpread1.GetRootWorkbook().GetActiveWorkbook(); if (activeView != null) { activeView.ShowAutoFillIndicator(); } }
private void Form1_Load(object sender, EventArgs e) { fpSpread1.AllowDragFill = true;
Spread Windows Forms Developer’s Guide 678
Copyright © GrapeCity, Inc. All rights reserved.
} private void fpSpread1_TouchStripOpening(object sender, FarPoint.Win.Spread.TouchStripOpeningEventArgs e) { e.Cancel = true; FarPoint.Win.Spread.CellTouchStrip touchStrip = new FarPoint.Win.Spread.CellTouchStrip(fpSpread1); ToolStripSeparator separator = new ToolStripSeparator(); FarPoint.Win.Spread.TouchStripButton autoFill = new FarPoint.Win.Spread.TouchStripButton("AutoFill", System.Drawing.Image.FromFile("C:\\SpreadWin7\\dragfill.png") ); autoFill.Click += autoFill_Click; touchStrip.Items.AddRange(new ToolStripItem[] { separator, autoFill }); touchStrip.Show(new Point(e.X - 20, e.Y - 35 - touchStrip.Height)); }
VBPrivate Sub autoFill_Click(sender As Object, e As EventArgs) Dim activeView As FarPoint.Win.Spread.SpreadView = fpSpread1.GetRootWorkbook().GetActiveWorkbook() If activeView IsNot Nothing Then activeView.ShowAutoFillIndicator() End IfEnd Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load FpSpread1.AllowDragFill = TrueEnd SubPrivate Sub fpSpread1_TouchStripOpening(sender As Object, e As FarPoint.Win.Spread.TouchStripOpeningEventArgs) e.Cancel = True Dim touchStrip As New FarPoint.Win.Spread.CellTouchStrip(fpSpread1) Dim separator As New ToolStripSeparator() Dim autoFill As New FarPoint.Win.Spread.TouchStripButton("AutoFill", System.Drawing.Image.FromFile("C:\SpreadWin7\dragfill.png")) AddHandler autoFill.Click, AddressOf autoFill_Click touchStrip.Items.AddRange(New ToolStripItem() {separator, autoFill}) touchStrip.Show(New Point(e.X - 20, e.Y - 35 - touchStrip.Height))End Sub
Using Touch Support with Drop-Down Elements
Youcanusetouchgesturesindrop-downcells,calendars,andotherelementsinthecontrol.
Thefollowingitemsaredrop-downelementsorwindows:
FilterDropDown(Gadget)FilterDropDown(FilterBar'sDropDown)DropDownList(ComboCellType)DropDownCalendar(DateTimeCellType)DropDownCalendar(GcDateTimeCellType)DropDownEdit(GcTextCellType)
SettheTouchDropDownScale('TouchDropDownScaleProperty'intheon-linedocumentation)propertytochangethescaleoftheelementsinthedrop-downwindow.Thedefaultvalueis1.5.Thefollowingdrop-downfilter
Spread Windows Forms Developer’s Guide 679
Copyright © GrapeCity, Inc. All rights reserved.
hasascaleof2.
Note:IftheTouchDropDownScale('TouchDropDownScaleProperty'intheon-linedocumentation)propertyissetto0,alldrop-downwindowsarezoomedinmouseortouchmode.IftheTouchDropDownScale('TouchDropDownScaleProperty'intheon-linedocumentation)propertyissettoavalidvalue(1fto4f),thenpaddingisincreasedfortouchsupportbasedonthepropertyvalue.
UsingCode
SettheTouchDropDownScale('TouchDropDownScaleProperty'intheon-linedocumentation)propertytochangethescaleofthedrop-downwindow.
CSFpSpread1.TouchDropDownScale = 1.0F;FpSpread1.TouchSelectionGripperBackColor = Color.Aqua;FpSpread1.TouchSelectionGripperLineColor = Color.BurlyWood;FpSpread1.TouchSelectionGripperThickness = 2;
VBFpSpread1.TouchDropDownScale = 1.0FFpSpread1.TouchSelectionGripperBackColor = Color.AquaFpSpread1.TouchSelectionGripperLineColor = Color.BurlyWoodFpSpread1.TouchSelectionGripperThickness = 2
Using Touch Support with Editable Cells
Youcanusetouchgesturestoeditcellsthatallowediting.
Double-tapacelltogointoeditmode.TapacelltogointoeditmodeiftheEditModePermanent('EditModePermanentProperty'intheon-linedocumentation)propertyistrue.Typingacharacterinthecellalsostartseditmode.
Button,checkbox,multipleoption,hyperlink,slider,andfilterbarcellsusethefollowingtouchgestures:
TouchGesture MouseAction
Tap Click
Double-tap Double-click
Pressandslide Pressleftmousebuttonandmove
GcTextBox,GcDateTime,number,regularexpression,percent,currency,datetime,general,andtextcellshavesimilar
Spread Windows Forms Developer’s Guide 680
Copyright © GrapeCity, Inc. All rights reserved.
touchbehaviors.
Listboxandrichtextcellssupporttouchgesturessimilartostandardcontrols.
IftheEditablepropertyistrueforthecomboboxandmultiple-columncomboboxcells,thegripperisdisplayed.Thefollowingimagedisplaysagripperinthecell.
UsingCode
YoucansettheShowGrippersInEditingStatus('ShowGrippersInEditingStatusProperty'intheon-linedocumentation)propertytotruetodisplayagripperwhilethecellisineditmode.
CSprivate void Form1_Load(object sender, EventArgs e) { fpSpread1.ShowGrippersInEditingStatus = true; }
private void button1_Click(object sender, EventArgs e) { fpSpread1.ShowGrippersInEditingStatus = false; }
private void fpSpread1_ShowGrippersInEditingStatusChanged(object sender, EventArgs e) { listBox1.Items.Add("Status Changed"); }
VBPrivate Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load FpSpread1.ShowGrippersInEditingStatus = TrueEnd Sub
Private Sub FpSpread1_ShowGrippersInEditingStatusChanged(sender As Object, e As EventArgs) Handles FpSpread1.ShowGrippersInEditingStatusChanged ListBox1.Items.Add("Status Changed")End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click FpSpread1.ShowGrippersInEditingStatus = FalseEnd Sub
Using Touch Support with InputMan Cells
YoucanusetouchsupportwithGcDateTimeandGcTextBoxcells.
Youcantapsidebuttonsinthecellstochangethecellvalues.
Spread Windows Forms Developer’s Guide 681
Copyright © GrapeCity, Inc. All rights reserved.
UsingCode
ThefollowingexamplecreatessidebuttonsforGcDateTimecellsandaGcTextBoxcell.TheDropDownOpeningeventhasaByTouchpropertythatreturnswhetherthedrop-downbuttonwasopenedwithatouchgesture.
CSGrapeCity.Win.Spread.InputMan.CellType.SideButtonInfo testbutton = new GrapeCity.Win.Spread.InputMan.CellType.SideButtonInfo();testbutton.Behavior = GrapeCity.Win.Spread.InputMan.CellType.SideButtonBehavior.SpinDown;testbutton.Delay = 300;testbutton.Interval = 5;testbutton.Text = "1";
GrapeCity.Win.Spread.InputMan.CellType.GcDateTimeCellType dateCellType = new GrapeCity.Win.Spread.InputMan.CellType.GcDateTimeCellType();dateCellType.SideButtons.Add(new GrapeCity.Win.Spread.InputMan.CellType.SideButtonInfo() { Text = "A" });this.fpSpread1_Sheet1.Columns[0].CellType = dateCellType;
GrapeCity.Win.Spread.InputMan.CellType.GcTextBoxCellType textCellType = new GrapeCity.Win.Spread.InputMan.CellType.GcTextBoxCellType();textCellType.SideButtons.Add(new GrapeCity.Win.Spread.InputMan.CellType.SideButtonInfo() { Text = "B" });this.fpSpread1_Sheet1.Columns[1].CellType = textCellType;
GrapeCity.Win.Spread.InputMan.CellType.GcDateTimeCellType dateCellType2 = new GrapeCity.Win.Spread.InputMan.CellType.GcDateTimeCellType();dateCellType2.SideButtons.Add(testbutton);this.fpSpread1_Sheet1.Columns[2].CellType = dateCellType2;
void IMCellType_DropDownOpening(object sender, GrapeCity.Win.Spread.InputMan.CellType.DropDownOpeningEventArgs e) { listBox1.Items.Add(e.ByTouch.ToString()); }
private void fpSpread1_EditModeOn(object sender, EventArgs e) { if (fpSpread1.EditingControl is
Spread Windows Forms Developer’s Guide 682
Copyright © GrapeCity, Inc. All rights reserved.
GrapeCity.Win.Spread.InputMan.CellType.GcDateTime) ((GrapeCity.Win.Spread.InputMan.CellType.GcDateTime)fpSpread1.EditingControl).DropDownOpening += new EventHandler(IMCellType_DropDownOpening); }
private void fpSpread1_EditModeOff(object sender, EventArgs e) { if (fpSpread1.EditingControl is GrapeCity.Win.Spread.InputMan.CellType.GcDateTime) ((GrapeCity.Win.Spread.InputMan.CellType.GcDateTime)fpSpread1.EditingControl).DropDownOpening -= new EventHandler(IMCellType_DropDownOpening); }
VBDim testbutton As New GrapeCity.Win.Spread.InputMan.CellType.SideButtonInfo()testbutton.Behavior = GrapeCity.Win.Spread.InputMan.CellType.SideButtonBehavior.SpinDowntestbutton.Delay = 300testbutton.Interval = 5testbutton.Text = "1"
Dim dateCellType As New GrapeCity.Win.Spread.InputMan.CellType.GcDateTimeCellType()dateCellType.SideButtons.Add(New GrapeCity.Win.Spread.InputMan.CellType.SideButtonInfo() With {.Text = "A"})FpSpread1_Sheet1.Columns(0).CellType = dateCellType
Dim textCellType = New GrapeCity.Win.Spread.InputMan.CellType.GcTextBoxCellType()textCellType.SideButtons.Add(New GrapeCity.Win.Spread.InputMan.CellType.SideButtonInfo() With {.Text = "B"})FpSpread1_Sheet1.Columns(1).CellType = textCellType
Dim dateCellType2 As New GrapeCity.Win.Spread.InputMan.CellType.GcDateTimeCellType()dateCellType2.SideButtons.Add(testbutton)FpSpread1_Sheet1.Columns(2).CellType = dateCellType2
Private Sub IMCellType_DropDownOpening(ByVal sender As Object, ByVal e As GrapeCity.Win.Spread.InputMan.CellType.DropDownOpeningEventArgs) ListBox1.Items.Add(e.ByTouch.ToString()) End Sub
Private Sub FpSpread1_EditModeOff(sender As Object, e As EventArgs) Handles FpSpread1.EditModeOff If TypeOf (FpSpread1.EditingControl) Is GrapeCity.Win.Spread.InputMan.CellType.GcDateTime Then RemoveHandler CType(FpSpread1.EditingControl, GrapeCity.Win.Spread.InputMan.CellType.GcDateTime).DropDownOpening, AddressOf IMCellType_DropDownOpening End If End Sub
Private Sub FpSpread1_EditModeOn(sender As Object, e As EventArgs) Handles FpSpread1.EditModeOn If TypeOf (FpSpread1.EditingControl) Is GrapeCity.Win.Spread.InputMan.CellType.GcDateTime Then AddHandler CType(FpSpread1.EditingControl, GrapeCity.Win.Spread.InputMan.CellType.GcDateTime).DropDownOpening, AddressOf IMCellType_DropDownOpening End If
Spread Windows Forms Developer’s Guide 683
Copyright © GrapeCity, Inc. All rights reserved.
End Sub
Using Touch Support with Filtering
Youcanusetouchgestureswhenfiltering.
UsetheZoomFactor('ZoomFactorProperty'intheon-linedocumentation)propertytoincreasethesizeofthedrop-downlist.TheAllowAutoFilter('AllowAutoFilterProperty'intheon-linedocumentation)propertymustbetruetoallowfilteringwithtouchgestures.
Note:Iftheuserselectsacolumnthatcontainssortingandfilteringindicators,theresizegripperisdisplayed.Thegripperhasahigherprioritythanthefilterlistorsortoperation.SettheHeaderIndicatorPositionAdjusting('HeaderIndicatorPositionAdjustingProperty'intheon-linedocumentation)propertytospecifythedistancebetweenthesortingandfilteringindicatorsandtherightedgeofthecolumnsothattheusercansortorfilterthecolumnwhilethegripperisdisplayed.
UsingCode
ThefollowingexamplesetstheAllowAutoFilter('AllowAutoFilterProperty'intheon-linedocumentation)andZoomFactor('ZoomFactorProperty'intheon-linedocumentation)properties.
CSfpSpread1.ActiveSheet.Columns[1].AllowAutoFilter = true;fpSpread1.ActiveSheet.ZoomFactor = 2;
VBFpSpread1.ActiveSheet.Columns(1).AllowAutoFilter = TrueFpSpread1.ActiveSheet.ZoomFactor = 2
Using Touch Support with Grouping
Youcanusetouchgestureswhengrouping.
Pressdownonacolumnheaderandthenslidetothegroupbararea.Releasetocreateagroup.
Tapthegroupheaderbuttonareatosort.
Youcanchangethegrouporder.Pressdownonthegroupheaderbuttonandthenslide.Releaseoverthetargetpositiontochangetheorder.
Youcanexpandorcollapsethegroupbytappingtheplusorminussymbol.
SettheZoomFactor('ZoomFactorProperty'intheon-linedocumentation)propertytochangethesizeofthe
Spread Windows Forms Developer’s Guide 684
Copyright © GrapeCity, Inc. All rights reserved.
control.Touchgesturesareeasiertouseifthecontroliszoomed.
SettheAllowColumnMove('AllowColumnMoveProperty'intheon-linedocumentation),AllowGroup('AllowGroupProperty'intheon-linedocumentation),andGroupBarInfo.Visible('VisibleProperty'intheon-linedocumentation)propertiestotruetoallowgroupingwithtouchgestures.
UsingCode
ThefollowingexamplesetstheAllowColumnMove('AllowColumnMoveProperty'intheon-linedocumentation),AllowGroup('AllowGroupProperty'intheon-linedocumentation),GroupBarInfo.Visible('VisibleProperty'intheon-linedocumentation),andZoomFactor('ZoomFactorProperty'intheon-linedocumentation)properties.
CSfpSpread1.AllowColumnMove = true;fpSpread1.ActiveSheet.GroupBarInfo.Visible = true;fpSpread1.ActiveSheet.AllowGroup = true;fpSpread1.ActiveSheet.ZoomFactor = 2;
VBFpSpread1.AllowColumnMove = TrueFpSpread1.ActiveSheet.GroupBarInfo.Visible = TrueFpSpread1.ActiveSheet.AllowGroup = TrueFpSpread1.ActiveSheet.ZoomFactor = 2
Using Touch Support with Range Grouping
Youcanusetouchgestureswhenexpandingorcollapsingrangegroups.
Taptheexpandorcollapsebuttontoexpandorcollapsetherangegroup.
SettheZoomFactor('ZoomFactorProperty'intheon-linedocumentation)propertytochangethesizeofthecontrol.Touchgesturesareeasiertouseifthecontroliszoomed.
UsingCode
ThefollowingcodecreatesarangeoroutlinegroupandsetstheZoomFactor('ZoomFactorProperty'intheon-linedocumentation)property.
CSfpSpread1.ActiveSheet.Rows.Count = 11;
Spread Windows Forms Developer’s Guide 685
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.ActiveSheet.Columns.Count = 6;fpSpread1.InterfaceRenderer = null;fpSpread1.ActiveSheet.RangeGroupBackgroundColor = Color.LightGreen;fpSpread1.ActiveSheet.RangeGroupButtonStyle = FarPoint.Win.Spread.RangeGroupButtonStyle.Enhanced;fpSpread1.ActiveSheet.AddRangeGroup(0, 8, true);fpSpread1.ActiveSheet.AddRangeGroup(0, 5, true);fpSpread1.ActiveSheet.AddRangeGroup(1, 3, false);fpSpread1.ActiveSheet.AddRangeGroup(1, 2, false);fpSpread1.ZoomFactor = 2;
VBFpSpread1.ActiveSheet.Rows.Count = 11FpSpread1.ActiveSheet.Columns.Count = 6FpSpread1.InterfaceRenderer = NothingFpSpread1.ActiveSheet.RangeGroupBackgroundColor = Color.LightGreenFpSpread1.ActiveSheet.RangeGroupButtonStyle = FarPoint.Win.Spread.RangeGroupButtonStyle.EnhancedFpSpread1.ActiveSheet.AddRangeGroup(0, 8, True)FpSpread1.ActiveSheet.AddRangeGroup(0, 5, True)FpSpread1.ActiveSheet.AddRangeGroup(1, 3, False)FpSpread1.ActiveSheet.AddRangeGroup(1, 2, False)FpSpread1.ZoomFactor = 2
Using Touch Support when Moving Columns or Rows
Youcanusetouchgesturestomovecolumnsorrows.
Pressthecolumnheaderorrowheadertoselectit,thenslidetothetargetlocation.Releasetomovethecolumnorrow.
Selectacolumnorrowheaderrangeandthenpressandslidetomovetherange.Releasetocompletetheaction.
TheAllowColumnMove('AllowColumnMoveProperty'intheon-linedocumentation)propertymustbetruetomovecolumns.AllowColumnMove('AllowColumnMoveProperty'intheon-linedocumentation)andAllowColumnMoveMultiple('AllowColumnMoveMultipleProperty'intheon-linedocumentation)mustbetruetomovemultiplecolumns.TheAllowRowMove('AllowRowMoveProperty'intheon-linedocumentation)propertymustbetruetomoverows.AllowRowMove('AllowRowMoveProperty'intheon-linedocumentation)andAllowRowMoveMultiple('AllowRowMoveMultipleProperty'intheon-linedocumentation)mustbetruetomovemultiplerows.TheAllowRowMoveDataAllowAddNew
Spread Windows Forms Developer’s Guide 686
Copyright © GrapeCity, Inc. All rights reserved.
('AllowRowMoveDataAllowAddNewProperty'intheon-linedocumentation)propertymustbetruetomovearowbelowtheaddnewroworasteriskrow.
RefertoUsingTouchSupportwithSelectionsformoreinformationonhowtoselectacolumnorrow.
UsingCode
ThisexamplesetstheAllowColumnMove('AllowColumnMoveProperty'intheon-linedocumentation),AllowColumnMoveMultiple('AllowColumnMoveMultipleProperty'intheon-linedocumentation),AllowRowMove('AllowRowMoveProperty'intheon-linedocumentation),andAllowRowMoveMultiple('AllowRowMoveMultipleProperty'intheon-linedocumentation)properties.
CSfpSpread1.AllowColumnMove = true;fpSpread1.AllowColumnMoveMultiple = true;fpSpread1.AllowRowMove = true;fpSpread1.AllowRowMoveMultiple = true;
VBFpSpread1.AllowColumnMove = TrueFpSpread1.AllowColumnMoveMultiple = TrueFpSpread1.AllowRowMove = TrueFpSpread1.AllowRowMoveMultiple = True
UsingCode
ThisexamplesetstheAllowRowMoveDataAllowAddNew('AllowRowMoveDataAllowAddNewProperty'intheon-linedocumentation)propertyafterbindingthecontrol.TheDataAllowAddNew('DataAllowAddNewProperty'intheon-linedocumentation)propertymustbetruetoallowtheasteriskrow.
CSDataSet ds = new DataSet();DataTable emp = new DataTable("Employees");DataTable div = new DataTable("Division");emp.Columns.Add("LastName");emp.Columns.Add("FirstName");emp.Rows.Add(new Object[] { "Jones", "Marianne" });emp.Rows.Add(new Object[] { "Fieldes", "Anna" });div.Columns.Add("Section");div.Columns.Add("Specialty");div.Rows.Add(new Object[] { "Finance", "Taxes" });div.Rows.Add(new Object[] { "Mergers", "Legal" });ds.Tables.AddRange(new DataTable[] { emp, div });fpSpread1.DataSource = ds;fpSpread1.DataMember = "Division";fpSpread1.AllowRowMove = true;fpSpread1.AllowRowMoveMultiple = true;fpSpread1.ActiveSheet.DataAllowAddNew = true;fpSpread1.AllowRowMoveDataAllowAddNew = true;
VBDim ds As New DataSet()Dim emp As New DataTable("Employees")Dim div As New DataTable("Division")
Spread Windows Forms Developer’s Guide 687
Copyright © GrapeCity, Inc. All rights reserved.
emp.Columns.Add("LastName")emp.Columns.Add("FirstName")emp.Rows.Add(New Object() {"Jones", "Marianne"})emp.Rows.Add(New Object() {"Fieldes", "Anna"})div.Columns.Add("Section")div.Columns.Add("Specialty")div.Rows.Add(New Object() {"Finance", "Taxes"})div.Rows.Add(New Object() {"Mergers", "Legal"})ds.Tables.AddRange(New DataTable() {emp, div})fpSpread1.DataSource = dsfpSpread1.DataMember = "Division"fpSpread1.AllowRowMove = TruefpSpread1.AllowRowMoveMultiple = TruefpSpread1.ActiveSheet.DataAllowAddNew = TruefpSpread1.AllowRowMoveDataAllowAddNew = True
Using Touch Support when Resizing Columns or Rows
Youcanresizecolumnsorrowsusingtouchgestures.
Selectacolumnorrow(taptoselect),pressthecolumnorrowresizehandleandslidetochangethewidthorheight,andthenrelease.
FpSpreadprovidesaResizeZeroIndicator('ResizeZeroIndicatorProperty'intheon-linedocumentation)propertythatspecifiesthepolicywhenacolumnorrowisresizedtozero.IfthepropertyissettoDefaultwhenusingtouchgestures,acolumnwithzerowidthcannotberesized(orarowwithaheightofzero).IfthepropertyvalueisEnhanced,thenazerowidthcolumn(orzeroheightrow),canberesized.Selectthecolumnorrow,andpressandholdtheresizehandletoresizethevisiblecolumnorrow.Tapthecenterofthetwoshortlinestoselectthecolumnwithawidthofzero(orrowwithaheightofzero),thenpressandholdtheresizehandletoresizethecolumn(orrow).
Thefollowingimagedisplaysaselected,zerowidthcolumn.
ThecolumnorrowResizable('ResizableProperty'intheon-linedocumentation)propertymustbetruetoresizeacolumnorrow.
FpSpreadprovidesaResizeZeroIndicator('ResizeZeroIndicatorProperty'intheon-linedocumentation)propertythatspecifiesthepolicywhenacolumnorrowisresizedtozero.Whenusingthemouse,thedefaultvaluedisplaysthesamemousecursorforresizingandresizing-out.TheEnhancedvaluedisplaysaresizecursortotheleftofacolumnheaderborderandaresize-outcursortotherightofacolumnheaderborder.
UsingCode
ThefollowingexampleallowstheusertoresizezerowidthcolumnsorzeroheightrowsbysettingtheResizeZeroIndicator('ResizeZeroIndicatorProperty'intheon-linedocumentation)propertytoEnhanced.
Spread Windows Forms Developer’s Guide 688
Copyright © GrapeCity, Inc. All rights reserved.
CSfpSpread1.ResizeZeroIndicator = FarPoint.Win.Spread.ResizeZeroIndicator.Enhanced;fpSpread1.ActiveSheet.Columns[0, 5].Resizable = true;fpSpread1.ActiveSheet.Rows[0, 10].Resizable = true;fpSpread1.ActiveSheet.Columns[2].Width = 0;
VBFpSpread1.ResizeZeroIndicator = FarPoint.Win.Spread.ResizeZeroIndicator.EnhancedFpSpread1.ActiveSheet.Columns(0, 5).Resizable = TrueFpSpread1.ActiveSheet.Rows(0, 10).Resizable = TrueFpSpread1.ActiveSheet.Columns(2).Width = 0
Using Touch Support with Scrolling
Youcanusetouchgestureswhenscrollinginthecontrol.
Youcantapthescrollbarorpressandslidethescrollbartoscroll.Youcanalsousepanninggesturesinthecellareaofthecontrol(vertical,horizontal,diagonal,oroblique).Panninginthediagonaldirectionscrollshorizontallyandvertically.SpecifythetypeofpanningmodewiththePanningMode('PanningModeProperty'intheon-linedocumentation)property.
Spread Windows Forms Developer’s Guide 689
Copyright © GrapeCity, Inc. All rights reserved.
YoucanspecifyfeedbackwhenscrollingwiththeBoundaryFeedbackMode('BoundaryFeedbackModeProperty'intheon-linedocumentation)property(standardorsplit).Formoreinformationonstandard,seehttp://msdn.microsoft.com/en-us/library/windows/desktop/dd317331(v=vs.85).aspx.TheSplitoptionseparatesfrozenandscrollableareasorheadersandscrollableareas.
UsingCode
ThisexamplesetsthePanningMode('PanningModeProperty'intheon-linedocumentation)propertytoallowhorizontalandverticalpanningandspecifiesthetypeoffeedback.
CSfpSpread1.PanningMode = FarPoint.Win.Spread.SpreadPanningMode.Both;fpSpread1.BoundaryFeedbackMode = FarPoint.Win.Spread.BoundaryFeedbackMode.Split;
VBFpSpread1.PanningMode = FarPoint.Win.Spread.SpreadPanningMode.BothFpSpread1.BoundaryFeedbackMode = FarPoint.Win.Spread.BoundaryFeedbackMode.Split
Using Touch Support with Selections
Spread Windows Forms Developer’s Guide 690
Copyright © GrapeCity, Inc. All rights reserved.
Youcanselectcolumns,rows,cellranges,andtheentirecontrolusingtouchgestures.
Tapacelltoselectthecellanddisplaytheselectiongripper.Pressthecellselectiongripperandslide.Releasetoselectacellrange.
Tapacolumnheader(orrowheader)toselectacolumn(orrow).Youcanthenpresstheselectiongripperandslidetoselectacolumnrange(orrowrange).Releasetocompletetheselection.Youcanalsoselectacolumnorrowrangebytappingaheaderandthenslidingintheheaderarea.Releasetocompletetheselection.ThisactionrequiresthattheAllowColumnMove('AllowColumnMoveProperty'intheon-linedocumentation)property(orAllowRowMove('AllowRowMoveProperty'intheon-linedocumentation)property)besettofalse.
Youcanselecttheentirecontrolbytappingthecornerheader.
Youcanchangethesizeofthecellrangeselectionbypressingtheselectiongripperandslidinginanydirection.Releasetocompletetheaction.
Youcanselectmultipleranges.Selectarange,thentapacellinadifferentlocationtostartthenextselection.Usethegrippertoselectthesecondrange.SettheTapToAddSelection('TapToAddSelectionProperty'intheon-linedocumentation)propertytotrue.TheSelectionPolicy('SelectionPolicyProperty'intheon-linedocumentation)propertymustbesettoMultiRangeandtheUseOptimizedSelectionForTouch('UseOptimizedSelectionForTouchProperty'intheon-linedocumentation)propertymustbetrue.SettheOperationMode('OperationModeProperty'intheon-linedocumentation)propertytoNormalorReadOnly.Thefollowingimagedisplaysmultipleselectionsandgrippersaroundoneselectedcellrange.
YoucantaptoselectorunselectarowwhentheOperationMode('OperationModeProperty'intheon-linedocumentation)propertyissettoMultiSelect.ThegripperisnotdisplayedwhenusingMultiSelect.IftheOperationModepropertyissettoExtendedSelect,youcantaptoselectarow,butnottounselecttherow.ThegripperisdisplayedwithExtendedSelectandcanbeusedtoselectarangeofrows.
SettheUseOptimizedSelectionForTouchtotruetodisplayaselectiongripperforselectingacellrange.Thegripperisdisplayedwhentouchingthecell,column,orrow.Thegripperisnotdisplayedwhenusingthemouseorkeyboard.
Theborderisdisplayedaroundtheselectedcellrangewhenusingtouchoperations.
Theselectiongrippersaredisplayedontheoutsideedgeoftherange(top-leftandbottom-rightedges,bydefault).YoucancustomizethegripperappearanceusingtheTouchSelectionGripperThickness('TouchSelectionGripperThicknessProperty'intheon-linedocumentation),TouchSelectionGripperLineColor('TouchSelectionGripperLineColorProperty'intheon-linedocumentation),andTouchSelectionGripperBackColor('TouchSelectionGripperBackColorProperty'intheon-linedocumentation)properties.YoucanchangethelocationofthegripperswiththeRightToLeftproperty.
UsingCode
ThefollowingexampleallowsmultipleselectionsusingtouchsupportandsetstheTouchSelectionGripperBackColor('TouchSelectionGripperBackColorProperty'intheon-linedocumentation),TouchSelectionGripperLineColor('TouchSelectionGripperLineColorProperty'intheon-linedocumentation),andTouchSelectionGripperThickness('TouchSelectionGripperThicknessProperty'intheon-linedocumentation)properties.
CSfpSpread1.TouchSelectionGripperBackColor = Color.Aquamarine;fpSpread1.TouchSelectionGripperLineColor = Color.DarkMagenta;
Spread Windows Forms Developer’s Guide 691
Copyright © GrapeCity, Inc. All rights reserved.
fpSpread1.TouchSelectionGripperThickness = 2;fpSpread1.TapToAddSelection = true;fpSpread1.ActiveSheet.SelectionPolicy = FarPoint.Win.Spread.Model.SelectionPolicy.MultiRange;fpSpread1.UseOptimizedSelectionForTouch = true;
VBFpSpread1.TouchSelectionGripperBackColor = Color.AquamarineFpSpread1.TouchSelectionGripperLineColor = Color.DarkMagentaFpSpread1.TouchSelectionGripperThickness = 2FpSpread1.TapToAddSelection = TrueFpSpread1.ActiveSheet.SelectionPolicy = FarPoint.Win.Spread.Model.SelectionPolicy.MultiRangeFpSpread1.UseOptimizedSelectionForTouch = True
Using Touch Support with Shapes
Youcanusetouchgestureswithshapes.
Usethefollowingtouchgestureswithshapes:
TouchGesture
MouseAction Action
Tap Click Selectsacellnote,shape,orchart.
Double-tap Double-Click Editsacellnote,shape,orchartifeditingissupported.
Pressedgethenslide
Pressleftbuttononedgethenmove
Resizesacellnote,shape,orchartifCanSize('CanSizeProperty'intheon-linedocumentation)issettotrue.
Pressshapethenslide
Pressleftbuttononshapethenmove
Movesacellnote,shape,orchartifCanMove('CanMoveProperty'intheon-linedocumentation)issettotrue.
Pressrotatedhandleandslide
Pressleftbuttononrotatedhandleandmove
RotatesashapeorchartifCanRotate('CanRotateProperty'intheon-linedocumentation)issettotrue.
Using Touch Support when Sorting
Youcanusetouchgestureswhensorting.
Tapthesortindicatortosort.TheAllowAutoSort('AllowAutoFilterProperty'intheon-linedocumentation)propertymustbetruetousetouchgestures.Thefollowingimagedisplayssortindicators.
SettheZoomFactor('ZoomFactorProperty'intheon-linedocumentation)propertytochangethesizeofthe
Spread Windows Forms Developer’s Guide 692
Copyright © GrapeCity, Inc. All rights reserved.
control.Sometouchgesturesareeasiertouseifthecontroliszoomed.
Note:Iftheuserselectsacolumnthatcontainssortingandfilteringindicators,theresizegripperisdisplayed.Thegripperhasahigherprioritythanthefilterlistorsortoperation.SettheHeaderIndicatorPositionAdjusting('HeaderIndicatorPositionAdjustingProperty'intheon-linedocumentation)propertytospecifythedistancebetweenthesortingandfilteringindicatorsandtherightedgeofthecolumnsothattheusercansortorfilterthecolumnwhilethegripperisdisplayed.
UsingCode
Thefollowingexampleallowssortingandzoomsthecontrol.
CSfpSpread1.ActiveSheet.Columns[0, 3].AllowAutoSort = true;fpSpread1.ActiveSheet.ZoomFactor = 2;
VBFpSpread1.ActiveSheet.Columns(0, 3).AllowAutoSort = TrueFpSpread1.ActiveSheet.ZoomFactor = 2
Using Touch Support with Viewports
Youcanusetouchgestureswithviewports.
Pressthesplitboxandslidetodisplaythesplitlineorbar.Pressonthelineandslidetochangethesizeoftheviewport.
Youcandouble-tabasplitlinetoremovetheviewport.
Using Touch Support with the Tab Strip
Youcanusetouchgestureswiththetabstrip.Youcanchangetabs,selectasheet,editasheet,andscroll.
Tapthetabstripbuttonstonavigatethetabstrip.Tapasheetnameinthetabstriptoselectthesheet.Double-tapasheetnameinthetabstriptoeditthesheetname.Youcanusepanningtoscrollthroughthesheetsinthetabstripiftherearemoresheetsthancanbedisplayedinthetabstriparea.TheEditable('EditableProperty'intheon-linedocumentation)propertymustbetrueforthetabstripinordertoeditthesheetnames.
SettheZoomFactor('ZoomFactorProperty'intheon-linedocumentation)propertytochangethesizeofthetabstripbuttons.Sometouchgesturesareeasiertouseifthecontroliszoomed.
Spread Windows Forms Developer’s Guide 693
Copyright © GrapeCity, Inc. All rights reserved.
Using Touch Support with Zooming
Youcanusethepinchoperationwhenzooming.
SettheAllowUserToTouchZoom('AllowUserToTouchZoomProperty'intheon-linedocumentation)propertytoallowzoomingusingthepinchoperation.
YoucanusetheTouchZoomSnapPoints('TouchZoomSnapPointsProperty'intheon-linedocumentation)propertytoconfiguresnappoints.Whenzooming,ifthefinalzoomfactoriscloseto(lessthantheTouchZoomSnapDistance('TouchZoomSnapDistanceProperty'intheon-linedocumentation)propertyvalue)asnappoint,thefinalzoomfactorchangestothesnappoint.Forexample,add1tothesnappoint.Whentheuserchangesthezoomfactorto103%,thezoomfactorchangesto100%.
FpSpreadusesstandardpinchandstretchgestureswhenzooming.Formoreinformation,seehttp://msdn.microsoft.com/en-us/library/windows/apps/hh465415.aspx.
UsingCode
Thefollowingexampleallowszoomingwiththepinchoperation.
CSfpSpread1.AllowUserToTouchZoom = true;fpSpread1.MinZoomFactor = .1F;fpSpread1.TouchZoomSnapDistance = 1;fpSpread1.TouchZoomSnapPoints.Add(1f);fpSpread1.TouchZoomSnapPoints.Add(2f);
VBFpSpread1.AllowUserToTouchZoom = TrueFpSpread1.MinZoomFactor = .1FFpSpread1.TouchZoomSnapDistance = 1FpSpread1.TouchZoomSnapPoints.Add(1f)FpSpread1.TouchZoomSnapPoints.Add(2f)
Spread Windows Forms Developer’s Guide 694
Copyright © GrapeCity, Inc. All rights reserved.
2 Index
celltypes
multipleoptionbutton,370-372
cells
formatter,312
columnheaders
gridlines,157-160
cursors
forresizing,268-269
Excelfile
openinginSpread,535-536
including
cellnotesinsearch,242
celltagsinsearch,242
multiple
headers,81-84
parts
splitboxes,222-224
renderers
focusindicator,400-403
settingcelltype
combobox(multiplecolumn),367-370
listbox,365-367
sheetcorner
colors,131-132
images,131-132
styles
XPthemes,115-116
tabs
sheetnames,204-209
themes
XPthemes,115-116
abortdialog
printing,558-563
accessibility
HitTest,216-217
actions
undo,215-216
undoandredo(overview),60
active
cell,86-87
Spread Windows Forms Developer’s Guide 695
Copyright © GrapeCity, Inc. All rights reserved.
celltypeofactivecell,313
sheet,68-69
sheettab,204-209
add,227-228
adding
cellspans,180-182,58
columns,77-78
controlstosheet,225-226
customfunction,437-440
customnames,436-437
notes,410-413
rows,77-78
shapes,258-260
sheets,70-71
spans,180-182,58
styles,186-189
tags,252-253,251-252,251
AddingaChartControl,657-664
AddingaComponenttoaProject,30-32
AddingaComponenttoaVisualStudio2013Project,28-30
AddingaComponenttoaVisualStudio2015or2017Project,26-28
AddingaContextMenu,671
AddingaContextMenutoaComponent,212-213
AddingaGradienttoHeaderCells,156-157
AddingaNotetoaCell,410-413
AddingaPageBreak,571-572
AddingaRoworColumn,77-78
AddingaRowtoaBoundSheet,455-456
AddingaSheet,70-71
AddingaSparklinetoaCell,189-191
AddingaTable,227-228
AddingaTableFormula,236-237
AddingaTagtoaCell,252-253
AddingaTagtoaRoworColumn,251-252
AddingaTagtoaSheet,251
AddingaTitleandSubtitletoaSheet,122-123
AddingaWatermarktoaPrintedPage,572-573
AddinganUnboundColumntoaBoundSheet,458-459
AddinganUnboundRowtoaBoundSheet,456-458
addingdata,644
AddingFormulastoCalculateBalances,48-49
AddingSpreadtotheCheckbookProject,44
AddingSupportforHighDPISettings,37-39
Spread Windows Forms Developer’s Guide 696
Copyright © GrapeCity, Inc. All rights reserved.
AddingtoBoundData,455
advancedoptions
includingcellnotes,242
includingcelltags,242
includingheaders,242
advancedsearchdialog,242
AligningCellContents,168-170
alignment
cellcontents,168-170
allowing
formulaediting,435-436
mergingcells,182-184
userresizing,268-269
zooming,211
AllowingaComboBoxCelltoHandleaDoubleClick,383-385
AllowingCellDatatoOverflow,184-186
AllowingCellstoMergeAutomatically,182-184
AllowingtheDisplayofButtonsinaCell,399-400
AllowingtheUsertoAutomaticallySortRows,305-307
AllowingtheUsertoChangetheChart,669-670
AllowingtheUsertoDrawwithaTabletPC,261-262
AllowingtheUsertoEnterDatainRowsorColumns,265-266
AllowingtheUsertoEnterFormulas,435-436
AllowingtheUsertoFilterRows,275-276
AllowingtheUsertoGroupRows,295-296
AllowingtheUsertoMoveRowsorColumns,266-268
AllowingtheUsertoPerformaStandardSearch,241-242
AllowingtheUsertoPerformanAdvancedSearch,242
AllowingtheUsertoResizeRowsorColumns,268-269
AllowingtheUsertoZoomtheDisplayoftheComponent,211
AllowingUserFunctionality,253-255
AllowingUserInteractionwithRowsandColumns,265
alternatesearch,241-242
alternatingrows,147-149
anchorcells,180-182
annotationmode,260-261
overview,57-58
appearance
cellborders,172-176
cellsettings,163-164,86
columnsettings,143,75-76
groupingaffecton,299-300
Spread Windows Forms Developer’s Guide 697
Copyright © GrapeCity, Inc. All rights reserved.
headers,149-150,80-81
overallcomponent,101
rowsettings,143,75-76
Seealsostyles,186-189
selections,247-250
settingsingeneral,101,68
sheetsettings,117,68
visualstyles,115-116
applicationtags,252-253,251-252,251
ApplyingaSkintoaSheet,128-129
ApplyingaSkintotheComponent,103-104
AreaCharts,585-587
arranging
columns,307-309,307
rows,307-309,307
arrows
scrollbar,198-202
sortindicators,305-307
ascending
sortindicator,305-307
assembly
TextRenderer,59-60
autocomplete,390
autofit,268-269,676
automatic
completion,390,356-359
mergingcells,182-184,58
text,150-152
automaticcompletion,390,356-359
automaticfit,676
axis,614-615
AxisandOtherLines,614-615
axismodel,89-91
background
colors,164-166
imageincell,166-168
imageprinting,572-573
BarCharts,587-590,584
barcode
celltype,340-345
bars
grouping,296-297
progress,372-374
Spread Windows Forms Developer’s Guide 698
Copyright © GrapeCity, Inc. All rights reserved.
basemodels,89-91
bestsize,145-146
cells,170-171
bidirectionaldisplay,116-117
BIFF12format
opening,535-536
BIFF8format
opening,535-536
BindingaCellRangeinSpreadasaDataSourcetoanExternalControl,449-451
BindingaCellRangeinSpreadtoanExternalDataSource,447-449
BindingaComboBoxtoaDataReader,454-455
BindingSpreadtoanExternalDataSet,446-447
BindingtheChartControl,667-669
BindingtoData,446
bindingtodatasets
addingunboundrows,455-456,458-459,456-458
celltypes,461-463
changingcolumnassignment,451-454
columnheaders,459-461
defaultbinding,446-447
overview,53
blocks(Seeranges),87-88
borders,172-176,614-615
cells,172-176
creating,172-176
customizing,172-176
introduction,172-176
kinds,172-176
multiplelines,178-180
overallcomponent,112-113
printing,564-565,558-563
printingsheetborders,558-563
styles,172-176
bound,644-646
bubblecharts,584
built-infunctions,54-55
buttons
about,399-400
celltype,345-349
displaying,399-400
gradient,345-349
tabstrip,204-209
Spread Windows Forms Developer’s Guide 699
Copyright © GrapeCity, Inc. All rights reserved.
visualstyles,115-116
XPthemes,115-116
calculator
notdisplaying,330-335
pop-up,388-390
calendar
pop-up,386-388
CameraShapes,52-53
cell,681-684
cellborders,172-176
styles,172-176
celleditor
validation,481-485
cellnotes,410-413
includinginsearch,242
NoteStyle,410-413
celloverflow,184-186
cellranges
printing,555-556,552-553,558-563,553-555
cellreferences
style,428-430
cellspans,180-182
adding,180-182
columnheaders,161-163
removing,180-182
rowheaders,161-163
CellSpansintheSheetCorner,138-139
celltags
includinginsearch,242
celltypes,65-67,312
informulas,426-428
activecell,313
barcode,340-345
basics,312-313
button,345-349
checkbox,349-352
colorpicker,352-356
combobox,356-359
controls,339-340
currency,318-319
currency(tutorial),474-475
custom,391-395
databinding,461-463
Spread Windows Forms Developer’s Guide 700
Copyright © GrapeCity, Inc. All rights reserved.
date-time,319-321
default,327-329
double,330-335
editable,317-318
feature,53
general,327-329
graphical,339-340
headers,312-313
hyperlink,359-363
image,363-365
listbox,365-367
mask,329-330
multiplecolumncombobox,367-370
percent,335-337
progressindicator,372-374
regularexpression,337-338
richtext,374-378
setting,317-318,339-340
slidercontrol,378-381
sorting,304-305
text,338-339
time(Seedate-time),319-321
validation,481-485
CellTypesforCellFunctionality,53
cells
imagein,363-365
activecell,86-87
aligningcontents,168-170
anchorcell,180-182
appearancesettings,163-164,86
automaticmerging,182-184
backgroundimage,166-168
bestsize,170-171
borders,172-176
buttons,399-400
clearing,487-488
colorsetting,164-166
combiningintospan,180-182
conditionalformatting,423-426
copyingdata,485
customname,436-437
editmode,396-397
Spread Windows Forms Developer’s Guide 701
Copyright © GrapeCity, Inc. All rights reserved.
editor,312
fillingrange,480-481
focusindicator,400-403
formatter,327-329
gradientinheader,156-157
headers,149-150,80-81
hidingselectionhighlights,251
locking,397-399
merging,58
movingdata,485-486
multiplelineborder,178-180
notes,410-413
overflow,184-186
printingnotes,556-557
ranges,87-88
referencestyle,428-430
removing,487-488
renderer,312
resizing,170-171
searching,242-243
settingcelltypesfordatabinding,461-463
settingcolor,164-166
shortcutobject,163-164,61-64,86
sorting,58
spanning,180-182,58
swappingdata,486-487
tags,252-253
texttips,408-410
types,312
validation,481-485
centering
printing,564-565
ChanginganInputMapforaChildView,517-520
ChangingChartOptions,664-666
ChangingtheDefaultKeyboardMap,510-511
charactermask,329-330
chart,657,676-677
adding,657-664
binding,667-669
contextmenu,671
overview,657
plottypes,657
ChartCollectionEditors,653
Spread Windows Forms Developer’s Guide 702
Copyright © GrapeCity, Inc. All rights reserved.
ChartControlsonaSheet,53
chartdesigner,657
ChartDesignerToolbar,656-657
ChartLineStyle,618-620
ChartObjectModel,581-582
ChartTypesandViews,582-584
ChartUserInterfaceElements,580-581
checkbox
includingcelltags,242
includingheaders,242
celltype,349-352
includingcellnotes,242
child
inputmap,517-520
childcontrols,225-226
overview,53
ChildControlsonaSheet,53
childsheets,463-469
printing,550
childviews,463-469
printing,550
circularformula,431-432
circularreferences,431-432
classid,213
clearing
data,487-488
ClearingorRemovingPartsoftheInterface,257
ClickEvent
inFpSpreadcontrol,217
ClickingActions,522-525
Clipboard,677
contents,213-215
deactivating,213-215
excludingheaders,213-215
incode,213-215
operations,213-215
pasting,213-215
scope,213-215
clock
pop-up,386-388
collapsing
grouping,296-297
Spread Windows Forms Developer’s Guide 703
Copyright © GrapeCity, Inc. All rights reserved.
icon,209-211
collectioneditors,653
colorpicker
celltype,352-356
ColorScaleRules,416-417
ColoringaCell,164-166
colors
cellsetting,164-166
colorpicker,352-356
gradient,156-157
gradientinprogressindicator,372-374
gridlines,120-122
printing,564-565,558-563
rich-textcell,374-378
selections,247-250
sheetcorner,131-132
sheets,118-119
columnbar,268-269
columnfilterdefinition,287,280
ColumnFootersandGroupFooters,53
columnheaders,81
automatictext,150-152
content,152-154
customtext,152-154
displaying,84-86
hiding,84-86
multiple,55
multiplerows,81-84
printing,558-563
spans,161-163
style,154-156
text,150-152,152-154
width,160-161
columnwidth
preferredsize,145-146
columns
adding,77-78
appearancesettings,143,75-76
filterdefinition,287,280
freezing,269-271
headers,81
hiding,79-80
leadingfrozen,269-271
Spread Windows Forms Developer’s Guide 704
Copyright © GrapeCity, Inc. All rights reserved.
moving,266-268
number,76-77
removing,266-268,78-79
resizing,268-269,145-146
restrictingentry,265-266
shortcutobject,143,61-64,75-76
sortindicators,305-307
sorting,58,307-309,307
tags,251-252
trailingfrozen,269-271
width,143-145
combining
cellsintospan,180-182
mergingcells,182-184
CombiningPlotTypes,642-644
combobox
bindingtoDataReader,454-455
celltype,356-359,367-370
double-clicking,383-385
comma-delimitedfile
opening,535-536
comparing
conditionalformat,423-426
comparison
formatting,423-426
operators,423-426
completingentry(autocomplete),390
complexborder
multiplelines,178-180
ComplexBorderSideClass
using,178-180
component,28-30
components
appearance,101
borderstyle,112-113
contextmenu,212-213
resetting,257,255-257
Spread,50-51
compositeofsettings,64
CompoundBorderArrayProperty
using,178-180
computedvalue
Spread Windows Forms Developer’s Guide 705
Copyright © GrapeCity, Inc. All rights reserved.
customname,436-437
ConceptsOverview,61
conditionalformatting,423-426,53
conditionaloperators,415
conditions,423-426
ConnectingtoData,644
connectingtodatabase
tutorial,471-472
contents
copying,485
moving,485-486
swapping,486-487
context
customfunction,437-440
contextmenu
FpSpreadcomponent,212-213
rich-textcell,374-378
control
namebox,443-445
ControlClass(FpSpreadbasedon),217
controllayer,225-226
controls
appearance,101
borderstyle,112-113
calculator,388-390
calendar,386-388
childonsheet,225-226
clock,386-388
contextmenu,212-213
progress,372-374
slider,378-381
subeditor,390-391
zooming,211
copy,677
copying
data,485
filling,480-481
sheets,71-72
sheetsbetweencomponents,69-70
copying(SeeClipboardoperations),213-215
CopyingandInsertingaSheet,71-72
CopyingDataonaSheet,485
CopySheetMethod,71-72
Spread Windows Forms Developer’s Guide 706
Copyright © GrapeCity, Inc. All rights reserved.
corners(seesheetcorner),131-132
count
parameters,437-440
create,227-228
creating
customnames,436-437
cellborders,172-176
contextmenu,212-213
customfunction,437-440
datasettutorial,473-474
outlines,300
styles,186-189
CreatingaBuildLicense,22-23
CreatingaChartControl,650-653
CreatingaComplexBorderwithMultipleLines,178-180
CreatingaCustomCellType,391-395
CreatingaCustomFilter,287
CreatingaCustomGroup,299
CreatingaCustomSheetModel,98-99
CreatingaCustomSkinforaComponent,104-107
CreatingaCustomSkinforaSheet,129-131
CreatingaHeaderwithMultipleRowsorColumns,81-84
CreatingaHierarchicalDisplayManually,469-471
CreatingaPiePlot,634-636
CreatingaPolarPlot,636-639
CreatingaRadarPlot,639-642
CreatingaRangeofCells,87-88
CreatingaSpaninaHeader,161-163
CreatingaSpanofCells,180-182
CreatingaYPlot,627-629
CreatingAlternatingRows,147-149
CreatinganXYPlot,629-631
CreatinganXYZPlot,631-634
CreatingandApplyingaStyleforCells,186-189
CreatingandCustomizingCellBorders,172-176
CreatingandUsingaCustomFunction,437-440
CreatingandUsingaCustomName,436-437
CreatingBorderswithDiagonalLines,176-178
CreatingCameraShapes,262-264
CreatingCharts,626,626-627
CreatingConditionalFormattingwithRules,415-416
CreatingCustomHierarchyIcons,471
Spread Windows Forms Developer’s Guide 707
Copyright © GrapeCity, Inc. All rights reserved.
CreatingPlotTypes,626-627
CreatingTables,226-227
criteria
filter,287,280
culture,26
currency
minimumandmaximumvalues,385-386
celltype,318-319
decimalsymbol,318-319
formatting,318-319
separators,318-319
symbol,318-319
cursors
display,113-114
HitTestforlocating,216-217
insplitbar,218-222
locating(HitTest),216-217
setting,113-114
tabstrip,204-209
custom
celltypes,391-395
defaultinputmap,510-511
functions,437-440
functions,errorvalue,437-440
functions,numberofparameters,437-440
names,436-437
parametersincustomfunctions,437-440
rowfilters,287
textinheaders,152-154
custompainting,114-115,116-117
customstyles,186-189,58-59
CustomizableCellintheSheetCorner,137-138
customizing
cellborders,172-176
datamodel,98-99
focusindicator,400-403
gridlines,120-122
images,209-211
printing,558-563
selections,247-250
CustomizingAutomaticCompletion(TypeAhead),390
CustomizingCellBorders,172
CustomizingCellTypesforBoundSheets,461-463
Spread Windows Forms Developer’s Guide 708
Copyright © GrapeCity, Inc. All rights reserved.
CustomizingClipboardOperationOptions,213-215
CustomizingColumnandFieldBinding,451-454
CustomizingColumnHeadersforBoundSheets,459-461
CustomizingDataBinding,459
CustomizingDrawing,257-258
CustomizingEnhancedFiltering,290
CustomizingHeaderLabelText,152-154
CustomizingInteractionBasedonEvents,217
CustomizingInteractioninCells,396
CustomizingInteractionintheOverallComponent,198
CustomizingInteractionwithaSheet,218
CustomizingInteractionwithCellTypes,312
CustomizingMarkersandPoints,191-193
CustomizingPaintingofPartsoftheComponent,114-115
CustomizingRoworColumnInteraction,265
CustomizingRow,Column,andCellAppearance,143
CustomizingScrollBarTips,202-204
CustomizingSheetInteraction,198
CustomizingSimpleFiltering,276
CustomizingSplitBoxes,222-224
CustomizingtheAppearanceofaCell,163-164
CustomizingtheAppearanceofanOutline(RangeGroup),302-303
CustomizingtheAppearanceofHeaders,149-150
CustomizingtheAppearanceofthePrinting,558
CustomizingtheDefaultHeaderLabels,150-152
CustomizingtheDimensionsoftheComponent,111-112
CustomizingtheDisplayofthePointer,113-114
CustomizingtheFilterBar,294-295
CustomizingtheFilterList,280
CustomizingtheFocusIndicatorforaCell,400-403
CustomizingtheGroupBar,298-299
CustomizingtheHeaderGridLines,157-160
CustomizingtheIndividualSheetAppearance,117
CustomizingtheInputMaps,515-517
CustomizingtheNumberofRowsorColumns,76-77
CustomizingtheOutlineoftheComponent,112-113
CustomizingtheOverallComponentAppearance,101
CustomizingthePop-UpCalculatorControl,388-390
CustomizingthePop-UpDate-TimeControl,386-388
CustomizingthePositionintheDisplay,224-225
CustomizingthePrintJobSettings,563-564
CustomizingthePrintedPageHeaderorFooter,565-570
Spread Windows Forms Developer’s Guide 709
Copyright © GrapeCity, Inc. All rights reserved.
CustomizingthePrintedPageLayout,564-565
CustomizingtheRenderers,107-111
CustomizingtheRoworColumnAppearance,143
CustomizingtheScaleMode,211-212
CustomizingtheScrollBarsoftheComponent,198-202
CustomizingtheSelectionAppearance,247-250
CustomizingtheSheetAppearance,101
CustomizingtheSheetCornerAppearance,131-132
CustomizingtheSheetNameTabsoftheComponent,204-209
CustomizingtheStyleofHeaderCells,154-156
CustomizingtheUserErrorMessages,218
CustomizingtheUserInterfaceImages,209-211
CustomizingUndoandRedoActions,215-216
CustomizingUserSearchingofData,240-241
CustomizingUserSelectionofData,243
CustomizingViewports,218-222
cut,677
cutting(SeeClipboardoperations),213-215
data
clearing,487-488
copying,485
filtering,273-275
moving,485-486
removing,487-488
searching,242-243
sorting,304-305
swapping,486-487
viewinghierarchically,463-469
databar,417-419
DataBarRule,417-419
databinding,53
addingunboundrows,455-456,458-459,456-458
celltypes,461-463
changingcolumnassignments,451-454
columnheaders,459-461
comboboxtoDataReader,454-455
defaultbinding,446-447
overview,53
tutorial,474,471
datacharts,610-611
datamodel,89-91
customizing,98-99
optionalinterfaces,99-100
Spread Windows Forms Developer’s Guide 710
Copyright © GrapeCity, Inc. All rights reserved.
dataonly
savingtoXML,533-534
DataPlotTypes,610-611
dataset
tutorial,473-474
datasource,644-646
datatypes
informulas,426-428
databaseconnection
tutorial,471-472
DataReader
bindingcombbox,454-455
dates
pop-upcalendar,386-388
date-time
celltype,319-321
DeactivatingtheDefaultKeyboardMap,509-510
decimal
currency,318-319
default
celltype,327-329
headerstyle,154-156
inputmapchange,510-511
maps,501-502,495-501
models,89-91
DefaultKeyboardMaps,501-502
DefaultKeyboardNavigation,495-501
DefaultMapforExcelCompatibility,502-503
DefaultMapforExtendedSelectandWhenAncestorOfFocused,508-509
DefaultMapforExtendedSelectandWhenFocused,508
DefaultMapforMultiSelectandWhenAncestorOfFocused,508
DefaultMapforMultiSelectandWhenFocused,508
DefaultMapforNormalandWhenAncestorOfFocused,503-505
DefaultMapforNormalandWhenFocused,503
DefaultMapforReadOnlyandWhenAncestorOfFocused,505-506
DefaultMapforReadOnlyandWhenFocused,505
DefaultMapforRowModeandWhenAncestorOfFocused,506-507
DefaultMapforRowModeandWhenFocused,506
DefaultMapforSingleSelectandWhenAncestorOfFocused,507-508
DefaultMapforSingleSelectandWhenFocused,507
DefiningtheContentsoftheFilterItemList,280-284
DefiningtheOrderoftheItemsintheFilterItemList,284-285
Spread Windows Forms Developer’s Guide 711
Copyright © GrapeCity, Inc. All rights reserved.
deleting(Seeremoving.),73-74
descending
sortindicator,305-307
designer,648-649
SpreadDesigner,58
DeterminingtheCellTypeoftheActiveCell,313
DeterminingWhichHeaderRowDisplaystheIndicators,289-290
Developer'sGuide,0
FarPointSpreadforWindowsForms,0
diagonal,176-178
dialog
abortprinting,577
displayingforuser,576-577
printing,577
dialogs
colordialog,352-356
printing,558-563
search,242,241-242
dimensions,111-112
directions
fillingcells,404-408
display
customizing,114-115,116-117
displaying
activecell,86-87
activesheet,68-69
buttons,399-400
cursors,113-114
dateandtime,319-321
gridlines,120-122
hidingsheets,74-75
positioning,224-225
printabortdialog,577
printdialog,577
printpreview,578-579
rowsfiltered,280
sheettabstrip,204-209
texttips,408-410
userdialog,576-577
DisplayingaFooterforColumnsorGroups,123-127
DisplayingaPrintDialogfortheUser,577
DisplayinganAbortMessagefortheUser,577
DisplayingDialogsforUsers,576-577
Spread Windows Forms Developer’s Guide 712
Copyright © GrapeCity, Inc. All rights reserved.
DisplayingErrorIconsinCellsorRows,414-415
DisplayingGridLinesonaSheet,120-122
DisplayingSpinButtons,382-383
DisplayingTextTipsinaCell,408-410
displays
groupingaffecton,299-300
double-clicking
combobox,383-385
double-precision
celltype,330-335
double-precisionfloating-pointnumber(celltype),330-335
DoughnutCharts,601-602,584
drag,72-73
draganddrop,403-404
dragandfill,404-408
filldirection,404-408
dragandmove
columns,266-268
dragfill,677-679
drawing,260-261
annotationmode,260-261
buttons,399-400
Drawing(Rendering)Style,140-142
drawingspace
defined,257-258
drawingtext,59-60
drawings
annotations,260-261
inknotation,261-262
dropdown,679-680
drop-downlistcell,356-359,365-367,367-370
editmode,396-397
editable,680-681
EditBaseCellTypeClass
about,312-313
editing
automaticcompletion,390
editmode,396-397
formulas,426-428
editingformulas
allowinguseredit,435-436
editor
Spread Windows Forms Developer’s Guide 713
Copyright © GrapeCity, Inc. All rights reserved.
celltypes,312-313
editors
subeditors,390-391,217-218
elevation,620-621
ElevationandRotation,620-621
embedding
controlsonsheet,225-226
controlstosheet,225-226
End-UserLicenseAgreement,21-22
EnterEvent
inFpSpreadcontrol,217
EnteringDataActions,526
error
icon,414-415
row,414-415
errorvalue
asparameter,437-440
estimating(GoalSeek),434-435
evaluationorder,formulas,431-432
events
inFpSpread,217
overview,217
scrollbars,198-202
splitbars,218-222
validation,481-485
viewports,218-222
Excelcompatibility,520
Excelcompatibilityoption,502-503
Excelfile
opening,535-536
ExcelSupportwithImportandExportCapabilities,53-54
Excel-stylegrouping,300
exchanging
data,486-487
expanding
grouping,296-297
icon,209-211
exporting,53-54
PDFfile,548-550
expressions
namesinformulas,436-437
extendedcharactersets
probleminrich-textcell,374-378
Spread Windows Forms Developer’s Guide 714
Copyright © GrapeCity, Inc. All rights reserved.
FactorsofKeyboardMapUsage,493-495
FeatureOverview,51-52
features
groupingaffecton,299-300
undoandredo,60
files
.SKN(skin),544-545
OfficeOpenXML,535-536
PDFfile,548-550
zero-basedsheetindex,535-536
fill
copy,404-408
series,404-408
FillEffects,615-618
filling
rangeofcells,480-481
FillingCellswithDragandDrop,403-404
FillingCellswithDragandFill,404-408
FillingCellswithDragandMove,408
FillRangeMethod
illustrated,480-481
fills
direction,404-408
filter,276,228-231,684
bar,294-295
enhanced,290-293,294-295,290
filtercriteria,287,280
filtering,273-275
columnfilterdefinition,287,280
custom,287
hidingindicators,287
indicatorrow,287
indicators,287,209-211
introduction,273-275
rows,280
styles,277-280
FilteringDataonaSheet,54
filteringindicators
hiding,287
rowlocation,287
financial
celltype,318-319
Spread Windows Forms Developer’s Guide 715
Copyright © GrapeCity, Inc. All rights reserved.
finddialog,242,241-242
finding,242-243
formulavaluewithGoalSeek,434-435
sheetbyname,69-70
FindingaValueUsingGoalSeek,434-435
FindingMoreDetailsontheSheetModels,91-92
FindingRowsorColumnsThatHaveData,146-147
FindingtheDocumentation,41-43
firstcondition,423-426
fitting
data,170-171,145-146
floatingobjects(shapes),257-258
floatingpoint
celltype,330-335
floatingtoolbars,440
floating-pointnumber(celltype),330-335
focusindicators
customizing,400-403
hiding,251
hidingrectangle,251
focuslocation(inmapping),493-495
fonts
rich-textcell,374-378
styleinrich-textcell,374-378
footers
printing,565-570,558-563,570-571
foreground
color,164-166
formatstring
generalcell,327-329
FormattedversusUnformattedData,64-65
formatter,327-329
celltypes,312-313
generalcell,327-329
formatting
cellsconditional,423-426
currency,318-319
currencycell,318-319
generalcelltype,327-329
inheriting,64
richtextcell,374-378
formula,240,236-237
formulabars,440-442
Spread Windows Forms Developer’s Guide 716
Copyright © GrapeCity, Inc. All rights reserved.
FormulaEditor,426-428
FormulaProviderControl,54
FormulaTextBox(FormulaBar),54
formulas,54-55
allowinguseredit,435-436
cellreference,428-430
celltypes,426-428
circularreference,431-432
customfunctions,437-440
customname,436-437
customnames,436-437
datatypes,426-428
floatingtoolbar,440-442
FormulaEditor,426-428
GoalSeek,434-435
nestingfunctions,432-433
one-based,428-430,430-431
orderofevaluation,431-432
placingincell,426-428
sheetreference,430-431
workingwith,426
FpSpread
events,217
fractions,330-335
free-handdrawing,260-261
freezing
rowsorcolumns,269-271
frozen
leadingrowsorcolumns,269-271
trailingrowsorcolumns,269-271
frozenrowsorcolumns,269-271
functions,54-55
custom,437-440
parametersincustomfunctions,437-440
FunctionsandFormulas,54-55
GDI
drawingtext,59-60
general
celltype,327-329
formatter,327-329
GeneralStyleoftheSheetCorner,132-135
genericcell(Seegeneralcelltype),327-329
Spread Windows Forms Developer’s Guide 717
Copyright © GrapeCity, Inc. All rights reserved.
gestures,672
GetReservedCursorMethod
using,113-114
GettingMorePractice,41
GettingStarted,21
GettingTechnicalSupport,43
globalinputmaps,493-495
GoalSeek,434-435
using,434-435
gradient
overview,55
gradients,156-157,345-349
button,345-349
header,156-157
inheadercells,156-157
progressindicatorcell,372-374
GradientsforButtonCells,Headers,andMore,55
graphics
incell,363-365
sheetcorner,131-132
gridlines,120-122
about,120-122
cellborders,172-176
colors,120-122
columnheaders,157-160
headers,157-160
printing,564-565,558-563
rowheaders,157-160
style,120-122
three-dimensional,120-122
group,684-685
grouping,296-297,295,685-686
bar,296-297
interoperability,299-300
multiplelevels,296-297
outline,300
overview,55
primary,296-297
secondary,296-297
spacingbetweengroupnames,298-299
GroupingRowsintheDisplay,55
GroupingRowsorColumnsinanOutline,55
HandlingDataUsingCellProperties,479-480
Spread Windows Forms Developer’s Guide 718
Copyright © GrapeCity, Inc. All rights reserved.
HandlingDataUsingSheetMethods,476-479
HandlingEventsofSubeditors,217-218
HandlingInstallation,21
HandlingRedistribution,23-25
HandlingRight-to-LeftLayouts,116-117
HeaderCountSynchronizationintheSheetCorner,139-140
headers,81
appearance,149-150,80-81
automatictext,150-152
celltypes,312-313
corner,131-132
defaultstyle,154-156
displaying,84-86
gradient,156-157
gridlines,157-160
height,160-161
hiding,84-86
includinginsearch,242
introduction,81
labeltext,152-154
labels,150-152
multiple,55,81-84
printing,565-570,558-563,570-571
resizingbasedon,145-146
setting,149-150,80-81
shortcutobject,81,61-64
size,160-161
sortindicators,305-307
spans,161-163
width,160-161
HeaderswithMultipleColumnsandRows,55
height
determiningbest,145-146
headerrow,160-161
rows,143-145
hidden
cellswhenspanned,180-182
hiding
cellsbyspanning,180-182
focusrectangle,251
headers,84-86
pop-upcalculator,330-335
Spread Windows Forms Developer’s Guide 719
Copyright © GrapeCity, Inc. All rights reserved.
rowsorcolumn,79-80
selections,251
sheets,74-75
HidingtheSelectionWhenFocusisLost,251
hierarchicalcollection,463-469
HierarchicalDisplay,55
hierarchy,463-469,55
collection,463-469
grouping,296-297
icons,209-211
inputmap,517-520
printing,550
HighlightingRules,419-421
highlights
selection,251
HitTest,216-217
general,216-217
HitTestforLocatingtheCursor,55
horizontal
alignment,168-170
scrollbars,202-204
host
overview,53
hosting
Webpage,213
HostingtheComponentonaWebPage,213
HTML
savingdata,529
savingtoTableelement,532-533
hyperlink
celltype,359-363
IconSetRule,421-422
icons
customizing,209-211
hierarchy,209-211
imagecell,363-365
images
backgroundincell,166-168
customizing,209-211
sheetcorner,131-132
transparent,363-365
ImplementingaSerializerClass,538-544
importing,53-54
Spread Windows Forms Developer’s Guide 720
Copyright © GrapeCity, Inc. All rights reserved.
fromExcelfile,535-536
improving
performance,488-491
ImprovingPerformancebySuspendingtheLayout,488-491
including
headersinsearch,242
index
zero-basedsheetinExcel,535-536
indicators
ascendingingrouping,296-297
cellnoteindicatorsize,410-413
currency,318-319
customizing,209-211
expandingingrouping,296-297
filter,287,209-211
filtering,287
focus,400-403
hidingfiltering,287
hidingsort,309-311
progress,372-374
resizingroworcolumn,268-269
rowlocation,287,309-311
selection,247-250
sort,309-311,305-307,209-211
IndicatorsandIconsintheInterface,55-56
inheritingformatting,64
inknotation,261-262
overview,56
InkNotationSupport,56
inking,261-262
overview,56
inputmapmode,493-495
inputmaps,502-503,503,56,492,515-517,520
childview,517-520
default,501-502,495-501
global,493-495
xml,520-521
inserting
columns,77-78
rows,77-78
sheets,70-71,71-72
InstallingtheProduct,21
Spread Windows Forms Developer’s Guide 721
Copyright © GrapeCity, Inc. All rights reserved.
InteractivityActions,527
interfaces
models,89-91
optionalmodel,99-100
interoperability
grouping,299-300
outline,300
InteroperabilityofGroupingwithOtherFeatures,299-300
InteroperabilityofOutlineswithOtherFeatures,303-304
invisible
headers,84-86
hidingsheets,74-75
rowsorcolumns,79-80
IsReservedLocationMethod
using,113-114
iterations,431-432
orderofevaluation,431-432
justification
printing,564-565
keyboard,673-674
KeyboardActionMapping,56
keyboardmapping
default,501-502,495-501
keys
mapping,503,56,515-517
keystrokemapping,493-495
LabelCollectionEditor,653-654
labels,624-625
automatictextinheaders,150-152
headertext,152-154
headers,150-152
landscapeorientation(printing),564-565
language,26
lastcondition,423-426
layers
drawingspace,257-258
layout
objects,488-491
resume,488-491
suspend,488-491
suspended,488-491
leading
frozenrowsorcolumns,269-271
Spread Windows Forms Developer’s Guide 722
Copyright © GrapeCity, Inc. All rights reserved.
legend,625-626
LegendCollectionEditor,654
Legends,625-626
LicensingaTrialProjectafterInstallation,21
light,621-623
LightCollectionEditor,655-656
lightcolor,621-623
Lighting,Shapes,andBorders,621-623
limiting
currencyvalues,385-386
LimitingValuesforaNumericCell,385-386
linechart,584
LineCharts,590-591
lines,614-615
cellborders,172-176
linkcell(Seehyperlinkcelltype),359-363
listboxes
celltype,365-367
load
inputmaps,520-521
loading
RTFfileinrich-textcell,374-378
skins,545-546
LoadingaSkin,545-546
LocatingthePointerUsingHitTest,216-217
locations
sheettabstrip,204-209
spreadsheet,224-225
locking
cells,397-399
LockingaCell,397-399
ManagingDataBinding,446
ManagingDataonaSheet,476
ManagingEventsfromUserActions,522
ManagingFileOperations,529
ManagingFilteringofRowsofUserData,273-275
ManagingFormulasinCells,426
ManagingGroupingofRowsofUserData,295
ManagingKeyboardInteraction,492
ManagingOutlines(RangeGroups)ofRowsandColumns,300
ManagingPrinting,547
ManagingSortingofRowsofUserData,304-305
Spread Windows Forms Developer’s Guide 723
Copyright © GrapeCity, Inc. All rights reserved.
mappingkeys,503,56,515-517
maps
defaultinputmapchange,510-511
defaultkeyboardmapping,501-502,495-501
inputmapforchildview,517-520
margins
printing,564-565,558-563
markers,191-193
marketcharts,591-593
MarketData(High-Low)Charts,591-593
mask
celltype,329-330
matching
insearch,241-242
maximumiteration,431-432
menu
contextmenu,212-213
mergepolicy,182-184
merging,182-184
cells,182-184,58
contrastwithspanning,182-184
introduction,182-184
message,672
models
axis,89-91
base,89-91
basisforcustomization,67,89
data,89-91
default,89-91
interfaces,89-91
optionalinterfaces,99-100
selection,89-91
sorting,304-305
span,89-91
style,89-91
types,89-91
modes
annotation,260-261
buttondisplay,399-400
gradient,156-157
gradientinprogressindicator,372-374
Inking,261-262
operation,244-247
Spread Windows Forms Developer’s Guide 724
Copyright © GrapeCity, Inc. All rights reserved.
monetary
celltype,318-319
move,686-688
moving
columns,266-268
data,485-486
rows,columns,266-268
sheets,72-73
splitbar,218-222
MovingaSheet,72-73
MovingDataonaSheet,485-486
multioptioncell,370-372
multiple
borderlines,178-180
headers,55
optionscelltype,370-372
panes,56,218-222
sheets,56,70-71,69-70
viewports,56,218-222
MultipleSheets,56
NameBoxControl,56
namemanager,443-445
namedexpressionsinformulas,436-437
namedrange
customname,436-437
namedstyles,186-189
names
custom,436-437
sheettab,204-209
tabstrip,204-209
NamespacesOverview,60-61
navigation,503,495-501
navigationkeys,503,56,515-517
NestingFunctionsinaFormula,432-433
notation
ink,261-262
note,676
notes
cells,410-413
includinginsearch,242
indicatorsize,410-413
printing,556-557
Spread Windows Forms Developer’s Guide 725
Copyright © GrapeCity, Inc. All rights reserved.
NotesforCells,56-57
NoteStyleproperty
forcellnotetodisplay,410-413
numbercell(Seeintegerordoublecelltype),330-335
numbers
columns,76-77
fractions,330-335
pop-upcalculator,388-390
rows,76-77
objectmodels,67,89-91
using,67
ObjectParentage,64
objects
parentage,64
OleDbDataAdaptercontrol
tutorial,472-473
one-basedref.s
informulas,428-430,430-431
opening,529
datafromfile,534
BIFF8formatfile,535-536
fromExcelfile,535-536
fromSpread6file,536-537
fromSpreadXMLfile,534-535
fromtextfile,537-538
skins,545-546
OpeningaCustomTextFile,537-538
OpeningaSpreadCOMFile,536-537
OpeningaSpreadXMLFile,534-535
OpeninganExcelFile,535-536
OpeningExistingFiles,534
OpeningtheChartDesigner,649-650
operationmode,244-247
inkeyboardmapping,493-495
introduction,244-247
operators
conditionalformatting,423-426
OptimizingthePrinting,573
OptimizingthePrintingUsingRules,573-576
OptimizingthePrintingUsingSize,576
optionbuttonscell,370-372
optional
interfaces,99-100
Spread Windows Forms Developer’s Guide 726
Copyright © GrapeCity, Inc. All rights reserved.
orderofprecedence,64
orientation,176-178
printing,576,564-565,558-563,573-576
outlinegrouping,300
Outlook-stylegrouping,296-297,295
overflow
contentsofcell,184-186
overviews
Spreadproduct,50-51
pagefooters
printing,565-570,558-563,570-571
pageheaders
printing,565-570,558-563,570-571
pagemargins
printing,558-563
pageorientation,564-565
pageranges
printing,550-552
pages
numberingprinted,558-563
printing,558-563
printingrangesof,550-552
painting
custom,114-115
customizing,114-115,116-117
palette
colorsinrich-textcell,374-378
panes,56,218-222
(seeviewports),218-222
PanesorViewports,57
parameters
count,437-440
customfunction,437-440
customfunctions,437-440
errorvalue,437-440
parents
hierarchy,463-469
inheritformatting,64
sheet,463-469
paretocharts,642-644
ParsingFormulasinCustomXMLDeserialization,544
parts
Spread Windows Forms Developer’s Guide 727
Copyright © GrapeCity, Inc. All rights reserved.
scrollbars,198-202
viewports,218-222
paste,677
pasting(SeeClipboardoperations),213-215
PDF,548-550
percent
celltype,335-337
performance
improving,488-491
PICmask,329-330
picture
imagecelltype,363-365
pictures
sheetcorner,131-132
PieCharts,602,584
pieplot,601
PiePlotTypes,601
pixels
scrolling,198-202
PlacingaFormulainCells,426-428
PlacingandRetrievingData,476
PlacingChildControlsonaSheet,225-226
PlotCollectionEditor,654-655
PlotTypes,584
PlotsandSeries,611-613
PointCharts,593-594,584
pointers,191-193
locating(HitTest),216-217
resizingroworcolumn,268-269
splitbars,218-222
pointers(Seecursors),113-114
polar,584
PolarAreaCharts,605-606
PolarLineCharts,604-605
PolarPlotTypes,602-603
PolarPointCharts,603-604
PolarStripeCharts,606
policy
merging,182-184
pop-upcalculator,388-390
notdisplaying,330-335
pop-upcalendar,386-388
pop-upclock,386-388
Spread Windows Forms Developer’s Guide 728
Copyright © GrapeCity, Inc. All rights reserved.
portraitorientation(printing),564-565
positioning
cell,224-225
horizontal,224-225
vertical,224-225
precedence
orderof,64
preferred
cellsize,170-171
columnwidth,145-146
height,145-146
rowheight,145-146
roworcolumnsize,145-146
width,145-146
preferredsize,170-171,145-146
PreventingaCellfromReceivingFocus,413
preview
control,578-579
printing,578-579
primarybuttons,399-400
PrintActions,527-528
printdialog,558-563
printpagecount,571-572,550-552
printing,571-572,547,550-552
abortdialog,558-563
automaticallydeterminingsettings,576,573-576
border,564-565
borders,558-563
canceling,558-563
cellnotes,556-557
cellranges,555-556,552-553,558-563,553-555
cellswithdata,558-563
centering,564-565
color,558-563
colors,564-565
columnheaders,558-563
columns,558-563
customizing,558-563
data,558-563
dialog,577,577
dialogs,558-563
fittingonpages,558-563
Spread Windows Forms Developer’s Guide 729
Copyright © GrapeCity, Inc. All rights reserved.
fittingtopages,576,573-576
footers,565-570,570-571
grid,564-565
gridlines,558-563
headers,565-570,570-571
hierarchy,550
introduction,547
jobname,558-563
justification,564-565
margins,564-565,558-563
namingjobs,558-563
numbering,558-563
orderofprintedpages,558-563
orientation,576,564-565,558-563,573-576
pagefooter,565-570,558-563,570-571
pageheader,565-570,558-563,570-571
pagemargins,558-563
pagenumbers,558-563
pageranges,558-563,550-552
PDFfile,548-550
preview,578-579
printdialog,558-563
printername,558-563
ranges,555-556,552-553,558-563,550-552,553-555
rowheaders,558-563
rows,558-563
scaling,576,558-563,573-576
sendingtotheprinter,547-548
shading,558-563
shadows,564-565
shapes,557-558
sheetborders,558-563
sheets,547-548
sizing,576,558-563,573-576
SmartPrint,576,573-576
specifyingprinteddata,555-556,576,552-553,550-552,553-555,573-576
specifyingtheprinter,558-563
watermark,572-573
whitespace,564-565
zoom,576,558-563,573-576
zooming,564-565
PrintingaChildViewofaHierarchicalDisplay,550
PrintingaRangeofCellsonaSheet,553-555
Spread Windows Forms Developer’s Guide 730
Copyright © GrapeCity, Inc. All rights reserved.
PrintingaSheetwithCellNotes,556-557
PrintingaSheetwithShapes,557-558
PrintinganAreaoftheSheet,555-556
PrintinganEntireSheet,547-548
PrintingandPDF,57
PrintingParticularPages,550-552
PrintingthePortionoftheSheetwithData,552-553
PrintingtoPDF,548-550
ProductOverview,50-51
Spread,50-51
ProductRequirements,25
progressindicator,372-374
gradient,372-374
project,28-30
protecting
cells,397-399
ProvidingaPreviewofthePrinting,578-579
QuickStartWizard,57
radar,584
RadarAreaCharts,609
RadarLineCharts,608-609
RadarPlotTypes,606-607
RadarPointCharts,607-608
RadarStripeCharts,609-610
radiobuttoncell(Seemultioptioncell),370-372
rangegrouping,300
ranges
cells,87-88
customname,436-437
filling,480-481
grouping,300
savingtoHTMLTableelement,532-533
sorting,58
sortingdata,307-309
ratio
tabstriptoscrollbarwidths,204-209
RearrangingDataonaSheet,485
recalculating
formulasautomatically,433-434
RecalculatingandUpdatingFormulasAutomatically,433-434
recalculationcycle,431-432
recalculations
Spread Windows Forms Developer’s Guide 731
Copyright © GrapeCity, Inc. All rights reserved.
suspending,488-491
recursing,431-432
redo,215-216
redo(undo)
overview,60
redrawing
suspending,488-491
reference,237-238,240
referencestyles
cells,428-430
sheets,430-431
references
circular,431-432
toacell,428-430
toasheet,430-431
regionalsettings(Windows),318-319
regularexpression
celltype,337-338
relocating
rows,columns,266-268
removing
cellspans,180-182
columns,78-79
data,487-488
headers(turningoff),84-86
rows,78-79
rows,columns,266-268
sheets,73-74
splitbars,218-222
RemovingaRoworColumn,78-79
RemovingaSheet,73-74
RemovingDatafromaSheet,487-488
renderer,107-111
renderers
celltypes,312-313
text,59-60
rendering
customizing,114-115
renderingtext,59-60
repainting
layout,488-491
suspending,488-491
repeat
Spread Windows Forms Developer’s Guide 732
Copyright © GrapeCity, Inc. All rights reserved.
fillingcells,480-481
RepeatedlyFillingaRangeofCellswithCopiedCells,480-481
RepeatingRowsorColumnsonPrintedPages,570-571
replacing
data,486-487
resetting
partsofcomponent,257,255-257
ResettingPartsoftheInterface,255-257
resize,171-172,231-232,688-689
resizeroworcolumncursor,268-269
resizing
allowinguser,268-269
cells,170-171
columns,268-269,145-146
includingheaders,145-146
rows,268-269,145-146
rowsandcolumns,268-269
ResizingaCelltoFittheData,170-171
ResizingaTable,231-232
ResizingtheDatatoFittheCell,171-172
ResizingtheRoworColumntoFittheData,145-146
restricting
columnentry,265-266
rowentry,265-266
resuming
layout,488-491
ReturningInformationforaClickedCell,413-414
richtext
format,374-378
celltype,374-378
rich-textcell
loadingRTFfile,374-378
rich-textcells
messagebox,374-378
RichTextBox
inrich-textcell,374-378
right-clickmenu,212-213
Right-To-LeftLayouts,57
right-to-leftsupport,116-117
rotation,620-621
rowheaders,81
automatictext,150-152
Spread Windows Forms Developer’s Guide 733
Copyright © GrapeCity, Inc. All rights reserved.
content,152-154
customtext,152-154
displaying,84-86
gridlines,157-160
height,160-161
hiding,84-86
multiple,55
multiplecolumns,81-84
printing,558-563
spans,161-163
style,154-156
text,150-152,152-154
rowheight
preferredsize,145-146
RowPreview,57
rows
adding,77-78
alternating,147-149
appearancesettings,143,75-76
customfilters,287
filtering,280,273-275
freezing,269-271
grouping,296-297,295,300
headers,81
height,143-145
hiding,79-80
leadingfrozen,269-271
moving,266-268
number,76-77
patterns,147-149
removing,266-268,78-79
resizing,268-269,145-146
restrictingentry,265-266
shortcutobject,143,61-64,75-76
sorting,58,307-309,307
stylesoffilteredrows,277-280
tags,251-252
trailingfrozen,269-271
RTFfile
rich-textcell,374-378
RTLsupport,116-117
rule
average,422-423
Spread Windows Forms Developer’s Guide 734
Copyright © GrapeCity, Inc. All rights reserved.
color,416-417
databar,417-419
highlight,419-421
icon,421-422
scale,416-417
top10,422-423
rules,415
save,647-648
inputmaps,520-521
saving,529
dataasXML,533-534
datatofile,529
PDFfile,548-550
skins,545
toExcelfile,530-531
toHTMLtable,529
toHTMLTableelement,532-533
toSpreadXMLfile,529-530
totextfile,531-532
toXML(rawdata),529
SavingaSkin,545
SavingandLoadingaSkin,544-545
SavingandLoadingMapFiles,520-521
SavingDatatoaFile,529
SavingorLoadingaChart,647-648
SavingSpreadsheetDatatoSimpleXML,533-534
SavingtoaSpreadXMLFile,529-530
SavingtoaTextFile,531-532
SavingtoanExcelFile,530-531
SavingtoanHTMLTable,532-533
scale
dpi,211-212
scaling
allowinguser,211
printing,564-565
scroll,689-690
scrollarrows,198-202
scrollbarshaft,198-202
scrollbars,198-202
events,198-202
horizontal,202-204
introduction,198-202
Spread Windows Forms Developer’s Guide 735
Copyright © GrapeCity, Inc. All rights reserved.
tips,202-204
tracking,198-202
using,198-202
vertical,202-204
scrollboxes,198-202
scrolltips,202-204
scrollableviewports,218-222
scrolling
scrollbars,198-202
scrolltips,202-204
smooth,198-202
search
cells,242-243
searchdialog
advancedoptions,242
standardoptions,241-242
searching,242-243
alternate,241-242
cells,242-243
includingcellnotes,242
includingcelltags,242
includingheaders,242
methods,242-243
withdialog,242,241-242
SearchingandSearchDialog,57
SearchingforDatawithCode,242-243
secondarybuttons,399-400
security
hostingcomponentonWebpage,213
SelectingActions,525-526
selection,690-692
Selectionmodel,89-91
selections
appearance,247-250
colors,247-250
customizing,247-250
hiding,251
indicator,247-250
operationmode,244-247
overview,243
using,243
semi-transparentlayer
selectioncolor,247-250
Spread Windows Forms Developer’s Guide 736
Copyright © GrapeCity, Inc. All rights reserved.
separators
currency,318-319
viewports,218-222
series,611-613
SeriesCollectionEditor,656
setting
activecell,86-87
activesheet,68-69
cellcolor,164-166
columnwidth,143-145
currencyminmax,385-386
richtextcell,374-378
rowheight,143-145
SettingaBackgroundImageforaSheet,119-120
SettingaBackgroundImagetoaCell,166-168
SettingaBarcodeCell,340-345
SettingaButtonCell,345-349
SettingaCheckBoxCell,349-352
SettingaColorPickerCell,352-356
SettingaComboBoxCell,356-359
SettingaCurrencyCell,318-319
SettingaDate-TimeCell,319-321
SettingaGcDateTimeCell,321-323
SettingaGcNumberCell,323-325
SettingaGcTextBoxCell,325-327
SettingaGeneralCell,327-329
SettingaHyperlinkCell,359-363
SettingaListBoxCell,365-367
SettingaMaskCell,329-330
SettingaMultipleOptionCell,370-372
SettingaMultiple-ColumnComboBoxCell,367-370
SettingaNumberCell,330-335
SettingaPercentCell,335-337
SettingaProgressIndicatorCell,372-374
SettingaRegularExpressionCell,337-338
SettingaRichTextCell,374-378
SettingaSliderCell,378-381
SettingaTextCell,338-339
SettinganImageCell,363-365
SettingandResettingUserInteraction,253
settingcelltype
barcode,340-345
Spread Windows Forms Developer’s Guide 737
Copyright © GrapeCity, Inc. All rights reserved.
button,345-349
checkbox,349-352
colorpicker,352-356
combobox,356-359,365-367,367-370
currency,318-319
datetime,319-321
double,330-335
general,327-329
hyperlink,359-363
image,363-365
mask,329-330
multipleoption,370-372
percent,335-337
progressindicator,372-374
regularexpression,337-338
slider,378-381
text,338-339
SettingFixed(Frozen)RowsorColumns,269-271
SettingTableStyles,233-236
SettingtheAppearanceofFilterIndicators,287
SettingtheAppearanceofFilteredRows,277-280
SettingtheAppearanceofGroupedRows,297-298
SettingtheAppearanceofSortIndicators,309-311
SettingtheAppearanceoftheDisplayoftheFilterItemList,285-287
SettingtheBackgroundColorsforaSheet,118-119
SettingtheCellTypesoftheRegister,46-48
SettingtheComponenttotheOriginalAppearance,101-103
SettingtheHeightorWidthofHeaderCells,160-161
SettingtheRowHeightorColumnWidth,143-145
SettingupConditionalFormattingofaCell,423-426
SettingupPreviewRows,271-273
SettinguptheFormulaProvider,442-443
SettinguptheFormulaTextBox,440-442
SettinguptheNameBox,443-445
SettingUptheRowsandColumnsoftheRegister,44-46
settings
appearance,101,68
Clipboardoptions,213-215
composite,64
shadows
printing,564-565
shape,692
camera,262-264,52-53
Spread Windows Forms Developer’s Guide 738
Copyright © GrapeCity, Inc. All rights reserved.
ShapeActions,527
shapes,495-501,614-615
adding,258-260
feature,57-58
floatingobjects,257-258
overview,257-258
printing,557-558
Shapes,Drawings,andAnnotations(FreehandDrawing),57-58
sheetcorner,131-132
sheetindex
zero-basedinExcel,535-536
sheetnametabs,204-209
sheetnames
tabstrip,204-209
sheetskins(Seeskins),545,128-129
sheettab
custompainting,114-115,116-117
sheettabs,204-209
custompainting,114-115
Sheet-LevelActions,526-527
sheets
activesheet,68-69
adding,70-71
Annotationmode,260-261
appearancesettings,117,68
childviews,463-469
colors,118-119
controlon,225-226
copying,71-72
copyingtoanothercomponent,69-70
corner,131-132
filtering,280
findingbyname,69-70
headers,81
hiding,74-75
moving,72-73
multiple,56,69-70
names,204-209
printing,547-548
printingborders,558-563
referencestyle,430-431
removing,73-74
Spread Windows Forms Developer’s Guide 739
Copyright © GrapeCity, Inc. All rights reserved.
shortcutobject,117,61-64,68
skins,128-129,129-131
stylesoffilteredrows,277-280
tabstrip,204-209
tabs,204-209
tags,251
templates,128-129,129-131
shortcutkeys
Clipboardoperations,213-215
shortcutobjects,61-64
cell,163-164,61-64,86
column,143,61-64,75-76
header,81,61-64
row,143,61-64,75-76
sheet,117,61-64,68
ShowingorHidingaRoworColumn,79-80
ShowingorHidingaSheet,74-75
ShowingorHidingFilterIndicators,289
ShowingorHidingHeaders,84-86
ShrinkToFit,171-172
size,623-624
cells,170-171
determiningbest,170-171
headers,160-161
ofroworcolumn,145-146
Size-Height,Width,andDepth,623-624
sizing
cellnoteindicator,410-413
skins,58-59,128-129
applying,128-129
creating,129-131
custom,58-59
defined,128-129
editor,129-131
files,544-545
loading,545-546
predefined,58-59
saving,545
SheetSkinEditor,128-129,129-131
SheetSkinEditorverb,128-129
spreadsheet,128-129,129-131
SkinsandStylesforCustomizedAppearance,58-59
slidercontrol,378-381
Spread Windows Forms Developer’s Guide 740
Copyright © GrapeCity, Inc. All rights reserved.
smartclient,213
SmartPrintfeature,576,573-576
smoothscrolling,198-202
sort,232-233,692-693
sortindicators,305-307
hiding,309-311
rowlocation,309-311
sorting,58,304-305
affectondatamodels,304-305
celltypes,304-305
columnsautomatically,307
datainrange,307-309
grouping,296-297
hidingindicators,309-311
inSpreadDesigner,307-309
indicatorrow,309-311
indicators,309-311,209-211
introduction,304-305
rowsautomatically,307
rowsorcolumns,307-309
SortingaTable,232-233
SortingRowsorColumns,58
SortingRows,Columns,orRanges,307-309
spacing
betweengroupnames,298-299
spanmodel,89-91
SpannableCells,58
spanning
cells,180-182,58
headercells,161-163
spans
adding,180-182
columnheaders,161-163
headercells,161-163
removing,180-182
rowheaders,161-163
sparkline,58
add,189-191
graph,189
grouping,194-197
horizontalaxis,193-194
switch,194-197
Spread Windows Forms Developer’s Guide 741
Copyright © GrapeCity, Inc. All rights reserved.
ungroup,194-197
verticalaxis,193-194
Sparklines,58
SpecifyingaCellReferenceinaFormula,428-430
SpecifyingaSheetReferenceinaFormula,430-431
SpecifyingHorizontalandVerticalAxes,193-194
SpecifyingWhattheUserCanSelect,244-247
SpecifyingWhattoPrint,547
spinbuttons,382-383
splitbars,56,218-222
events,218-222
removing,218-222
splitboxes,222-224
alignment,222-224
display,222-224
parts,222-224
using,218-222
splitdisplay,56
splitpointer,218-222
Spread
skins,129-131
SpreadDesigner,58
overview,58
StartingtheSpreadWizard,40
Step1:AddingSpreadtoaDataBindingProject,471
Step2:SettinguptheDatabaseConnection,471-472
Step3:SpecifyingtheDatatoUse,472-473
Step4:CreatingtheDataSet,473-474
Step5:BindingSpreadtotheDatabase,474
Step6:ImprovingtheDisplaybyChangingtheCellType,474-475
sticky,410-413
StripeCharts,594-595,584
structured,240
style,233-236
stylemodel,89-91
styles,58-59
cellborders,172-176
filteredrows,277-280
fontinrich-textcell,374-378
forcells,186-189
headers,154-156
named,186-189
sheetcorner,131-132
Spread Windows Forms Developer’s Guide 742
Copyright © GrapeCity, Inc. All rights reserved.
sheettabstrip,204-209
XPthemesoverview,60
subeditors,390-391,217-218
subregion
forcursorcustomization,113-114
surfacecharts,584
suspending
layout,488-491
swapping
data,486-487
SwappingDataonaSheet,486-487
symbols
currency,318-319
decimal,318-319
tab,693
tabstrip,204-209
appearance,204-209
buttons,204-209
cursors,204-209
custompainting,114-115,116-117
display,204-209
placement,204-209
width,204-209
TabStripandSheetNameTabs,59
table,240,227-228,228-231,231-232,232-233,233-236,226-227,236-237
TableDisplayintheSheetCorner,136-137
Tables,59
tabletPCinking,261-262
TabletPCsupport
overview,56
tabs
sheetnames,204-209
tags,252-253,251-252,251
incells,252-253
incolumns,251-252
inrows,251-252
insheets,251
includinginsearch,242
template
skinas,129-131
templates
cells,186-189
Spread Windows Forms Developer’s Guide 743
Copyright © GrapeCity, Inc. All rights reserved.
sheets,544-545
skins,544-545
styles,186-189
text
automaticcompletionincombobox,356-359
celltype,338-339
columnheaders,150-152,152-154
rowheaders,150-152,152-154
searching,242-243
textcell(seegeneralcelltype),327-329
textcolor
setting,164-166
TextDisplayintheSheetCorner,135-136
TextProperty
inFpSpreadcontrol,217
textrenderer,59-60
TextRenderingwithGDI,59-60
texttips,408-410
appearance,408-410
scrolltips,202-204
TextChangedEvent
inFpSpreadcontrol,217
TextRendererassembly,59-60
TextRendererclass,59-60
theme
skinas,129-131
thinclient,213
tick,378-381
times
pop-upclock,386-388
tips
texttips,408-410
TitleandSubTitle,60
tooltips
cell,408-410
toolbars
floatingtoolbar,440-442
tooltip,674-676
Top,Bottom,orAverageRules,422-423
TouchSupport,60,672
track,378-381
tracking
scrollbars,198-202
Spread Windows Forms Developer’s Guide 744
Copyright © GrapeCity, Inc. All rights reserved.
trailing
frozenrowsorcolumns,269-271
transparency
imagecell,363-365
transparent
image,363-365
trusted
hostingcomponentonWebpage,213
Tutorial:BindingtoaCorporateDatabase(OlderVisualStudio),471
Tutorial:CreatingaCheckbookRegister,43-44
tutorials
databinding,471
typeahead,390
unboundrows
adding,455-456,458-459,456-458
UnderlyingKeystrokeProcessing,492-493
UnderlyingModels,67
UnderstandingAdditionalFeaturesofCellTypes,381-382
UnderstandingCellTypeBasics,312-313
UnderstandingCharts,580
UnderstandingEditModeinaCell,396-397
UnderstandingEnhancedRowFiltering,290-293
UnderstandingHeaders,81
UnderstandingHowCellTypeAffectsModelData,316-317
UnderstandingHowCellTypesDisplayandFormatData,313-316
UnderstandingHowCellTypesWork,312
UnderstandingPartsoftheComponent,32
UnderstandingSimpleRowFiltering,276-277
UnderstandingStructuredReferenceSyntaxRules,239-240
UnderstandingStructuredReferences,237-238
UnderstandingtheAxisModel,93-94
UnderstandingtheDataModel,92-93
UnderstandingtheOptionalInterfaces,99-100
UnderstandingthePrintingOptions,558-563
UnderstandingtheProduct,50
UnderstandingtheSelectionModel,94-95
UnderstandingtheSheetModelClassesandInterfaces,89-91
UnderstandingtheSpanModel,95
UnderstandingtheSpreadWizard,39-40
UnderstandingtheSpreadsheetObjects,68
UnderstandingtheStyleModel,95-98
UnderstandingtheTypesofSheetModels,89
Spread Windows Forms Developer’s Guide 745
Copyright © GrapeCity, Inc. All rights reserved.
UnderstandingtheUnderlyingModels,89
UnderstandingTouchGestures,672
UnderstandingTouchMessages,672
UnderstandingTouchSupport,672
undo,215-216
overview,60
UndoandRedoActions,60
updating
formulasautomatically,433-434
userdialog
abortprinting,577
displaying,576-577
printpreview,578-579
printing,577
userentry
validation,481-485
userselection,244-247
user-defined
functions,437-440
names,436-437
UsingaBoundDataSource,644-646
UsingaCircularReferenceinaFormula,431-432
UsingaTouchKeyboard,673-674
UsinganOutline(RangeGroup)ofRowsorColumns,300-302
UsinganUnBoundDataSource,646
UsingApplicationTags,251
UsingAutomaticSorting,307
UsingConditionalFormattingofCells,415
UsingCustomFilterIndicatorImages,287-289
UsingDragOperationstoFillCells,403
UsingEditModeandFocus,396
UsingGrouping,296-297
UsingInputMapswithActionMaps,511-515
UsingOperatorsandSpecialItems,238-239
UsingRawandRepresentedData,646-647
UsingSatelliteAssembliesforLanguages,26
UsingSerialization,538
UsingSmartTagsDrop-Down,32-34
UsingSparklines,189
UsingStructuredReferences,240
UsingTableFilters,228-231
UsingtheAdditionalSpreadControls,440
UsingtheChartControl,657
Spread Windows Forms Developer’s Guide 746
Copyright © GrapeCity, Inc. All rights reserved.
UsingtheChartDesigner,648-649,666-667
UsingtheExcelCompatibilityInputMaps,520
UsingtheSpreadWizard,40-41
UsingtheTouchMenuBar,674-676
UsingTouchSupport,672-673
UsingTouchSupportwhenMovingColumnsorRows,686-688
UsingTouchSupportwhenResizingColumnsorRows,688-689
UsingTouchSupportwhenSorting,692-693
UsingTouchSupportwithAutoFit,676
UsingTouchSupportwithCellNotes,676
UsingTouchSupportwithCharts,676-677
UsingTouchSupportwithClipboardOperations,677
UsingTouchSupportwithDragandFill,677-679
UsingTouchSupportwithDrop-DownElements,679-680
UsingTouchSupportwithEditableCells,680-681
UsingTouchSupportwithFiltering,684
UsingTouchSupportwithGrouping,684-685
UsingTouchSupportwithInputManCells,681-684
UsingTouchSupportwithRangeGrouping,685-686
UsingTouchSupportwithScrolling,689-690
UsingTouchSupportwithSelections,690-692
UsingTouchSupportwithShapes,692
UsingTouchSupportwiththeComponent,672
UsingTouchSupportwiththeTabStrip,693
UsingTouchSupportwithViewports,693
UsingTouchSupportwithZooming,693-694
UsingVerbsinthePropertiesWindow,34-36
UsingVisibleIndicatorsintheCell,408
UsingWindowsRegionalSettingsorOptions,25-26
UsingXPThemeswiththeComponent,115-116
validating
userinput,481-485
ValidatingUserInput,481-485
validation,481-485
celltypes,481-485
event-based,481-485
IsValidmethod,481-485
userinput,481-485
verbs
SheetSkins,128-129
vertical
alignment,168-170
Spread Windows Forms Developer’s Guide 747
Copyright © GrapeCity, Inc. All rights reserved.
indent,betweengroupnames,298-299
scrollbars,202-204
viewport,693
viewports,56
columns,218-222
events,218-222
parts,218-222
rows,218-222
separator,218-222
setting,218-222
splitboxes,222-224
views
hierarchy,463-469
panes,56
zooming,211
visible
rowsorcolumns,79-80
visualstyles,115-116
overview,60
VisualStylesforXPThemes,60
Walls,613-614
watermark
whenprinting,572-573
Webpage
hostingthecomponent,213
Webpages
usercontrolon,213
WhenAncestorOfFocused,inmapping,493-495
WhenFocused,inmapping,493-495
whitespace(printing),564-565
width
columns,143-145
headercolumn,160-161
sheettabstrip,204-209
widthdeterminingbest,145-146
wildcards
insearch,241-242
Windowsregionalsettings,318-319
WorkingwithaSubEditor,390-391
WorkingwithAnnotations,260-261
WorkingwithCells,86
WorkingwithCollectionEditors,36-37
WorkingwithEditableCellTypes,317-318
Spread Windows Forms Developer’s Guide 748
Copyright © GrapeCity, Inc. All rights reserved.
WorkingwithGraphicalCellTypes,339-340
WorkingwithHeaders,80-81
WorkingwithHierarchicalDataDisplay,463-469
WorkingwithMultipleSheets,69-70
WorkingwithSelections,250-251
WorkingwithShapesinCode,258-260
WorkingwithSheets,68
WorkingwithSparklines,194-197
WorkingwiththeActiveCell,86-87
WorkingwiththeActiveSheet,68-69
WorkingwiththeChartControl,580
WorkingwiththeComponent,26
WorkingwiththeRowsandColumns,75-76
XLSXformat
opening,535-536
XML
savingdatato,533-534
savingrawdata,529
XPthemes,115-116
overview,60
XYBubbleCharts,595-596
XYLineCharts,596
XYPlotTypes,595
XYPointCharts,596-597
XYStripeCharts,597
XYZLineCharts,599-600
XYZPlotTypes,597-598
XYZPointCharts,598-599
XYZStripeCharts,601
XYZSurfaceCharts,600-601
YPlotTypes,584-585
zoom,693-694
zooming
allowinguser,211
printing,564-565
Spread Windows Forms Developer’s Guide 749
Copyright © GrapeCity, Inc. All rights reserved.