r.a.d.grid v3

158
Thank you for choosing telerik r.a.d.grid ! telerik r.a.d. grid is designed to eliminate the typical tradeoff associated with ASP.NET grid controls - rich functionality at the expense of weight and performance. Thanks to its innovative architecture r.a.d.grid is extremely fast and generates very little output. Added to this is true cross browser support - Internet Explorer, all Gecko-based browsers, and Opera. At the same time telerik r.a.d.grid delivers top-of-the line features like: rich client-side API, Outlook-style grouping with expressions, multi-column sorting, column and row resizing, column reordering, paging, hierarchical structures with more than one tables, preservation of state after postback etc. r.a.d. grid is available individually or as part of the telerik r.a.d.controls suite (http://www.telerik.com/radcontrols) - "Unleashing the power of Thin Client™". This document contains information about the following: l What's new in r.a.d.grid v3.0 (Section 1) l General Features (Section 2) l Standards Compliance (Accessibility and XHTML) (Section 3.1) l Installation and Deployment (Section 5.1) l r.a.d.grid Overview (Section 6.1) l Defining r.a.d.grid Structure (Section 7.2.1) l r.a.d.grid Client-Side (Section 12.1) l r.a.d.grid Server-Side (Section 13.7) l Troubleshooting (Section 15.1) r.a.d.grid v3.0 If you need further assistance, please contact [email protected] Revised: February 09, 2006 r.a.d.grid v3.0 | 1 © 2002-2006, telerik. All Rights Reserved.

Upload: others

Post on 20-Jan-2022

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: r.a.d.grid v3

Thank you for choosing telerik r.a.d.grid !

telerik r.a.d.grid is designed to eliminate the typical tradeoff associated with ASP.NET grid controls - rich functionality at the expense of weight and performance. Thanks to its innovative architecture r.a.d.grid is extremely fast and generates very little output. Added to this is true cross browser support - Internet Explorer, all Gecko-based browsers, and Opera.

At the same time telerik r.a.d.grid delivers top-of-the line features like: rich client-side API, Outlook-style grouping with expressions, multi-column sorting, column and row resizing, column reordering, paging, hierarchical structures with more than one tables, preservation of state after postback etc.

r.a.d.grid is available individually or as part of the telerik r.a.d.controls suite (http://www.telerik.com/radcontrols) - "Unleashing the power of Thin Client™".

This document contains information about the following:

l What's new in r.a.d.grid v3.0 (Section 1)

l General Features (Section 2)

l Standards Compliance (Accessibility and XHTML) (Section 3.1)

l Installation and Deployment (Section 5.1)

l r.a.d.grid Overview (Section 6.1)

l Defining r.a.d.grid Structure (Section 7.2.1)

l r.a.d.grid Client-Side (Section 12.1)

l r.a.d.grid Server-Side (Section 13.7)

l Troubleshooting (Section 15.1)

r.a.d.grid v3.0

If you need further assistance, please contact [email protected] Revised: February 09, 2006

r.a.d.grid v3.0 | 1

© 2002-2006, telerik. All Rights Reserved.

Page 2: r.a.d.grid v3

Table Of Contents

1. What's New 6-11

2. General Features 12-16

3. Standards Compliance 17

3.1. Accessibility Compliance 17-18

3.2. XHTML Compliance 18

4. Changes And Backward Compatibility 19

5. Installation and Deployment 20

5.1. System Requirements 20

5.2. Installing r.a.d.grid From EXE File 20

5.3. Installing r.a.d.grid From ZIP File 21

5.4. Deploying r.a.d.grid Into ASP.NET Applications 21

5.4.1. Adding r.a.d.grid to the Visual Studio Toolbox 21-22

5.4.2. Adding r.a.d.grid to an ASP.NET WebForm 22-23

5.4.3. Adding r.a.d.grid to the Global Assembly Cache 23-24

5.4.4. Caching Client-Side Scripts 24

5.4.5. Relocating the RadControls Folder 24-25

5.4.6. Using Visual Studio .Net IntelliSense 25-27

5.4.7. Using IntelliSense in Visual Studio 2005 27

5.5. Licensing 27

5.5.1. Setting Trial License Keys 27-28

5.5.2. License Agreement 28-33

5.6. Upgrading Instructions 33

5.6.1. Trial License v2.x to Developer License v3.0 33-34

5.6.2. Developer License v2.x to Developer License v3.0 34

5.6.3. Trial License v3.0 to Developer License v3.0 34-35

6. r.a.d.grid Overview 36

6.1. Grid Elements 36-43

6.2. Columns 43

6.2.1. Column Types 43-49

6.2.2. Using Columns 49-51

6.3. Rows 51-54

6.4. Most Important Properties 54

6.5. Most Important Events 54-55

r.a.d.grid v3.0 | 2

© 2002-2006, telerik. All Rights Reserved.

Page 3: r.a.d.grid v3

7. Defining r.a.d.grid Structure 57

7.1. Defining r.a.d.grid in ASPX 57-58

7.2. Data Binding 58

7.2.1. Data Binding 58-60

7.2.2. DataGrid Like Binding 60-61

7.2.3. Using NeedDataSource Event 61-62

7.3. Hierarchical Grid 62

7.3.1. Hierarchical Views 62-64

7.3.2. Creating Hierarchical Grid Dynamically 64-68

7.3.3. Binding Hierarchical Grids 68-71

7.3.4. Examples For Detail Table Binding 71-73

7.3.5. Bind Programmatically To Hierarchical XML Data 73-75

7.3.6. Declarative Data Binding for Hierarchical Structures 75-81

8. Performing Insert/Update/Delete 82

8.1. Automatic Insert/Update/Delete in r.a.d.grid 82-84

8.2. API For Controlling the Automatic Operations 84-85

8.3. Error Handling 85-86

8.4. Data Editing Support 87-89

8.5. API For Controlling Insert Operation 89-90

8.6. Customizing Edit Forms 90-91

8.7. Editors In Grid Columns 91-93

8.8. Web User Controls In Edit Forms 93-96

8.9. Switching the Insert/Updade/ Regular Modes 96-97

9. Design-time Support 98

9.1. Overview 98-99

9.2. Setting RadGrid 99-100

9.3. Paging 101-102

9.4. Style Manager 102-103

9.5. Borders 103-104

9.6. Table Related Properties 104

9.6.1. Columns 104-105

9.7. Creating Hierarchical Grids 105-107

10. Customizing Appearance 109

10.1. Skins 109-110

r.a.d.grid v3.0 | 3

© 2002-2006, telerik. All Rights Reserved.

Page 4: r.a.d.grid v3

10.2. Customizing AutoGenerated Columns 110-111

10.3. Conditional Formatting 111-112

10.4. Customizations related to Hierarchy 113

11. AJAX in r.a.d.grid 114

11.1. AJAX in r.a.d.grid 114-115

11.2. Using AJAX mechanism outside of the grid 115-116

11.3. Redirecting with AJAX 116

11.4. Virtual Scrolling/Paging 116

12. r.a.d.grid Client-Side 118

12.1. Client-Side Object Model 118

12.2. Client-Side JavaScript Events 118-120

12.3. RadGridTable client-side API 120-121

12.4. Resizing 121-123

12.5. Scrolling 123-124

12.6. Selecting 124-125

12.7. Performing Postback With Client-Side Events 125-126

13. r.a.d.grid Server-Side 128

13.1. Accessing Columns 128

13.2. Accessing Cells And Rows 128-129

13.3. Grouping 129-134

13.4. Sorting 134-136

13.5. Paging 136-139

13.6. Filtering 139-140

13.7. Hierarchy Load 140-142

13.8. Optimizing Performance 142

13.9. Saving r.a.d.grid Settings On a Per User Basis 142-146

13.10. Event Bubbling in r.a.d.grid 146-147

13.11. Raising Postback From User Control 147-148

14. Interoperability with Other Controls 149

14.1. Interoperability of r.a.d.grid with r.a.d.callback 149-150

14.2. VAM Validators 150

14.2.1. Overview 151

14.2.2. Setup Your Web Site 151-152

14.2.3. Adding the Control to the Page 152-153

r.a.d.grid v3.0 | 4

© 2002-2006, telerik. All Rights Reserved.

Page 5: r.a.d.grid v3

15. Troubleshooting 154

15.1. Most Common Mistakes 154-157

16. Ask Technical Questions 158

r.a.d.grid v3.0 | 5

© 2002-2006, telerik. All Rights Reserved.

Page 6: r.a.d.grid v3

New in r.a.d.grid v3.01. Full support for ASP.NET 2.0 - r.a.d.grid is now available in two editions - one for .NET 1.x and a

mirror one complied against the .NET 2.0 to offer specific features for Microsoft's next-generation IDE - Visual Studio .NET 2005.

2. AJAX support for controls inside r.a.d.grid (Section 11.1) - All standard ASP.NET controls in grid cells that normally perform postbacks will now use the r.a.d.grid AJAX mechanism automatically. Furthermore the AJAX support for third-party controls has been significantly improved. As a result, the developers can enjoy the performance AJAX technology by merely setting a single property EnableAsyncRequests to true.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/AJAX/ThirdParty/DefaultCS.aspx)

3. Improved API for updating (Section 8.4) the GridTableView - the ExtractValuesFromItemmethod will collect all field/value pairs that can be used to perform updates. This allows you to develop your application in a way similar to the update mechanism in ASP.NET 2.0, while saving dozens of extra code.

4. Extracting values from TemplateColumns (Section 8.4) - r.a.d.grid can extract the values from a template column even under ASP.NET 1.x using the declarative DataBindingsDescrptioncollection

5. Built-in support for inserting new records - you can set r.a.d.grid to insert new records entirely in a declarative way. Yet when you need greater customization you can still have programmatic control over the behavior of this feature.

6. Ability to set the default values for Item prior insertion - r.a.d.grid allows you with just few lines of code set predefined values for specific Item input controls (e.g. dropdown list) prior to Item insertion. This lets you declaratively bind such input controls and later use their values when performing automatic updates.

7. Filtering (Section 13.6) - r.a.d.grid can now perform filtering operations for all columns that support filtering GridBoundColumn, GridCheckBoxColumn, etc. For each column there will be a dropdown menu with the available filter expressions.r.a.d.grid can automatically determine the expression set applicable for each column based on the data type of the field. Each column data type is automatically stored by r.a.d.grid during data binding in the DataType property.

1 What's New

r.a.d.grid v3.0 | 6

© 2002-2006, telerik. All Rights Reserved.

Page 7: r.a.d.grid v3

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/GeneralFeatures/Filtering/DefaultCS.aspx)

8. Virtual Scrolling/Paging with AJAX (Section 11.4) - hold the Shift key and use the grid scrollbar to virtually change the grid pages. r.a.d.grid will perform an AJAX request and silently change the page to the one set with the virtual scrollbar.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/AJAX/VirtualScrollPaging/DefaultCS.aspx)

9. Scrolling with static headers (Section 12.5) and 100% grid size - without the browser scrollbars and with only r.a.d.grid scrollbars visible plus static headers, r.a.d.grid will mimic a Microsoft Excel ® application.

10. Keep in edit/insert mode - you can set r.a.d.grid to stay in edit/insert mode after update by setting the KeepInEditMode/KeepInInsertMode property.

11. Declarative support for custom editors (Section 8.7) - you can now add custom column editors to the WebForm. Then you can declaratively set a column to use these editors. Using this mechanism gives you a great flexibility and very easy customization of the edit forms.

12. Significantly Improved Design-time support and property builder (Section 9.1) - now you can define hierarchical grids using the enhanced property builder in Visual Studio.Net.

r.a.d.grid v3.0 | 7

© 2002-2006, telerik. All Rights Reserved.

Page 8: r.a.d.grid v3

13. Loading template (Section 7.2.1) - when r.a.d.grid is working in AJAX mode, it can display a template during asynchronous operations. You can use the default template or set your own where you can even use rich media like flash objects for example.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/AJAX/LoadingTemplate/DefaultCS.aspx)

14. Support for images in button columns (Section 6.2.1) - GridButtonColumn and GridEditCommandColumn now support ImageButtons - intuitive default images are now included for edit, update, insert, cancel, add new record, refresh and other, that can much improve the user experience.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/DataEditing/ExtractValues/DefaultCS.aspx)

r.a.d.grid v3.0 | 8

© 2002-2006, telerik. All Rights Reserved.

Page 9: r.a.d.grid v3

15. New Command Row (Section 6.1) - GridCommandItem can be used to add function buttons in the content area of RadGrid, such as [Add New Record], [Refresh], [Delete Selected], etc.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/Programming/CommandItem/DefaultCS.aspx)

16. Pager with templates and command API (Section 13.5) - the Pager item now can use templates. All command buttons in the template can take advantage of the paging command API, the PagerItem.Paging properties using binding expressions. This allows highest level of customization of the Pager item and even using custom logic for defining the appearance.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/Programming/PagerTemplate/DefaultCS.aspx)

New in r.a.d.grid v2.01. XHTML Compliance (Section 3.2) - r.a.d.grid now provides complete XHTML compliance. The

HTML markup of the component is fully XHTML 1.1 compliant.

2. Accessibility Compliance (Section 3.1) - r.a.d.grid is now "Level A" content compliant (in accordance with the W3C Web Accessibility Guidelines 1.0).

3. Asynchronous (AJAX) Requests (Section 11.1) - r.a.d.grid can now make Asynchronous JavaScript with XMLHttpRequests (AJAX). This dramatically improves the responsiveness of the component, simulates Windows-application like behavior, and minimizes the traffic to the server.To enable AJAX callback requests you need to set a single property (EnableAsyncRequests) to true. This will make all Button, ImageButton, LinkButton controls, as well as any custom controls within r.a.d.grid to make AJAX callbacks instead of postbacks.

4. Client-side expand/collapse and mixed expand/collapse in hierarchical mode (Section 13.7) - r.a.d.grid now allows you to expand hierarchical tables client-side for better user experience. Moreover, you can specify the expand/collapse mode (client- or server-side) for each individual table, i.e. client-side for first level and server-side second level.

5. Client-side expand/collapse in group-by mode (Section 13.3) - similarly to the hierarchical

r.a.d.grid v3.0 | 9

© 2002-2006, telerik. All Rights Reserved.

Page 10: r.a.d.grid v3

mode, r.a.d.grid can expand/collapse grouped items entirely client-side, eliminating the time-consuming postbacks for this common operation.

6. Edit Forms Spanning Across Multiple Columns (Section 8.6) - r.a.d.grid allows you to set the number of vertical columns, across which an autogenerated edit form will span.

7. UserControls as Edit Forms (Section 8.8) - r.a.d.grid supports different edit forms for management of item content. You can switch the type of the edit forms using the GridEditFormType Enumeration. In the example above the edit form is a WebUserControl specified by the UserControlName Property.

8. Templates as Edit Forms - similarly to using UserControls as Edit Forms, you can now display templates as Edit Forms.

9. Conditional Formatting (Section 10.3) - r.a.d.grid now enables you to apply conditional formatting to grid elements for enhanced readability and usability of the displayed data.

r.a.d.grid v3.0 | 10

© 2002-2006, telerik. All Rights Reserved.

Page 11: r.a.d.grid v3

10. Columns Collection Persistence (Section 7.3.3) - r.a.d.grid saves the structure of the columns for each [detail] table view in the ViewState.

r.a.d.grid v3.0 | 11

© 2002-2006, telerik. All Rights Reserved.

Page 12: r.a.d.grid v3

Click to enlarge

1. Cross-Browser Support (Section 5.1) - r.a.d.grid supports the full set of features on most popular browsers like Internet Explorer, Gecko-based browsers (Mozilla, Firefox, Netscape), and Opera.

2. Hierarchical Structure of Tables (Section 7.3.1) - r.a.d.grid allows presentation of related DataSets as hierarchical structures of tables. Unique: You can even have more than one table in the same level of hierarchy.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/Hierarchy/ThreeLevel/DefaultCS.aspx)

3. Grouping (Section 13.3) - you can easily implement multilevel Outlook-style grouping of data from a single table - just drag the column header(s) to the group panel on the top, which defines the groping order and hierarchy. You can also programmatically group the data using the group-by expressions. Unique: when using grouped data, you can have grouping by two columns and at the same time use all sorting features of r.a.d.grid (e.g. group by one/two column(s) and sort by another column).

2 General Features

r.a.d.grid v3.0 | 12

© 2002-2006, telerik. All Rights Reserved.

Page 13: r.a.d.grid v3

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/GroupBy/OutlookStyle/DefaultCS.aspx)

4. Multi-Column Sorting (Section 13.4) - in addition to the simple one-column sorting r.a.d.grid allows you to sort data by several columns just like in Microsoft Excel.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/GeneralFeatures/Sorting/DefaultCS.aspx)

5. Viewstate Optimization - you can tune the grid performance by controlling the trade-off between client-side load and speed. When working with hierarchical data, you can choose one of the three available modes for loading the detail tables: - ServerBind - optimum server load, viewstate and render size. - ServerOnDemand - minimum viewstate and render-size, maximum server load. - Client - minimum server load, maximum viewstate and render-size. Rich client browser functionality.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/Programming/ViewState/DefaultCS.aspx)

6. Preserving the Grid State After Postback - an unique feature of telerik r.a.d.grid is the ability to preserve its appearance, group-by state, sorting, current page, edit or selected state, and resizing after postbacks with minimum resource usage. This significantly improves the usability of the component.

7. Easy Migration from DataGrid to r.a.d.grid - the declarative syntax of r.a.d.grid is quite similar to that of the DataGrid control, which makes the migration a pretty straightforward task.

r.a.d.grid v3.0 | 13

© 2002-2006, telerik. All Rights Reserved.

Page 14: r.a.d.grid v3

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/GeneralFeatures/Migration/DefaultCS.aspx)

8. Rich Set of Column Types (Section 6.2.1) - r.a.d.grid supports all widely used column types (EditCommand, Bound, CheckBox, Dropdown, PushButton, LinkbButton, HyperLink, ) as well as Templated columns, which give you complete freedom over the data layout and formatting.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/GeneralFeatures/ColumnTypes/DefaultCS.aspx)

9. Paging (Section 13.5) - r.a.d.grid natively supports table paging, which enables users to view the data in small chunks for faster loading and easier navigation.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/GeneralFeatures/Paging/DefaultCS.aspx)

10. Column and Row Resizing (Section 12.4) - r.a.d.grid supports convenient client-side column and row resizing with features like: - real-time resizing - resizing of the grid on column resizing - clipping of the cell content on column resizing

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/Client/Resizing/DefaultCS.aspx)

11. Column Reordering with Drag-and-Drop - telerik r.a.d.grid allows users to quickly reorder the columns by simply drag-and-dropping their headers.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/Client/ColumnsReorder/DefaultCS.aspx)

12. Scrolling (Section 12.5) - r.a.d.grid enhances the simple scrolling by supporting static headers -you can scroll the grid data, while the header row always stays visible at the top.

r.a.d.grid v3.0 | 14

© 2002-2006, telerik. All Rights Reserved.

Page 15: r.a.d.grid v3

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/Client/Scrolling/DefaultCS.aspx)

13. Multi-Row Selection and Area Selection (Section 12.6) - You can easily select multiple rows using Ctrl + Click or by simply dragging a range over the rows, which you want to select.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/Programming/WebMail/DefaultCS.aspx)

14. Design-Time Support (Section 9.1) - r.a.d.grid has full support for the design mode of Visual Studio .NET. This allows you to build, customize, and populate the grid in a convenient WYSIWYG environment.

15. Extensive Client-side API ('Overview' in the on-line documentation) - r.a.d.grid introduces a comprehensive client-side API, which enables you to resize, move, reorder, select, scroll columns on-the-fly and much more.

16. Exporting - you can easily export the content to Microsoft Excel and Microsoft Word.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/GeneralFeatures/Exporting/DefaultCS.aspx)

17. Flexible Editing Functionality - in line - edit controls appear within the edited row.

r.a.d.grid v3.0 | 15

© 2002-2006, telerik. All Rights Reserved.

Page 16: r.a.d.grid v3

- in forms - the grid generates a form for entering the row data.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/DataEditing/EditModes/DefaultCS.aspx)

18. Custom Editor Support (Section 8.7) - Editable columns in r.a.d.grid (Bound column, Dropdown column, CheckBox column) allow you to replace their default editor with custom ones with enhanced functionality like validation, rich-text editing, etc. Once you have created the custom editors, you can then easily re-use them for other grid implementations.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/DataEditing/UserControlEditForm/DefaultCS.aspx)

19. Appearance Customization (Section 10.1) - the appearance of all grid elements is fully customizable using skins. If you have a hierarchical grid, you can set a single skin for the whole grid, or customize each DetailTable separately.

See a live example at www.telerik.com (http://www.telerik.com/r.a.d.controls/Grid/Examples/Hierarchy/ThreeLevel/DefaultCS.aspx)

r.a.d.grid v3.0 | 16

© 2002-2006, telerik. All Rights Reserved.

Page 17: r.a.d.grid v3

Compliance Levelr.a.d.grid is "Level A" content compliant (in accordance with the W3C Web Accessibility Guidelines 1.0).

3.1.1 Accessibility features for grid images: l 'alt' attribute for all images (applies only for images as a part of the grid content. Alt attribute for the

r.a.d.grid control images (sort images, expand images) is not available for setting) - For user agents that cannot display images, this attribute specifies alternate text.

3.1.2 Accessibility features for GridTableView:l 'summary' attribute - GridTableView.Summary - It sets the 'summary' attribute for the respective

table. This attribute provides a summary of the table's purpose and structure for user agents rendering to non-visual media such as speech and Braille.

l <caption> tag - GridTableView.Caption - It sets the <caption> tag for the current <table>.

Visual user agents allow sighted people to quickly grasp the structure of the table from the headings as well as the caption. A consequence of this is that captions will often be inadequate as a summary of the purpose and structure of the table from the perspective of people relying on non-visual user agents.

Authors should therefore take care to provide additional information summarizing the purpose and structure of the table using the Summary attribute of the element. This is especially important for tables without captions.

l 'frame' attribute - GridTableView.Frame - sets tips and visibility for table borders.

3.1.3 Other accessibility features: l r.a.d.grid renders header cells in the header row

l r.a.d.grid renders 'thead', 'tfoot' and 'tbody' elements

Section 508 The USA federal mandate requiring that information technology be made accessible to people with disabilities. Much of Section 508 compliance concerns making Web sites, intranets, and web-enabled applications accessible. Section 508 compliance has since become a major prerequisite not only in government related software, but also in most enterprise and corporate software solutions.

W3C Web Content Accessibility Guidelines 1.0The main goal of these guidelines is to encourage developers in creating applications providing accessible content. However, adhering to these guidelines will also make Web content more available to all kind of users, using different devices and interfaces: desktop browser, voice browser, mobile phone, automobile-based personal computer, etc.

In accoradnce with these quidelines W3C defines three levels of conformance  developer may implement inorder to provide some level of content compliance to their products:

l Conformance Level "A"

l Conformance Level "Double-A"

l Conformance Level "Triple-A"

3 Standards Compliance

3.1 Accessibility Compliance

r.a.d.grid v3.0 | 17

© 2002-2006, telerik. All Rights Reserved.

Page 18: r.a.d.grid v3

For more details on W3C Web Content Accessibility Guidelines 1.0 see http://www.w3.org/TR/WAI-WEBCONTENT.

In our attempt to make our products content compliant, each web-control we develop and its Quick Start Framework should strive to obtain at least one of conformance levels listed above.

Compliance Levelr.a.d.grid now provides XHTML 1.1 compliance, with the following exceptions:

l GridCheckBoxColumn is not XHTML compliant. By default it is ReadOnly and .NET Framework renders:disabled="disabled" which is not XHTML compliant statement.

What is XHTMLXHTML stands for EXtensible HyperText Markup Language and it is a stricter and cleaner version of HTML recommended by W3C (World Wide Web Consortium). XHTML is the effective inheritor of HTML 4.01 and although it is almost identical to its predecessor it is aimed to replace it.

3.2 XHTML Compliance

r.a.d.grid v3.0 | 18

© 2002-2006, telerik. All Rights Reserved.

Page 19: r.a.d.grid v3

r.a.d.grid v2.0 to r.a.d.grid v3.0l The type of the property RadGrid.ClientSettings.Scrolling.ScrollHeight that is a member of

GridScrolling class i changed from string to Unit. You should use the corresponding Unit static constructor to assign a value to this property.

l DataKeyField is deprecated in r.a.d.grid v3.0. Use DataKeyNames instead.

l DataKeys is deprecated in r.a.d.grid v3.0. Use DataKeyValues instead.

l GridTableView.CreateColumnSet functions are deprecated in r.a.d.grid v3.0. You should handle the RadGrid.ColumnCreated event. In the event argument, you can find the column that r.a.d.gridis currently creating and customize it as needed.

r.a.d.grid v1.0 to r.a.d.grid v2.01. If you use r.a.d.grid v1.0 code for r.a.d.grid v2.0, you may find some of your columns missing or empty. This behavior is caused because the state management was changed since r.a.d.grid 1.0.4.In order to improve the dynamic creation of r.a.d.grid , the state management was implemented for the whole columns collection. This feature unfortunately affects slightly the behavior when switching from 1.x to 2.0 if you add dynamically columns to r.a.d.grid . As the collection of column is now restored automatically after each postback, you should create and add the column in r.a.d.grid in Page_Load if IsPostBack is false.If you use VB you could also move the call to the routine for dynamical creation of r.a.d.grid from Page.Init to RadGrid.Init event handler.

4 Changes And Backward Compatibility

The old usage:RadGrid1.ClientSettings.Scrolling.ScrollHeight = "300px";New usage:RadGrid1.ClientSettings.Scrolling.ScrollHeight = Unit.Pixel(300);

r.a.d.grid v3.0 | 19

© 2002-2006, telerik. All Rights Reserved.

Page 20: r.a.d.grid v3

Serverl Internet Information Services (IIS)

l Microsoft .NET Framework 1.0, 1.1

Browser Clientl Internet Explorer 5.0+, Netscape 6.0+, Mozilla 1.+, Firefox 1.x

l Opera 7+

l JavaScript must be enabled in order to use the client-side functions

Browser LimitationsThe following article describes the browser limitations and what implications do they have on r.a.d.controls:

http://www.telerik.com/Default.aspx?PageId=2575

To install r.a.d.grid on your machine run the RadGrid_3_0.exe and follow the instructions.

The wizard will install the r.a.d.grid component in the following folder (unless you specify otherwise):

\Program Files\telerik\r.a.d.grid3.0\NET1

It will also create a virtual folder "r.a.d.grid3.0_Net1" (accessible at "http://localhost/telerik/r.a.d.grid3.0_NET1" ).

The installation folder contains the following:

l "bin" folder - contains the RadGrid .dll files.

l "Img" folder - contains the node images used in the r.a.d.grid examples

l "RadControls" folder

l RadControls\Grid\Skins- contains the grid skins

l RadControls\Grid\Script\[product_version] - contains the clients-side java script file

Hint: To launch the Quick-Start framework do the following:

l Access it via http:// (http://localhost/) localhost (e.g. "http://localhost/telerik/r.a.d.grid3.0_NET1" by default) or from your Start Menu -> Telerik -> r.a.d.grid v3.0 -> ASP.NET 1.X -> r.a.d.grid v3.0 Live Examples

Individual Versus Common r.a.d.controls InstallationSince r.a.d.grid can be deployed as an individual control as a member of the r.a.d.controls suite, for example, the developer may use the common installer to install the whole controls suite, or may want to install only an updated version of a control.

You can safely install the updated r.a.d.grid only and keep your existing r.a.d.grid installation. r.a.d.gridfiles will be placed in a separate folder and the new installation will not damage the common installer files. The r.a.d.grid installation may have an updated help too - it will get registered with the correct grid namespace. You should be able to see the updated r.a.d.grid help in your MSDN help viewer.

5 Installation and Deployment

5.1 System Requirements

5.2 Installing r.a.d.grid From EXE File

r.a.d.grid v3.0 | 20

© 2002-2006, telerik. All Rights Reserved.

Page 21: r.a.d.grid v3

To install r.a.d.grid on your machine from the ZIP file follow the instructions below:

1. Log in your Client.NET account.

2. Go to "My licenses".

3. Locate the control that you need to install, i.e. r.a.d.grid.

4. Click on the "Download" link next to the respective version and download the ZIP file.

5. Once the download completes, unzip the files in your IIS's inetpub/wwwroot/telerik folder.

The installation folder contains the following:

l "bin" folder - contains the RadGrid .dll files.

l "Img" folder - contains the node images used in the r.a.d.grid examples

l "RadControls" folder

l RadControls\Grid\Skins- contains the grid skins

l RadControls\Grid\Script\[product_version] - contains the clients-side java script file

7. Create a virtual directory for the folder where you unzipped the files. This is accomplished through the Internet Information Services console: Start -> Settings -> Control Panel -> Administrative Tools -> Internet Information Services.Navigate to the folder you've created, right-click on it, choose Properties and finally click the Create button. Click OK.

8. Give full permission rights to the ASPNET user (if you are using IIS5) or to the Network Service account (under IIS6) on the folder where the files were unzipped.

9. Run the project by using "http://localhost/telerik/r.a.d.grid3.0_NET1"

If you add r.a.d.grid to the Visual Studio .Net Toolbox you will be able to easily deploy the component in your WebForms in Design mode (Section 5.4.1). Follow the steps below:

1. Open the Toolbox.

2. Expand the General Section.

3. Right click it and open Customize Toolbox (called Add/Remove Items in Visual Studio 2003 or Choose Items in Visual Studio 2005).

4. Click the .NET Framework Components tab.

5. Click the Browse button.

6. Browse to the r.a.d.grid installation folder ("\Program Files\telerik\r.a.d.grid3.0\NET1" by default) and select the RadGrid.dll from the "bin" subfolder.

7. Click the Open button to confirm.

5.3 Installing r.a.d.grid From ZIP File

5.4 Deploying r.a.d.grid Into ASP.NET Applications

5.4.1 Adding r.a.d.grid to the Visual Studio Toolbox

r.a.d.grid v3.0 | 21

© 2002-2006, telerik. All Rights Reserved.

Page 22: r.a.d.grid v3

The r.a.d.grid icon should appear in the Toolbox.

In order to add r.a.d.grid to an ASP.NET WebForm you can use one of the following two approaches:

l Drag the r.a.d.grid icon from the Visual Studio .NET Toolbox (Section 5.4.1)

l Write the r.a.d.grid tag manually in the aspx/ascx file

In both cases you also need to copy the "RadControls (Section 5.4.5)" folder from the r.a.d.gridinstallation folder to the root folder of your web-application.

Adding r.a.d.grid to a WebForm using Visual Studio .NETThe easiest way to deploy r.a.d.grid is by dragging its icon from the Visual Studio .NET Toolbox in Design mode. Visual Studio will automatically copy the RadGrid.dll to the ".\bin" folder of your web-application and will create the respective References. You only have to copy the "RadControls" folder as explained above.

5.4.2 Adding r.a.d.grid to an ASP.NET WebForm

Note: You can place the folder to any location and specify it by setting the corresponding value in RadControlsDir property.

r.a.d.grid v3.0 | 22

© 2002-2006, telerik. All Rights Reserved.

Page 23: r.a.d.grid v3

Adding r.a.d.grid to a WebForm ManuallyIf you prefer you can deploy r.a.d.grid manually. Follow the instructions below:

l Copy the "RadControls (Section 5.4.5)" folder from the r.a.d.grid installation folder to the root folder of your web-application.

l Copy the RadGrid.dll from the "bin" of the r.a.d.grid installation folder to the "bin" folder of your web-application.

l Open your aspx/ascx template and add the r.a.d.grid Register directive at the top:

l Write the r.a.d.grid tags in the body of the WebForm:

To add a control to the Global Assembly Cache (GAC) follow the instructions below:

1. Run the .NET command prompt (Start -> Programs -> Microsoft VS.NET -> VS.NET Tools -> VS.NET prompt) and start the gacutil.exe tool with -i parameter (install) and the name of the control, e.g.

You may also directly copy the dll files to the "\WINDOWS\assembly" (or "\WINNT\assembly") folder of your server - this is equivalent to the effect of the gacutil.exe utility.

2. Change the machine.config file of the server and add a reference to the assembly in the GAC. The machine.config file is the configuration file for all web applications on the server. It is located at: "\WINDOWS\Microsoft.NET\Framework\v1.0.3705\CONFIG" (you may need to change the version for different .NET versions). It is similar in to the web.config file, but the web.config only works for the web application, in which it resides.

Note: You can place the folder to any location and specify it by setting the corresponding value in RadControlsDir property.

<%@ Register TagPrefix="radG" Namespace="Telerik.WebControls" Assembly="RadGrid" %>

<radG:RadgridID="RadGrid1"Runat="server"Width="285px"Height="300px"

/>

5.4.3 Adding r.a.d.grid to the Global Assembly Cache

gacutil.exe -i RadGrid.dll

r.a.d.grid v3.0 | 23

© 2002-2006, telerik. All Rights Reserved.

Page 24: r.a.d.grid v3

Locate the <assemblies> tag (which should be under <configuration><system.web> <compilation>/<compilers>/<assemblies> ) Between the <assemblies> tag, you should enter something similar to:

To get the information that goes into the assembly attribute (version, culture, PublicKeyToken), you can run the gacutil /l command, which will return a list of all the assemblies in the GAC. You will have to look for the one you just added and copy the entire line (minus the Custom=null part at the end).For example, the following command:

will return:

so the correct entry in the machine.config should be:

After that you should be able to use the control in all the application on the server without having to copy it to the "bin" folder of each web-application.

5.4.3.1 Remove from Global Assembly CacheIn order to remove r.a.d.grid from GAC, please use the following command:

The r.a.d.grid client-side script (JavaScript) is extracted in an external file, which will be automatically cached by the browser. You don't have to do anything to enable this caching mechanism.

The client-side script is located in the folder "\RadControls\Grid\Script\[product_version]". By default the RadControls folder is located in the root of your web-application, but you can relocate (Section 5.4.5) it if needed.

The /RadControls folder contains the various resources needed for the telerik r.a.d.controls(http://www.telerik.com/radcontrols) components (i.e. images, localization files, configuration files, skins, etc.). Each component seeks for its resources in the respective subfolder of "RadControls", for example /RadControls/Grid/ for the r.a.d.grid.

By default, the RadControls folder should be located (Section 5.4.1) in the root of your web-application. However, you can move the folder using the Windows Explorer to a different location within your web-application and specify its position in the RadControlsDir property e.g.

Moving the folder within your web-application1. Manually copy the RadControls to the new location within your web application (say ~/Resources/).

Do not use VS to do this for you as it changes the namespaces of the files and changes the project language from C# to VB which in turn breaks the application.

2. Specify its position in the RadControlsDir property in the control's declaration in your ascx/aspx file, e.g.

<add assembly="AssemblyFileName, Version=0.0.0.0, Culture=neutral, PublicKeyToken=5edf592a9c40680c"

gacutil -l RadGrid

RadGrid, Version=3.0.0.0, Culture=neutral, PublicKeyToken=e8ab424810b6b9b5 Custom=null

<add assembly="RadGrid, Version==3.0.0.0, Culture=neutral, PublicKeyToken=e8ab424810b6b9b5"

gacutil.exe -u radgrid

5.4.4 Caching Client-Side Scripts

5.4.5 Relocating the RadControls Folder

You do not need to add the /RadControls folder to your VisualStudio project.

RadControlsDir="~/Resources/RadControls/"

<radG:RadGrid>

r.a.d.grid v3.0 | 24

© 2002-2006, telerik. All Rights Reserved.

Page 25: r.a.d.grid v3

where the tilde "~" represents the root of your web-application.

Moving the folder outside your web-applicationThis is the best scenario if you want to have single RadControls folder for several applications.

1. Manually copy the RadControls to the new location (say ~/Resources/). Do not use VS to do this for you as it changes the namespaces of the files and changes the project language from C# to VB which in turn breaks the application.

2. Create a virtual directory with name RadControls under each application root which points physically to the same physical folder. That physical folder should include all the scripts and other required settings of the controls. Note that such mechanism enables different versions of our products to reside in different web applications - just change the reference of the virtual folder to other physical path when you want to use other version of some control.

3. Please, keep in mind that in such scenario it is very important that the respective RadControls virtual directories should NOT be web application but virtual directories only.

4. Specify the position of the RadControls folder in the RadControlsDir property in the control's declaration in your ascx/aspx file as shown below :

where the tilde "~" represents the root of your web-application.

There are two approaches for enabling IntelliSense support for the r.a.d.controls in Visual Studio.NET IDE:

l enable IntelliSense globally for all projects

l enable IntelliSense for a specific project (this approach allows you to have IntelliSense for 2 or more different versions of one control, e.g. one version used in one project, and another version used in a different project)

Enabling IntelliSense globally for all projects1. Copy the XSD schema from the installation folder:

RadControls/[Control]/Intellisense/Rad[Control].xsd

...RadControlsDir="~/Resources/RadControls">

</radG:RadGrid>

<radG:RadGrid>...RadControlsDir= "~/RadControls">

</radG:RadGrid>

Make sure you set the RadControlsDir property to "~/RadControls/" (with the slash following the letters).

Default location Relocated

(RadControlsDir not set) (RadControlsDir="~/Resources/RadControls/")

5.4.6 Using Visual Studio .Net IntelliSense

r.a.d.grid v3.0 | 25

© 2002-2006, telerik. All Rights Reserved.

Page 26: r.a.d.grid v3

to ..\<Visual Studio Installation Folder>\Common7\Packages\schemas\xml

Please, note that you must restart VS.NET after copying the .xsd files to the specified folder in order to add the xmlns attributes.

2. Add the scheme in your ASPX file as described below

Enabling IntelliSense for a specific project1. After you copy the RadControls folder from the product installation folder to the root of your web

application, you need to include the following file in your Visual Studio .Net project:RadControls/[Control]/Intellisense/Rad[Control].xsd

Important: Make sure that you include only this file!

2. Add the scheme in your ASPX file as described below

Adding the scheme in your ASPX fileFor both approaches above you have to properly add the XSD schema in your web form. The xml namespace declaration attribute should be set within a surrounding tag, such as <SPAN> and then place the control declaration inside it to take advantage of the Intellisense. For example:

<span xmlns:radG="http://schemas.telerik.com/Intellisense/RadGrid">................

<radg:radgrid id="RadGrid1" runat="server" />................

</span>

or

<body xmlns:radG="http://schemas.telerik.com/Intellisense/RadGrid">................

<radg:radgrid id="RadGrid1" runat="server" />................

</body>

r.a.d.grid v3.0 | 26

© 2002-2006, telerik. All Rights Reserved.

Page 27: r.a.d.grid v3

The instructions above are the same for all of telerik controls. You will just need to change the xmlnsattribute to point to the appropriate tag prefix of our control, for example:

Visual Studio 2005 automatically enables IntelliSense - through reflection it detects all classes, properties and methods in the dll file(s).

For additional convenience each telerik control is provided an XML file which contains the comments for its classes, properties and methods. For example, when r.a.d.grid is dragged to the webform the RadGrid.Net2.xml file is automatically added in the bin directory of the project. Each time a particular class/property/method is being selected from the dropdown of the autocomplete functionality, a tooltip with the comment for this class/property/method is displayed:

Developer LicensesIf you have purchased a developer license, you can skip this section. Developer licenses come with modified DLLs, which work without license keys. If you have a developer license for one or more of the

IMPORTANT: You should never set the xmlns attribute to a server control declaration, i.e. the following will be wrong: <form id="Form1" runat="server" xmlns:radG="http://schemas.telerik.com/Intellisense/RadGrid"><radg:radgrid id="RadGrid1" runat="server" />

</form>

<%@ Register TagPrefix="radG" Namespace="Telerik.WebControls" Assembly="RadGrid" %>

<body xmlns:radG=http://schemas.telerik.com/Intellisense/RadGrid><radG:RadGrid ID="grid1" Runat="server"

......</radG:RadGrid>

......</body>

5.4.7 Using IntelliSense in Visual Studio 2005

5.5 Licensing

5.5.1 Setting Trial License Keys

r.a.d.grid v3.0 | 27

© 2002-2006, telerik. All Rights Reserved.

Page 28: r.a.d.grid v3

telerik components, you only need to ensure that you are using the developer build.

If your application is displaying a license key error, this means that you are using a trial version of the product. Log in to your Client.net (http://www.telerik.com/clientnet) account and download the developer build. Please take a look at section "Upgrading the Trial License to a Production License (Section 5.5.1)" step-by-step instructions.

Trial LicensesThe free trial licenses of all telerik products are fully functional and will work for an unlimited time without license keys at http://localhost. The trial licenses will display the following message on your webform:

"[product name] Copyright © telerik 2005. To remove this message, please, obtain a 30-day trial key".

The message can be removed if you set a trial license key.

Also, if you try to access the products by IP (e.g. http://123.123.123.123), domain name (http://www.telerik.com), or machine name (http://MyPc/MyWebApplication), you will receive the following license key warning:

"([product name] You have not provided valid license key or company name, or you are trying to access the control by domain name, IP, or server name. Please, use http://localhost/ instead or contact telerik's support team through the on-line ticketing system)".

By setting a trial license key you will be able to test the products on locations other than http://localhost and will also hide the copyright message. You can generate a trial license key by logging to your Client.net (http://www.telerik.com/clientnet) account. Follow the steps below:

1. Log into Client.net (www.telerik.com/clientnet (http://www.telerik.com/clientnet))

2. Go to "My Licenses" -> [product] Trial -> "Keys" -> "Generate keys"

3. Complete the fields. (See the "Guidelines for specifying domain names" ('Guidelines For Specifying Domain Names' in the on-line documentation) The key will be generated immediately and will also be sent to your e-mail.

The license information for all telerik components is stored in the LicenseFile.xml file, which can be found in the RadControls folder. By default, the LicenseFile property of each control points to this file: ~/RadControls/LicenseFile.xml.

You can change the file’s location and name, but in order for the products to work properly, you must set a valid path/name in the LicenseFile property.

As the LicenseFile property has a default value, the easiest way to set your licensing information is to open the supplied default LicenseFile.xml and enter the required information. You should use the licensing information from the license key confirmation e-mail to fill in the "company" and "licenseKey" fields for all products that you want to unlock. Below is a sample LicenseFile.xml:

As you can notice, you may use a single LicenseFile to unlock more than one telerik component and thus keep all of your licensing information into one place.

<root>

<license control="grid" company="YOUR COMPANY" licenseKey="YOUR LICENSE KEY1"/>

<license control="spell" company="YOUR COMPANY" licenseKey="YOUR LICENSE KEY2"/>

<license control="menu" company="YOUR COMPANY" licenseKey="YOUR LICENSE KEY3"/>

</root>

5.5.2 License Agreement

r.a.d.grid v3.0 | 28

© 2002-2006, telerik. All Rights Reserved.

Page 29: r.a.d.grid v3

telerik r.a.d.controls Single Developer License

End-User License Agreement

By installing the product identified above and/or its related materials, you are accepting the following License Agreement. Check the box "I have read and agree to the License Agreement" if you agree.

IMPORTANT - READ CAREFULLY: This license agreement ("LICENSE") is a legal agreement between you (either an individual or a single entity, also referred to as "LICENSEE", "YOU") and Telerik Corporation, ("TELERIK"), for the product "telerik r.a.d.controls suite" or "telerik r.a.d.navigation suite" ("PRODUCT SUITES"), or any individual component included in any of the two suites ("INDIVIDUAL COMPONENT"), all of which include computer software, and may include the software's source code written in a high-level computer language, associated media, printed materials, and "online" or electronic documentation (collectively referred to as "SOFTWARE").

By installing, copying, downloading, accessing, or otherwise using the SOFTWARE, you agree to be bound by the terms of this LICENSE. If you do not agree to the terms of this LICENSE, do not buy, install or use the SOFTWARE.

Any earlier license we may have granted to you for the use of earlier versions of the SOFTWARE is replaced by this LICENSE. The purchase of licenses, which include source code, is final.

This license does not apply to Internet Service Provides (ISP). If your entity is an ISP, please, contact the telerik sales team ([email protected]) for a special ISP license agreement.

SOFTWARE PRODUCT LICENSE

The SOFTWARE is protected by copyright laws and international copyright treaties, as well as other intellectual property laws and treaties and contains confidential information and trade secrets. The SOFTWARE is licensed, not sold. TELERIK retains ownership of the copy of the SOFTWARE in your possession, and all copies you may be licensed to make. TELERIK also retains all rights not expressly granted to you in this LICENSE.

1. GRANT OF LICENSE

TELERIK hereby grants to you, and you accept, a non-exclusive, non-transferable license to install, copy, and use the SOFTWARE only as authorized below.

The SOFTWARE is licensed per Developer seat. This means that each individual using or otherwise accessing the SOFTWARE for development purposes must obtain the right to do so by purchasing an individual product license.

You are not allowed to integrate and distribute the SOFTWARE as part of branded commercial products meant for mass distribution. This is subject to a redistributable license. For more information and inquiries, please contact [email protected].

You may make copies on more than one computer, as long as the use of the SOFTWARE is by the same licensed developer. The SOFTWARE is in "use" on a computer when it is loaded into temporary memory (i.e. RAM) or installed into permanent memory (e.g. hard disk or other storage devise) of that computer for development purposes. If you install the SOFTWARE on a network server for the sole purpose of internal distribution among, or development by, licensed developers this is not considered "use" of the SOFTWARE.

Individual Component License:

You are granted 1 (one) Single Developer license to distribute the INDIVIDUAL COMPONENT, which you

r.a.d.grid v3.0 | 29

© 2002-2006, telerik. All Rights Reserved.

Page 30: r.a.d.grid v3

have purchased, royalty-free with an unlimited number of solutions (web-sites or custom web-applications), provided they are developed solely by the licensed developer.

At no time may the INDIVIDUAL COMPONENT be used by other individuals than the licensed developer. The INDIVIDUAL COMPONENT may not be distributed for use with web-sites other than those developed by the licensed developer.

As part of your license you are entitled to "Silver" Support Package which guarantees response within 48 hours.

Component Suite License:

You are granted 1 (one) Single Developer license to distribute the SUITE, which you have purchased, royalty-free with an unlimited number of solutions (web-sites or custom web-applications), provided they are developed solely by the licensed developer.

At no time may the SUITE be used by other individuals than the licensed developers. The SUITE may not be distributed for use with web-sites other than those developed by the licensed developer.

If you have purchased 5 (five) or more Single Developer licenses for the SUITE you are entitled to receive the source code of all included components.

As part of your license you are entitled to "Silver" Support Package which guarantees response within 48 hours.

Component Suite License Plus Subscription:

You are granted 1 (one) Single Developer "Component Suite License" as defined above.

In addition, you are entitled to receive all version updates for the products included in the SUITE, as well as all new products that may be added to the SUITE for a period of 1 (one) year.

As part of your license you are entitled to "Gold" Support Package which guarantees response within 24 hours.

2. DESCRIPTION OF OTHER RIGHTS AND LIMITATIONS

(a) You can distribute the SOFTWARE only as an integral part of your own solutions(s) ("YOUR SOFTWARE"). YOUR SOFTWARE must add significant and primary functionality to the SOFTWARE. The SOFTWARE's source code may be distributed as an integral part of those solution(s) in COMPILED form only.

(b) YOUR SOFTWARE may not, in the reasonable opinion of TELERIK, compete with the SOFTWARE, or any other TELERIK product.

(c) You ensure that the SOFTWARE is not distributed in any form that allows it to be reused by any application other than YOUR SOFTWARE.

(d) You do not wrap or distribute the SOFTWARE in a model, component, or other derivative that can be used for development purposes on any application, tool, environment or container.

(e) Your END-USERS are not allowed to use the SOFTWARE for development purposes or further redistribution and deployment.

(f) You are not allowed to resell, transfer, rent, lease, or sublicense the SOFTWARE and your associated rights.

(g) You are not allowed to disassemble, decompile or "unlock", decode or otherwise reverse translate or engineer, or attempt in any manner to reconstruct or discover any source code or underlying algorithms of SOFTWARE provided in object code form only.

(h) You are not allowed to use, copy, modify, or merge copies of the SOFTWARE and any accompanying

r.a.d.grid v3.0 | 30

© 2002-2006, telerik. All Rights Reserved.

Page 31: r.a.d.grid v3

documents except as permitted in this LICENSE.

(i) Under no circumstances may any portion of the SOFTWARE's source code or any modified version or derivative work of the source code be distributed, disclosed or otherwise made available to any third party.

(j) You may not expose, document or make public the SOFTWARE API (Application Programming Interface) and SOFTWARE DLLs (Dynamic Link Libraries).

(k) You acknowledge that the SOFTWARE's source code contains valuable and proprietary trade secrets of TELERIK. All individuals employed by or belonging to your entity agree to expend every effort to insure its confidentiality.

(l) The SOFTWARE's source code is sold as is. TELERIK does not provide technical support for modified source code.

(m) You may not use the telerik product names, logos or trademarks to market YOUR SOFTWARE.

(n) You agree to indemnify, hold harmless, and defend telerik and its resellers from and against any and all claims or lawsuits including attorney's fees that arise or result from the use or distribution of your software product.

3. DELIVERY

TELERIK shall deliver to LICENSEE a master copy of the SOFTWARE licensed hereunder in compiled C# code in electronic files only. Documentation shall also be provided in electronic format. The applicable source code licensed hereunder will be delivered as C# source files and Visual Studio .NET project files in electronic format only.

4. UPGRADES

You are eligible for free minor upgrades (e.g. v.1.5 to v.1.8), patches, and bug-fixes for the SOFTWARE, including the source code. SOFTWARE labeled as an upgrade replaces and/or supplements (and may disable) the product that formed the basis for your eligibility for the upgrade. You may use the resulting upgraded product only in accordance with the terms of this LICENSE.

If you have purchased a "Component Suite License Plus Subscription" you are entitled to receive all version updates for the products included in the SUITE, as well as all new products that may be added to the SUITE for a period of 1 (one) year.

5. TERMINATION

This LICENSE shall last as long as you use the SOFTWARE in compliance with this LICENSE. TELERIK may terminate this LICENSE if you fail to comply with any of the terms and conditions herein. In such event you agree to remove and destroy all copies of the SOFTWARE, any applicable source code, as well as all copies that have been integrated in other products.

TELERIK reserves the right to discontinue at any time any product, shall it be offered individually or as a part of a product SUITE. However, TELERIK is obligated to provide the proper level of support for all discontinued products for a period of 1 (one) year after the date of discontinuance.

6. COPYRIGHT

All title and copyrights in and to the SOFTWARE (including but not limited to any images, photographs, animations, video, audio, music, text, incorporated into the SOFTWARE), the accompanying printed materials, and any copies of the SOFTWARE, and any trademarks or service marks of TELERIK are owned

r.a.d.grid v3.0 | 31

© 2002-2006, telerik. All Rights Reserved.

Page 32: r.a.d.grid v3

by TELERIK. All title and intellectual property rights in and to the content that may be accessed through use of the SOFTWARE is the property of the respective content owner and may be protected by applicable copyright or other intellectual property laws and treaties. This LICENSE grants you no rights to use such content.

All error corrections, bug fixes, patches, updates or other modifications shall be the sole property of TELERIK.

7. LIMITED WARRANTY

TELERIK warrants solely that the SOFTWARE will perform substantially in accordance with the accompanying written materials for a period of ninety (90) days. TELERIK does not warrant the use of the SOFTWARE will be uninterrupted or error free at all times and in all circumstances, nor that program errors will be corrected. This limited warranty shall not apply to any error or failure resulting from (i) machine error, (ii) LICENSEE's failure to follow operating instructions, (iii) negligence or accident, or (iv) modifications to the SOFTWARE by any person or entity other than TELERIK. In the event of a breach of warranty, LICENSEE 's sole and exclusive remedy, is repair of all or any portion of the SOFTWARE. If such remedy fails of its essential purpose, LICENSEE 's sole remedy and TELERIK's maximum liability shall be a refund of the paid purchase price for the defective SOFTWARE only. This limited warranty is only valid if TELERIK receives written notice of breach of warranty within thirty days after the warranty period expires.

8. LIMITATION OF LIABILITY

TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT WILL TELERIK BE LIABLE FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF OR INABILITY TO USE THE PRODUCT, INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF ADVISED OF THE POSSIBILITY THEREOF, AND REGARDLESS OF THE LEGAL OR EQUITABLE THEORY (CONTRACT, TORT OR OTHERWISE) UPON WHICH THE CLAIM IS BASED. IN ANY CASE, TELERIK'S ENTIRE LIABILITY UNDER ANY PROVISION OF THIS AGREEMENT SHALL NOT EXCEED IN THE AGGREGATE THE SUM OF THE LICENSE FEES LICENSEE PAID TO TELERIK FOR THE PRODUCT GIVING RISE TO SUCH DAMAGES, NOTWITHSTANDING ANY FAILURE OF ESSENTIAL PURPOSE OF ANY LIMITED REMEDY, WITH THE EXCEPTION OF DEATH OR PERSONAL INJURY CAUSED BY THE NEGLIGENCE OF TELERIK TO THE EXTENT APPLICABLE LAW PROHIBITS THE LIMITATION OF DAMAGES IN SUCH CASES. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT BE APPLICABLE. TELERIK IS NOT RESPONSIBLE FOR ANY LIABILITY ARISING OUT OF CONTENT PROVIDED BY LICENSEE OR A THIRD PARTY THAT IS ACCESSED THROUGH THE PRODUCT AND/OR ANY MATERIAL LINKED THROUGH SUCH CONTENT. ANY DATA INCLUDED IN A PRODUCT UPON SHIPMENT FROM TELERIK IS FOR TESTING USE ONLY AND TELERIK HEREBY DISCLAIMS ANY AND ALL LIABILITY ARISING THEREFROM. THE EXTENT OF TELERIK'S LIABILITY FOR THE LIMITED WARRANTY SECTION SHALL BE AS SET FORTH THEREIN.

9. MISCELLANEOUS

This License will be governed by the law of the Republic of Bulgaria. If any provision of this LICENSE is to be held unenforceable, such holding will not affect the validity of the other provisions hereof. Failure of a party to enforce any provision of this LICENSE shall not constitute or be construed as a waiver of such provision or of the right to enforce such provision.

All disputes, arising from this contract or related to it, including those arising from or concerning its interpretation, invalidity, performance or termination, as well as the disputes for filling gaps in this contract or its adaptation to newly established facts, shall be referred for resolution to the Court of Arbitration at the Bulgarian Chamber of Commerce and Industry in compliance with its Rules for Litigations, based on arbitration agreements.

This License represents the entire understanding between the parties with respect to its subject matter.

YOU ACKNOWLEDGE THAT YOU HAVE READ THIS AGREEMENT, THAT YOU UNDERSTAND THIS AGREEMENT, AND UNDERSTAND THAT BY CONTINUING THE INSTALLATION OF THE SOFTWARE PRODUCT, BY LOADING OR RUNNING THE SOFTWARE PRODUCT, OR BY PLACING OR COPYING THE SOFTWARE ONTO YOUR COMPUTER HARD DRIVE, YOU AGREE TO BE BOUND BY THIS AGREEMENT'S TERMS AND CONDITIONS. YOU FURTHER AGREE THAT, EXCEPT FOR WRITTEN SEPARATE AGREEMENTS

r.a.d.grid v3.0 | 32

© 2002-2006, telerik. All Rights Reserved.

Page 33: r.a.d.grid v3

BETWEEN TELERIK AND YOU, THIS AGREEMENT IS A COMPLETE AND EXCLUSIVE STATEMENT OF THE RIGHTS AND LIABILITIES OF THE PARTIES.

Follow the steps below to upgrade your r.a.d.grid v2.x trial license to a Developer (production) license.

5.6.1.1 1. Back up Your Old Files We strongly suggest that you back-up your old r.a.d.grid files and folders.

5.6.1.2 2. Obtain the Necessary FileDownload the DEVELOPER build from the "My licenses" section of your Client.Net (http://www.telerik.com/clientnet) account, if you haven't done so already. We suggest that you use the ZIP version.

5.6.1.3 3. Install and Copy the New Files Unpack the ZIP file directly in your project folder, overwriting all existing files.

5.6.1.4 4. Update the Global Assembly Cache registrationIf you have added the control in GAC, remove it by running a gacUtil to remove the old copy and then add the new one. See how (Section 5.4.3)

5.6.1.5 5. Remove the Licensing Properties Since the Developer build does not use license keys, the following Licensing properties are no longer needed:

l LicenseKey

l Company

l LicenseFile

5.6.1.6 6. Changes and Backward CompatibilitySee Changes and Backwards compatibility (Section 4) for changed methods, properties and events which may break your application if not updated.

5.6.1.7 7. Recompile the Project

5.6.1.8 8. Run the project

Troubleshooting the Upgrade Process

If you still get the older version then try the following (not related to telerik controls):

l Sometimes the .NET Framework wrongly caches the r.a.d.controls' DLLs and therefore the update may seem to have failed. Try the following to ensure that this has been the exact problem and eliminate it:

1. Terminate the aspnet_wp.exe process (from the Windows Task Manager)2. Open a Windows Explorer and navigate to

C:\Windows(WINNT)\Microsoft.NET\Framework\vYOUR_VERSION\Temporary ASP.NET Files

5.6 Upgrading Instructions

5.6.1 Trial License v2.x to Developer License v3.0

THE PROCEDURE DESCRIBED IN THIS MANUAL IS IRREVERSIBLE AND YOU MAY LOSE YOUR DATA IF THE INSTALLATION IS NOT CARRIED OUT CORRECTLY!

If you are using Visual Studio .Net you need to also update the assembly references and recompile your project.

r.a.d.grid v3.0 | 33

© 2002-2006, telerik. All Rights Reserved.

Page 34: r.a.d.grid v3

3. Delete all the folders with names, corresponding to your telerik projects, containing RadEditor, RadTreeView, etc.

l Delete your Visual Studio web project caches as well - they should be located at C:\Documents and Settings\<YOUR USER>\VSWebCache.

l Delete your browser cache: Tools -> Internet Options -> Delete Files....

Follow the steps below to upgrade your r.a.d.grid v2.0 Developer license to a v3.0 Developer license.

5.6.2.1 1. Back up Your Old Files We strongly suggest that you back-up your old r.a.d.grid files and folders.

5.6.2.2 2. Obtain the Necessary FileDownload the DEVELOPER build from the "My licenses" section of your Client.Net (http://www.telerik.com/clientnet) account, if you haven't done so already. We suggest that you use the ZIP version.

5.6.2.3 3. Install and Copy the New Files Unpack the ZIP file directly in your project folder, overwriting all existing files.

5.6.2.4 4. Changes and Backward CompatibilitySee Changes and Backwards compatibility (Section 4) for changed methods, properties and events which may break your application if not updated.

5.6.2.5 6. Recompile the Project

5.6.2.6 7. Run the project

Troubleshooting the Upgrade Process

If you still get the older version then try the following (not related to telerik controls):

l Sometimes the .NET Framework wrongly caches the r.a.d.controls' DLLs and therefore the update may seem to have failed. Try the following to ensure that this has been the exact problem and eliminate it:

1. Terminate the aspnet_wp.exe process (from the Windows Task Manager)2. Open a Windows Explorer and navigate to

C:\Windows(WINNT)\Microsoft.NET\Framework\vYOUR_VERSION\Temporary ASP.NET Files3. Delete all the folders with names, corresponding to your telerik projects, containing

RadEditor, RadTreeView, etc.

l Delete your Visual Studio web project caches as well - they should be located at C:\Documents and Settings\<YOUR USER>\VSWebCache.

l Delete your browser cache: Tools -> Internet Options -> Delete Files....

Follow the steps below to upgrade your r.a.d.grid v3.0 trial license to a Developer (production) license.

5.6.3.1 1. Back up Your Old Files We strongly suggest that you back-up your old r.a.d.grid files and folders.

5.6.2 Developer License v2.x to Developer License v3.0

THE PROCEDURE DESCRIBED IN THIS MANUAL IS IRREVERSIBLE AND YOU MAY LOSE YOUR DATA IF THE INSTALLATION IS NOT CARRIED OUT CORRECTLY!

If you are using Visual Studio .Net you need to also update the assembly references and recompile your project.

5.6.3 Trial License v3.0 to Developer License v3.0

r.a.d.grid v3.0 | 34

© 2002-2006, telerik. All Rights Reserved.

Page 35: r.a.d.grid v3

5.6.3.2 2. Obtain the Necessary FileDownload the DEVELOPER build from the "My licenses" section of your Client.Net (http://www.telerik.com/clientnet) account, if you haven't done so already. We suggest that you use the ZIP version.

5.6.3.3 3. Install and Copy the New Files Unpack the ZIP file directly in your project folder, overwriting all existing files.

5.6.3.4 4. Update the Global Assembly Cache registrationIf you have added the control in GAC, remove it by running a gacUtil to remove the old copy and then add the new one. (See how (Section 5.4.3))

5.6.3.5 5. Remove the Licensing Properties Since the Developer build does not use license keys, the following Licensing properties are no longer needed:

l LicenseKey

l Company

l LicenseFile

5.6.3.6 7. Recompile the Project

5.6.3.7 8. Run the project

Troubleshooting the Upgrade Process

If you still get the older version then try the following (not related to telerik controls):

l Sometimes the .NET Framework wrongly caches the r.a.d.controls' DLLs and therefore the update may seem to have failed. Try the following to ensure that this has been the exact problem and eliminate it:

1. Terminate the aspnet_wp.exe process (from the Windows Task Manager)2. Open a Windows Explorer and navigate to

C:\Windows(WINNT)\Microsoft.NET\Framework\vYOUR_VERSION\Temporary ASP.NET Files3. Delete all the folders with names, corresponding to your telerik projects, containing

RadEditor, RadTreeView, etc.

l Delete your Visual Studio web project caches as well - they should be located at C:\Documents and Settings\<YOUR USER>\VSWebCache.

l Delete your browser cache: Tools -> Internet Options -> Delete Files....

THE PROCEDURE DESCRIBED IN THIS MANUAL IS IRREVERSIBLE AND YOU MAY LOSE YOUR DATA IF THE INSTALLATION IS NOT CARRIED OUT CORRECTLY!

If you are using Visual Studio .Net you need to also update the assembly references and recompile your project.

r.a.d.grid v3.0 | 35

© 2002-2006, telerik. All Rights Reserved.

Page 36: r.a.d.grid v3

ItemItems are the grid rows (GridDataItem object). In case you are using advanced appearance, you can have Items (odd rows) and AlternatingItems (even rows - see below).

AlternatingItemAlternatingItems like Items are the grid rows. In case you use advanced appearance, you can have Items (odd rows) and AlternatingItems (even rows).

6 r.a.d.grid Overview

6.1 Grid Elements

r.a.d.grid v3.0 | 36

© 2002-2006, telerik. All Rights Reserved.

Page 37: r.a.d.grid v3

HeaderItemThe header element is represented by GridHeaderItem object. If you want to have a header element for your columns, you need to set ShowHeader Property to true. Details (Section 6.2.2)

GridFilteringItemGridFilteringItem will appear automatically when you have Filtering (Section 13.6) enabled either by RadGrid.AllowFilteringByColumn or GridTableView.AllowFilteringByColumn properties.

r.a.d.grid v3.0 | 37

© 2002-2006, telerik. All Rights Reserved.

Page 38: r.a.d.grid v3

EditFormItemThis item nests the edit form that shows controls for item editing.

GridCommandItemGridCommandItem can be used to add function buttons in the content area of RadGrid, such as Add New Record, Refresh and others. The item content can be specified through a template. The command item can appear on the top/bottom/top and bottom of the grid. GridCommandItem is used when performing automatic database operations (Section 8.4).

Row Indicator ColumnYou can allow the row resizing by setting AllowRowResize Property to true. When you set this property, r.a.d.grid automatically generates a column of type GridRowIndicatorColumn. This column represents the handles for row resizing.

r.a.d.grid v3.0 | 38

© 2002-2006, telerik. All Rights Reserved.

Page 39: r.a.d.grid v3

Expand ColumnThe GridExpandColumn is an automatically generated and automatically placed column. It appears when the grid has a hierarchical structure. This column holds the expand/collapse functionality. The expand column is always placed in front of all other grid content columns and can not be moved. You can also manually add other instances of this type of column.

User ColumnDisplays a column bound to a field in a data source. The default data binding (when AutoGeneratedColumns property is set to true) generates GridBoundColumn columns.

MasterTableView

r.a.d.grid v3.0 | 39

© 2002-2006, telerik. All Rights Reserved.

Page 40: r.a.d.grid v3

MasterTableView is the top most table in the hierarchical structure. It contains all inner tables (DetailTables), which are available on demand (see Hierarchy Load (Section 13.7)). When there is no hierarchical structure, this table coincides with GridTableView.

DetailTableViewDetailTableView is the inner table of a hierarchical structure (2, 3 and more levels).

NestedViewItemNested view items have only one cell, that nests child table(s) (GridTableView).

r.a.d.grid v3.0 | 40

© 2002-2006, telerik. All Rights Reserved.

Page 41: r.a.d.grid v3

ScrollBarsIn order to enable the scrolling you need to set AllowScroll property to true. By default its value is false. The ScrollHeight property tells the grid the height beyond which the scrolling will be turned on. Read More...(Section 12.5)

Grouping elements - Group Splitter Column and Group Header ItemsThe GridGroupSplitterColumn is an automatically generated and automatically placed column. This column appears when you have grouping enabled and it facilitates the expand/collapse functionality. The group splitter column is always placed first and cannot be moved. Read More... (Section 6.2.1)

r.a.d.grid v3.0 | 41

© 2002-2006, telerik. All Rights Reserved.

Page 42: r.a.d.grid v3

Group PanelWhen you want to enable the group-by functionality, you need to set RadGrid.GroupingEnabled to true.

RadGrid.ShowGroupPanel shows/hides the group panel. Read More... (Section 13.3)

Panel Items

r.a.d.grid v3.0 | 42

© 2002-2006, telerik. All Rights Reserved.

Page 43: r.a.d.grid v3

You can access the group panel using the GroupPanel property of RadGrid. You should use PanelStyle and PanelItemsStyle to control the style of the group panel and its items. Read More... (Section 13.3)

telerik r.a.d.grid currently supports two main sets of columns, in accordance with how they are generated:

l Automatically generated columns - if the AutoGenerateColumns property is set to true (default value) r.a.d.grid will add at runtime all columns for each field from the specified DataSource after DataBinding (Section 7.2.1). This set of columns can be accessed using the AutoGeneratedColumns property.

l User-specified columns - these columns are created by the developer using the designer (Section 9.1) or by modifying the Columns collection at runtime. This is known as column binding:

The default columns appearance order (runtime rendering) is the same as the order they are declared.

Column Types

6.2 Columns

6.2.1 Column Types

Runtime auto generated columns would appear always after the user-specified columns, unless columns are reordered programmatically.

<Columns><radg:GridBoundColumn DataField="UnitPrice" SortExpression="UnitPrice" HeaderText=<radg:GridBoundColumn DataField="Quantity" SortExpression="Quantity" HeaderText="Quantity"<radg:GridBoundColumn DataField="Discount" SortExpression="Discount" HeaderText="Discount"

</Columns>

r.a.d.grid v3.0 | 43

© 2002-2006, telerik. All Rights Reserved.

Page 44: r.a.d.grid v3

Different column types determine the behavior of the columns in the control. Each r.a.d.grid table has a Columns Collection. Below is a list of all supported types of columns:

6.2.1.1 GridBoundColumnGridBoundColumn is the default column type of r.a.d.grid. It displays a column bound to a field in a data source. The default data binding (when AutoGenerateColumns property is set to true) generates GridBoundColumn type of columns. It displays each item from the DataSource field as text. This column is editable (Section 8.7) (implements the IGridEditableColumn interface) and provides by default GridTextColumnEditor, used for editing the text in each item.

GridBoundColumn has three similar and yet different properties controlling it visibility and rendering in a browser in regular and in edit mode:

l Display - concerns only the appearance the column in browser mode, client-side. The column will be rendered in the browser but all the cells will be styled with display: none. The column editor will be visible in edit mode.

l Visible - will stop column's cells from rendering in browser mode. The column will be visible in edit mode.

l ReadOnly - the column will be displayed according to the settings of previous properties in browser mode but will not appear in the edit-form.None of these properties can prevent you from accessing the column cells' content server-side using the UniqueName of the column.

6.2.1.2 GridButtonColumnGridButtonColumn displays a button for each item in the column. This button then can perform some command. This allows you to create a column of custom button controls, such as Add, Remove, Selector Edit buttons. The available buttons types are: PushButton, LinkButton and ImageButton. r.a.d.grid comes with two types of button columns:

l Select - when a button in this column is pressed, it will select the whole row. The Select column below uses a PushButton .

l Remove selection - when a button in this column is pressed, it will delete the row. The Remove selection column below uses a LinkButton.

6.2.1.3 GridEditCommandColumn Initially only the Edit button is shown. When it is pressed, the [Update] and [Cancel] appear on its place and the cells on this row become editable. The Edit button below uses a LinkButton.

r.a.d.grid v3.0 | 44

© 2002-2006, telerik. All Rights Reserved.

Page 45: r.a.d.grid v3

After clicking the Edit button, the column changes to:

GridEditCommandColumn can use also images as edit/update/cancel buttons:

6.2.1.4 Hyperlink ColumnEach row in a Hyperlink column will contain a predefined hyperlink. This link is not the same for the whole column and can be defined for each row individually. The content of the column can be bound to a field in a data source or to static text. You can customize the look of the links by using CSS classes (Section 10.1).

6.2.1.5 GridCheckBoxColumn Displays a CheckBox control for each item in the column. This allows you to edit for example Booleanfield(s) from data table(s). This column is editable (implements the IGridEditableColumn interface) and provides by default GridBoolColumnEditor, used for editing the text in each item. You can persist the checked state of a checkbox, if you use it within GridTemplateColumn (see below).

6.2.1.6 GridDropDownColumn Displays a DropDown control for each item in the column. This allows you to edit for example lookup field(s) from data table(s). This column is editable (implements the IGridEditableColumn interface) and provides by default GridDropDownColumnEditor, used for editing the text in each item.

6.2.1.7 GridTemplateColumnDisplays each item in the column in accordance to a specified template. This allows you to provide custom controls in the column. You can view and set templates using the Edit Template command in Visual Studio .NET.

r.a.d.grid v3.0 | 45

© 2002-2006, telerik. All Rights Reserved.

Page 46: r.a.d.grid v3

This will open the template editor, where you can set the template as common HTML. The template editor allows you to set header and footer for the template as well as a different view for this template when it is in edit mode.

There are cases in which the user would like to retain the checked column state in a hierarchical grid after expand/collapse for further custom operations. You can use ViewState properties on the page which holds the grid to save the current checkbox selection for each master/detail table. The alterations of these properties should be made in the OnCheckedChanged event handler of the respective checkbox.

The example below is optimized for viewstate minimization as these properties are modified only when CheckBoxInstance.Checked is True. Otherwise the row value is not added to the ViewState.

Similar actions could be performed for persistance of other controls state in GridTemplateColumn.

r.a.d.grid v3.0 | 46

© 2002-2006, telerik. All Rights Reserved.

Page 47: r.a.d.grid v3

ASPX Code<radg:radgrid id="RadGrid1" CssClass="RadGrid" style="Z-INDEX: 101; LEFT: 48px; POSITION: absolute; TOP: 32px"

runat="server" AutoGenerateColumns="False" AllowSorting="True" AllowPaging=DataMember="Customers"><MasterTableView ... >

<EditFormSettings><EditColumn UniqueName="EditCommandColumn"></EditColumn>

</EditFormSettings><Columns>. . .

<radg:GridTemplateColumn UniqueName="MasterTemplate" HeaderText="Checkbox column 1"<ItemTemplate>

<asp:CheckBox ID="cbChecked"

Runat="server" AutoPostBack="True" OnCheckedChanged="CheckChanged"></asp:CheckBox>

</ItemTemplate></radg:GridTemplateColumn>. . .

<ExpandCollapseColumn ButtonType="ImageButton" UniqueName="ExpandColumn"<HeaderStyle Width="19px"></HeaderStyle>

</ExpandCollapseColumn>. . .

</MasterTableView><GroupHeaderItemStyle BorderColor="Black" BackColor="Silver"></GroupHeaderItemStyle><GroupPanel Visible="False"></GroupPanel><PagerStyle Mode="NumericPages"></PagerStyle>

</radg:radgrid>

In Codebehind:protected void CheckChanged(Object sender, System.EventArgs e)

{CheckBox box = (CheckBox)sender;GridDataItem item = (GridDataItem)box.NamingContainer;Hashtable target = null;

if(item.OwnerTableView.DataMember == "Customers"){

target = CustomersChecked;}

else if(item.OwnerTableView.DataMember == "Customers1"){

target = Customers1Checked;}

else{

target = Customers2Checked;}

if(box.Checked){

target[item["CustomerID"].Text] = true;}

else{

target[item["CustomerID"].Text] = null;}

}

. . . private Hashtable CustomersChecked

{

r.a.d.grid v3.0 | 47

© 2002-2006, telerik. All Rights Reserved.

Page 48: r.a.d.grid v3

The full code for this example can be found here (http://www.telerik.com/Default.aspx?PageId=2514&b454K=qa8&b454T=Rff).

Structure ColumnsAll columns, which are added by r.a.d.grid automatically to facilitate some functionality are called Structure Columns. They fall in three categories:

6.2.1.8 GridExpandColumnThis column appears when the grid has a hierarchical structure, to facilitate the expand/collapse functionality. The expand column is always placed in front of all other grid content columns and can not be moved. You can also manually add other instances of this type of column.

get{

object res = ViewState["_cc"]; if(res == null){

res = new Hashtable();ViewState["_cc"] = res;

}

return (Hashtable)res;}

}

private Hashtable Customers1Checked{

get{

object res = ViewState["_cc1"]; if(res == null){

res = new Hashtable();ViewState["_cc1"] = res;

}

return (Hashtable)res;}

}

private Hashtable Customers2Checked{

get{

object res = ViewState["_cc2"]; if(res == null){

res = new Hashtable();ViewState["_cc2"] = res;

}

return (Hashtable)res;}

}

r.a.d.grid v3.0 | 48

© 2002-2006, telerik. All Rights Reserved.

Page 49: r.a.d.grid v3

6.2.1.9 GridGroupSplitterColumnThis column appears when grouping is enabled, to facilitate the expand/collapse functionality. The group splitter column is always placed first and can not be moved.

6.2.1.10 GridRowIndicatorColumnThis column facilitates row resizing.

Column elements

6.2.2 Using Columns

r.a.d.grid v3.0 | 49

© 2002-2006, telerik. All Rights Reserved.

Page 50: r.a.d.grid v3

6.2.2.1 HeaderThe Header is the cell on the top of each grid column. The Header remains persistent along the pages of the grid. Header cells always appear for all grid columns.

The Header element is represented by the GridHeaderItem object. If you want to have a Header element for your columns, you need to set the ShowHeader Property to true.

Then you can customize the Header appearance using the r.a.d.grid property builder (Section 9.1) or Header Style section of the r.a.d.grid property grid.

It can also provide some special functions as sorting (Section 13.4) if the AllowSorting Property is set to true.

Using the Header cells you can reorder columns simply by dragging and dropping them. All you need to do is to set AllowColumnsReorder Property to true.

Headers also allow you to resize columns. You will have to set AllowColumnResize Property to true. Resizing is performed client-side.

6.2.2.2 ItemsColumn Items are the regular data cells of the grid. Neighboring items form a single row (Section 6.3).

6.2.2.3 Footer The Footer element of a row is similar to the Header element, but it is placed at the bottom of the grid. It cannot provide header-specific functions like reordering, resizing and sorting of columns. Rather than that you can use the Footer row for showing some summary information for example.In order to have a Footer row in your grid you need to set the ShowFooter Property to true. Then you can customize the Footer appearance using the r.a.d.grid property builder (Section 9.1) or Footer Style section of the r.a.d.grid property grid.

Accessing values in columnsDepending on visibility and rendering properties for GridBoundColumn (Display, Visible, ReadOnlysee this (Section 6.2.1) topic for details) there are different ways to access the column value. Details about how to access the column value you can find in Accessing Columns (Section 13.1) topic.

Sort Expressionsr.a.d.grid supports sorting of column items elements. In order to have sorting enabled, you need to set the AllowSorting Property to true. The sort expressions are described in details in Sorting (Section 13.4) topic.

Group by ExpressionsIn r.a.d.grid you can group the items of a single column (and all grid respectively) just like in Microsoft Outlook®.

Group-by expressions are described in details in Grouping (Section 13.3) topic

FilteringEach column provides independent filter menu which allows filtering the whole r.a.d.grid. The filtering expressions depend on the DataType property for each column. This property is set automatically by r.a.d.grid based on the data source for each column. By default the DataType for columns is String. For details refer to Filtering Overview (Section 13.6) topic.

Client-side OperationsSome of the operations related to grid columns are performed client-side (without postback to the server), which significantly optimizes the grid performance. If you want to have reordering and resizing functionality in your grid, you will need to have the Header element enabled.

6.2.2.4 ReorderingYou can set the order of the grid columns by simply arranging them using drag and drop. All you need to do is to set the AllowColumnsReorder Property to true.

r.a.d.grid v3.0 | 50

© 2002-2006, telerik. All Rights Reserved.

Page 51: r.a.d.grid v3

6.2.2.5 ResizingTo resize columns you need to click the handle between the headers of two columns and drag sideways.

Columns in Edit ModeWhen the grid is in edit mode it changes the appearance of some cells. For example, bound columnswill become text-boxes, which allow users to edit the data.

Column editors and the ways to can implement you own custom editor are described in Editors In Grid Columns (Section 8.7) topic.

Adding Columns ProgrammaticallyYou can programmatically add columns in the codebehind by adding column objects to the GridTableView.Columns collection.

Rows in r.a.d.grid are presented by the GridItem objects and its descendants. Each row in the grid represents a record from the specified DataSource. Each GridTableView has a set of rows (Itemscollection) of type GridItem. The collection does not provide any methods to add or remove items. However, you can control the content of an item by providing a handler for the ItemCreated event.

Row TypesGenerally there are two types of rows (items):

l Static rows

l Dynamic rows

6.3.1 Static RowsThese rows are always present in the grid structure regardless of whether they are visible or not. The

You should never use the RenderColumns Property or AutoGeneratedColumns Property to add columns to r.a.d.grid.

GridBoundColumn boundColumn;boundColumn = new GridBoundColumn();boundColumn.DataField = "CustomerID";boundColumn.HeaderText = "CustomerID";this.RadGrid1.MasterTableView.Columns.Add(boundColumn);

Dim boundColumn As GridBoundColumnboundColumn = New GridBoundColumn()boundColumn.DataField = "CustomerID"boundColumn.HeaderText = "CustomerID"Me.RadGrid1.MasterTableView.Columns.Add(boundColumn)

Note that MasterTableView and RadGrid's Columns collections are equivalent. The reason for their co-existence is the backward compatibility between the different grid versions. You can access/modify each of these collections as the result would be the same.

6.3 Rows

Please note that:

l only items bound to the data source (normal and alternating rows) are contained in the Telerik.WebControls.RadGrid.Items collection. The header, footer, and separator are not included in the collection.

l the ItemsHierarchy collection contains all items of the owners GridTablesView and all items of the children views.

l the Items property of RadGrid is a reference to the ItemsHierarchy property of its MasterTableView.

r.a.d.grid v3.0 | 51

© 2002-2006, telerik. All Rights Reserved.

Page 52: r.a.d.grid v3

number of these items is always known. To this group belong Header (Section 6.2.2) row, Footer (Section 6.2.2) row, and Pager row (see below).

6.3.2 Dynamic RowsThe number of these items depends on the number of rows (records) in the Data Source and the number of groups (if the grouping (Section 13.3) is enabled). To this group belong data items, nested-view items, group-header items and edit-form items.

If you have a hierarchical grid each item in GridTableView's Items collection has a child item of type GridNestedViewItem that has a set of detail tables. So if you want to access, for example, the nested table view of the first item in the grid's master table you should have the following code:

Or if you have a reference to an instance of an item in a child table and if you want to access the parent table view you have to write the following code:

l Normal Rows - these are the odd rows of the grid (rows 1 and 3 on the picture below). The appearance of the normal rows is controlled by the ItemStyle property.

l Alternating Rows - these are the even rows of the grid (rows 2 and 4 on the picture below). The appearance of the alternating rows is controlled by the AlternatingItemStyle property.

Such division of the grid rows will help you easily customize its appearance and improve data readability. You can set the appearance of the normal and alternating rows programmatically or in the grid declaration:

Example:

Both ItemStyle and AlternatingItemStyle are of type GridTableItemStyle. All public properties for customization are in the list of GridTableItemStyle members.

6.3.3 Pager RowThe Pager is a row, which contains the paging navigation. If you want to have your data divided in pages, you should set the AllowPaging Property to true.

You can define the style of the Pager Row using the r.a.d.grid property builder (Section 9.1) or Pager Style section of the r.a.d.grid property grid.

Row StatesThere are two special types of Row States:

l selected rows

l rows in edit mode

RadGrid1.MasterTableView.Items[0].ChildItem.NestedTableViews[0];

childItem.OwnerTableView.ParentItem.OwnerTableView;

// code...RadGrid RadGrid1 = new RadGrid();RadGrid1.AlternatingItemStyle.BackColor = Color.Orange;RadGrid1.ItemStyle.BackColor = Color.White;...// declaration<radG:RadGrid runat="server" ... /><AlternatingItemStyle BackColor="Orange" ... /><ItemStyle BackColor="White" ... />

r.a.d.grid v3.0 | 52

© 2002-2006, telerik. All Rights Reserved.

Page 53: r.a.d.grid v3

Below is an example of a selected row:

The style of the selected row is defined by the SelectedItemStyle property.

Example:

Below is an example of a row in edit mode:

The style of the edited row is defined by the EditItemStyle property.

Example:

Row OperationsYou can allow row resizing by setting the AllowRowResize Property to true. When you set this property, r.a.d.grid automatically generates a column of type GridRowIndicatorColumn. This column represents the handles for row resizing.

You can select a row when you set the AllowRowSelect property to true. In r.a.d.grid you can even select several rows if AllowMultiRowSelection is set to true.

// declaration<radG:RadGrid runat="server" ... /><SelectedItemStyle BackColor="Blue" ... />// code...RadGrid RadGrid1 = new RadGrid();RadGrid1.SelectedItemStyle.BackColor = Color.Blue;...

// declaration<radG:RadGrid runat="server" ... /><EditItemStyle BackColor="Red" ... />

// code...RadGrid RadGrid1 = new RadGrid();RadGrid1.EditItemStyle.BackColor = Color.Red;...

r.a.d.grid v3.0 | 53

© 2002-2006, telerik. All Rights Reserved.

Page 54: r.a.d.grid v3

6.4 Most Important Properties

Property Description

RadGrid.MasterTableView

The main grid table - in the general case, when there is no hierarchy, only RadGrid.MasterTableView is rendered. You can think of this table as if it is the grid itself. MasterTableView and generally all table-views in the hierarchy use the style, client behavior and other settings applied to RadGrid, unless explicitly specified otherwise.

GridTableView.DetailTablesThis collection is used for defining the hierarchical structure of RadGrid.

RadGrid.ClientSettings

Set various client-side appearance and behavior options. SeeRadGridTable client-side API (Section 12.3) for details.

RadGrid.*StyleProperties that control the visual appearance of RadGrid and all tables in the hierarchy.

GridDataTable.*Style properties

Properties that control the visual appearance of GridDataTable and all tables in the hierarchy.

GridTableView.GroupByExpressions Add or remove objects to this collection to set grouping programmatically.

GridTableView.SortExpressionsAdd or remove objects to this collection to set sorting programmatically.

GridTableView.ColumnsGridTableView.AutoGeneratedColumnsGridTableView.RenderColumns

Properties to access runtime columns. Columns are set by default in design mode.AutoGeneratedColumns - are automatically generated columnsRenderColumns - all columns - columns+ AutoGenerated (if any) + structure columns -expand/collapse and group-splitters

Instead of setting properties for each GridTableView, you can use RadGrid global properties for:PageSize, AllowSorting, AllowPaging , AllowCustomPaging, ShowFooter, ShowHeader, BackColor, BorderColor, PagerStyle.Thus they will be set for each table in the hierarchy, unless specified otherwise.

6.5 Most Important Events

r.a.d.grid v3.0 | 54

© 2002-2006, telerik. All Rights Reserved.

Page 55: r.a.d.grid v3

When working with r.a.d.grid you will probably often use the following events:

Category Event Description

Action CancelCommand Fired when the Cancel button is clicked for an item in the RadGrid control.

DeleteCommand Fired when the Delete button is clicked for an item in the RadGrid control.

EditCommand Fired when the Edit button is clicked for an item in the RadGrid control.

UpdateCommand Fired when the Update button is clicked for an item in the RadGridcontrol.

ItemCommand Fired when any button is clicked in the RadGrid control. All bubbled events from grid items fire RadGrid.ItemCommand. Those like -Edit, Delete, or Update command events can be used to handle custom data-editing in RadGrid.Expand/Collapse items in the hierarchy or GridGroupHederItem-s (if grid displays grouped items), also fired after binding of detail tables, etc.

SortCommand Fired when a column is sorted.

PageIndexChanged Fired when one of the page selection elements is clicked.

SelectedIndexChanged(inherited from GridBaseDataList)

Fired when a different item is selected in a data listing control between posts to the server.

NeedDataSource Fired when RadGrid needs a data source for rebinding.

Behavior ItemCreated Fired on the server when an item in the RadGrid control is created.

ItemDataBound Fired after an item is databound to the RadGrid control.

Data DataBinding(inherited from Control) Fired when the server control binds to a data source.

DetailTableDataBind Fired when a table from DetailTablesCollection binds to a data source.

Misc Disposed(inherited from Control) Fired when a server control is released from the memory, which is the last stage of the server control lifecycle when an ASP.NET page is requested.

Init(inherited from Control) Fired when the server control is initialized, which is the first step in its lifecycle.

Load(inherited from Control) Fired when the server control is loaded into the RadGrid object.

PreRender(inherited from Control) Fired when the server control is about to render to its containing Page object.

Unload(inherited from Control) Fired when the server control is unloaded from the memory.

r.a.d.grid v3.0 | 55

© 2002-2006, telerik. All Rights Reserved.

Page 56: r.a.d.grid v3

r.a.d.grid v3.0 | 56

© 2002-2006, telerik. All Rights Reserved.

Page 57: r.a.d.grid v3

r.a.d.grid can be defined either programmatically or in the ASPX file.

Here is the basic skeleton of a 3-leveled r.a.d.grid in ASPX form. See the comments for details.

And here is a working sample of r.a.d.grid taken from the Quick Start Framework:

7 Defining r.a.d.grid Structure

7.1 Defining r.a.d.grid in ASPX

All properties not related to the grid structure definition in this example are omitted on purpose for the sake of simplicity. You can find full example source further in this document.

<radG:RadGrid ID="RadGrid1" runat="server" ...><MasterTableView ...> //define the MasterTableView

<DetailTables> //Open the DetailTables Collection ...<radG:GridTableView runat="server" ...> //... and define a child GridTableView

<DetailTables> //Then go to the DetailTables collection of the second level GridTableView (the one defined above)...<radG:GridTableView runat="server" ...> // and set the third level GridTableView

...</radG:GridTableView>

</DetailTables></radG:GridTableView>

</DetailTables></MasterTableView>

</radG:RadGrid>

<radg:radgrid id="RadGrid1" runat="server"CssClass= "RadGrid" Width="100%" AutoGenerateColumns="False" PageSize=AllowMultiRowSelection= "False" AllowPaging="True" GridLines="None" AllowFilteringByColumn=<PagerStyle Mode="NumericPages" CssClass="Pager"></PagerStyle><HeaderStyle CssClass="Header"></HeaderStyle><ItemStyle CssClass="Row"></ItemStyle><AlternatingItemStyle CssClass="AltRow"></AlternatingItemStyle><MasterTableView DataKeyNames="CustomerID" AllowMultiColumnSorting="True"<DetailTables>

<radG:GridTableView DataKeyNames="OrderID" DataMember="Orders"><ParentTableRelation>

<radG:GridRelationFields DetailKeyField="CustomerID" MasterKeyField=</ParentTableRelation><DetailTables>

<radG:GridTableView DataKeyNames="OrderID" DataMember="OrderDetails"<ParentTableRelation>

<radG:GridRelationFields DetailKeyField="OrderID"</ParentTableRelation><Columns>

<radG:GridBoundColumn SortExpression="UnitPrice"DataField= "UnitPrice">

</radG:GridBoundColumn><radG:GridBoundColumn SortExpression="Quantity" HeaderText=

DataField= "Quantity"></radG:GridBoundColumn><radG:GridBoundColumn SortExpression="Discount" HeaderText=

DataField= "Discount"></radG:GridBoundColumn>

</Columns><SortExpressions>

<radG:GridSortExpression FieldName="Quantity" SortOrder=</SortExpressions><ItemStyle BackColor="#A7B986"></ItemStyle><HeaderStyle CssClass="Header1"></HeaderStyle><AlternatingItemStyle BackColor="#D9E8C4"></AlternatingItemStyle>

</radG:GridTableView></DetailTables>

r.a.d.grid v3.0 | 57

© 2002-2006, telerik. All Rights Reserved.

Page 58: r.a.d.grid v3

r.a.d.grid is a component that visualizes data obtained from a database. The data is presented in tabular view.

There are two ways to bind the grid to a data base:

l DataGrid like binding (Section 7.2.2) - You need to set the DataSource property manually in the control declaration. This property specifies the database, which will be used as a source for the grid.

l By using the NeedDataSource event (Section 7.2.3) - r.a.d.grid will call this event each time it needs a data source.

When you create your grid and bind it to a data source, you can use one of the approaches described below.

Setting The DataSource objectWhen setting the DataSource property you should bear in mind the following notes:

<Columns><radG:GridBoundColumn SortExpression="OrderID" HeaderText=

DataField= "OrderID"></radG:GridBoundColumn><radG:GridBoundColumn SortExpression="OrderDate" HeaderText=

DataField= "OrderDate"></radG:GridBoundColumn><radG:GridBoundColumn SortExpression="EmployeeID" HeaderText=

DataField= "EmployeeID"></radG:GridBoundColumn>

</Columns><SortExpressions>

<radG:GridSortExpression FieldName="OrderDate"></radG:GridSortExpression></SortExpressions><ItemStyle Height="19px" BackColor="#FCEDB0"></ItemStyle><HeaderStyle CssClass="Header2" ForeColor="#ffffff"></HeaderStyle><AlternatingItemStyle Height="19px" BackColor="#D5B96A"></AlternatingItemStyle>

</radG:GridTableView></DetailTables><Columns>

<radG:GridBoundColumn SortExpression="CustomerID" HeaderText="CustomerID"DataField= "CustomerID">

</radG:GridBoundColumn><radG:GridBoundColumn SortExpression="ContactName" HeaderText="Contact Name"

DataField= "ContactName"></radG:GridBoundColumn><radG:GridBoundColumn SortExpression="CompanyName" HeaderText="Company"

DataField= "CompanyName"></radG:GridBoundColumn>

</Columns><SortExpressions>

<radG:GridSortExpression FieldName="CompanyName"></radG:GridSortExpression></SortExpressions>

</MasterTableView><SelectedItemStyle ForeColor="White" BackColor="DarkBlue" CssClass=""

</radg:radgrid>

7.2 Data Binding

7.2.1 Data Binding

DataSource property should refer to an object of one of the following types:

System.Data.DataSet

System.Data.DataTable

r.a.d.grid v3.0 | 58

© 2002-2006, telerik. All Rights Reserved.

Page 59: r.a.d.grid v3

Using NoRecordsTemplate in r.a.d.grid Each GridTableView has a property NoRecordsTemplate. This property defines a template that will be displayed if there are no records in the assigned DataSource. There are cases in which you may want to show an empty grid rather than this template. There is a boolean property EnableNoRecordsTemplate which defines whether GridTableView will use the defined NoRecordsTemplate or not.

The NoRecordsTemplate should be populated for each detail table (in case of hierarchical grids) in the DetailTableDataBind event (see Examples For Detail Table Binding (Section 7.3.4)). You can control the visibility of the table/NoRecordsTemplate controls by using corresponding Controls(0), Controls(1) of each GridTableView. This should happen after it was data-bound.

LoadingTemplates in r.a.d.grid AJAX modeEach RadGrid has a property EnableAJAXLoadingTemplate. When this property is set to true, an animated image will be shown when the grid is loading in AJAX mode (Section 11.1). In order to enable the r.a.d.grid AJAX mode, you should set EnableAsyncRequest property to true. By default r.a.d.grid will use the loading.gif image of the selected skin.

You can also set own loading template declaratively in the ASPX file. The example below demonstrate the declarative definition of a custom loading template using Micromedia Flash object.

System.Data.DataView

DataSource property can refer also to an object-collection that implements any of these interfaces:

System.ComponentModel.IListSource

System.Collections.IList

System.Collections.IEnumerable

<radg:radgrid id="RadGrid1" runat="server"><MasterTableView>

<NoRecordsTemplate><div>MyTemplate</div>

</NoRecordsTemplate></MasterTableView>

</radg:radgrid>

<radg:radgrid id="RadGrid1" Width="100%" EnableAJAXLoadingTemplate="True" cssclass="RadGrid"enableasyncrequests="True" allowsorting="True"pagesize="5" allowpaging="True" Height="200px" runat="server"><headerstyle cssclass="GridHeader" Height="20px"/><pagerstyle mode="NumericPages" cssclass="GridPager" Height="20px" /><itemstyle cssclass="GridRow" /><alternatingitemstyle cssclass="GridRow" /><MasterTableView CssClass="MasterTable" Height="100%" ></MasterTableView>

</radg:radgrid>

<radg:radgrid id="RadGrid2" Width="100%" EnableAJAXLoadingTemplate="True" cssclass="RadGrid"pagesize="5" allowpaging="True" Height="200px" runat="server"><AJAXLoadingTemplate>

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0"<param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="loading.swf" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#ffffff" /><embed src="loading.swf" quality="high" wmode="transparent" bgcolor="#ffffff"

</object></AJAXLoadingTemplate><headerstyle cssclass="GridHeader" Height="20px" /><pagerstyle mode="NumericPages" cssclass="GridPager" Height="20px"/><itemstyle cssclass="GridRow" /><alternatingitemstyle cssclass="GridRow" />

r.a.d.grid v3.0 | 59

© 2002-2006, telerik. All Rights Reserved.

Page 60: r.a.d.grid v3

1. Set the DataSource property. This property points the database which will be used as a source to r.a.d.grid.

2. Call the DataBind() method when appropriate.For example you can call it on the first page load (after postback r.a.d.grid uses the viewstate to recreate the data), or after handling some event (sort event for example).

<MasterTableView CssClass="MasterTable" Height="100%" ></MasterTableView></radg:radgrid>

7.2.2 DataGrid Like Binding

Simple data-binding through the DataBind() method can be used in simple scenarios which does not require complex operations like insert/delete/update, grouping, hierarchy relations, etc.

C# Code private void LoadData(){

OleDbConnection MyOleDbConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source="OleDbDataAdapter MyOleDbDataAdapter = new OleDbDataAdapter();

DataSet MyDataSet = new DataSet();

MyOleDbConnection.Open();try{

MyOleDbDataAdapter.SelectCommand = new OleDbCommand("SELECT * FROM Customers", MyOleDbConnection);MyOleDbDataAdapter.Fill(MyDataSet, "Customers");

}finally{

MyOleDbConnection.Close();}

DataView myDataView = MyDataSet.Tables["Customers"].DefaultView;

RadGrid1.DataSource = myDataView;}...

private void InitializeComponent(){

this.RadGrid1.PageIndexChanged += new Telerik.WebControls.GridPageChangedEventHandler(this.RadGrid1_PageIndexChanged);this.Load += new System.EventHandler(this.Page_Load);

}...

private void RadGrid1_PageIndexChanged(object source, Telerik.WebControls.GridPageChangedEventArgs e){

this.RadGrid1.CurrentPageIndex = e.NewPageIndex;LoadData();this.RadGrid1.DataBind();

}VB.NET Code

Private Sub Page_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load If Not Me.IsPostBack Then

LoadData()RadGrid1.DataBind()

End If End Sub 'Page_Load

... Private Sub LoadData()

r.a.d.grid v3.0 | 60

© 2002-2006, telerik. All Rights Reserved.

Page 61: r.a.d.grid v3

r.a.d.grid fires this event each time it needs to be bound to a data source.

This could happen in some of these cases:

l Right after OnLoad, r.a.d.grid checks the viewstate for stored grid-related information. If such information is missing (when the page loads for the first time) the NeedDataSource event is fired. This also means that if MasterTableView.DataSourcePersistenceMode has been set to NoPersistence, grid would bind each time the page loads (not only the first time)

l After automatic sorting

l When a Paging event occurs

l When Edit command is fired

l Right after Update, Delete command event handlers finish execution. You can cancel these operations handling ItemCommand event and assigning "false" to the event argument's Cancel property

l When Grouping / ungrouping - right after RadGrid.GroupsChanging event.

l When Resorting a group

l When a call to the Rebind() method takes place

l Prior to any detail table binds

l And after some other specific cases.

The advantages of using this event are that the developer does not need to write any code handling the logic about when and how the data-binding should take place. It is still the developer's responsibility to properly construct a data source object and assign it to the RadGrid's DataSource property.

In the code of this event you should prepare the data source (list of objects) for r.a.d.grid and assign it to grid's DataSource property.

Dim MyOleDbConnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" Dim MyOleDbDataAdapter As New OleDbDataAdapter()

Dim MyDataSet As New DataSet()

MyOleDbConnection.Open()Try

MyOleDbDataAdapter.SelectCommand = New OleDbCommand("SELECT * FROM Customers"MyOleDbDataAdapter.Fill(MyDataSet, "Customers")

FinallyMyOleDbConnection.Close()

End Try

Dim myDataView As DataView = MyDataSet.Tables("Customers").DefaultView

RadGrid1.DataSource = myDataView End Sub 'LoadData

... Private Sub RadGrid1_PageIndexChanged([source] As Object, e As Telerik.WebControls.GridPageChangedEventArgs) Handles RadGrid1.PageIndexChanged

Me.RadGrid1.CurrentPageIndex = e.NewPageIndexLoadData()

Me.RadGrid1.DataBind() End Sub 'RadGrid1_PageIndexChanged

7.2.3 Using NeedDataSource Event

<radG:RadGrid ID="RadGrid1"OnNeedDataSource= "RadGrid1_NeedDataSource"Runat= "server">

</radG:RadGrid>

VB.NET CodePrivate Sub RadGrid1_NeedDataSource(ByVal [source] As Object, ByVal e As Telerik.WebControls.GridNeedDataSourceEventArgs)

r.a.d.grid v3.0 | 61

© 2002-2006, telerik. All Rights Reserved.

Page 62: r.a.d.grid v3

A unique feature for r.a.d.grid is the support for hierarchical representation of related data tables (DataSet).

Dim MyOleDbConnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" Dim MyOleDbDataAdapter As New OleDbDataAdapterMyOleDbDataAdapter.SelectCommand = New OleDbCommand("SELECT * FROM Customers" Dim myDataTable As New DataTableMyOleDbConnection. Open()Try

MyOleDbDataAdapter.Fill(myDataTable)Finally

MyOleDbConnection. Close() End TryRadGrid1.DataSource = myDataTable

End SubC# Codeprivate void RadGrid1_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e){

OleDbConnection MyOleDbConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source="OleDbDataAdapter MyOleDbDataAdapter = new OleDbDataAdapter();MyOleDbDataAdapter.SelectCommand = new OleDbCommand("SELECT * FROM Customers"DataTable myDataTable = new DataTable();MyOleDbConnection. Open();try

{MyOleDbDataAdapter.Fill(myDataTable);

}finally

{MyOleDbConnection. Close();

}

RadGrid1.DataSource = myDataTable;}

7.3 Hierarchical Grid

7.3.1 Hierarchical Views

r.a.d.grid v3.0 | 62

© 2002-2006, telerik. All Rights Reserved.

Page 63: r.a.d.grid v3

Master Tabler.a.d.grid introduces a new approach to hierarchical data structures. The innovative in r.a.d.grid is having a so called MasterTableView. This is the topmost table of the hierarchical structure. It is a GridTableView Class with GridTableViewCollection Class. The collection holds the so called DetailTables - tables related to the fields of the MasterTable. Each DetailTable can have its own GridTableViewCollection with other Detail Tables, thus forming the hierarchical structure.

You can look on the MasterTable as a Root for the hierarchical tree. All tables underneath will be the tree nodes. As the MasterTable is on its turn a Collection it has own sections of properties in Visual Studio.

Detail Tables

Detail tables are the inner tables of the grid. They are related to a field in its parent table.

Each Detail Table is placed in an item (row) of its parent table. This special item is called NestedViewItem .

Note: There is only one MasterTable for a single r.a.d.grid . This is the topmost table. All inner tables are referred as a Detail Tables regardless of whether they have related (inner) tables or not.

r.a.d.grid v3.0 | 63

© 2002-2006, telerik. All Rights Reserved.

Page 64: r.a.d.grid v3

r.a.d.grid allows to set for each detail table its own appearance options (header, footer, paging enabled, etc).

Here are the basic steps that you need to follow in order to create r.a.d.grid dynamically in the codebehind.

1. Create the grid dynamically in the PageInit handler of the page (calling its constructor).

2. Attach the NeedDataSource and DetailTableDataBind events to the control right after you instantiate the grid.

3. Specify the preferred settings for your grid instance through its properties.

4. Create columns for the grid dynamically. Keep in mind that you have to first set their properties and then add them to the MasterTableView/GridTableView collection. Thus their ViewState will be properly persisted (as LoadViewState is raised after the Init event of the page)

5. Set properly ParentTableRelations for the GridTableViews (along with their MasterKeyField and DetailKeyField attributes) and DataKeyNames for the MasterTableView/GridTableViews in the code behind of the page.

6. Assign datasources for the grid tables in the NeedDataSource/DetailTableDataBind handlers of the grid. In DetailTableDataBind you can determine which datasource should be related to the currently bound GridTableView by checking its DataMember property (under.NET 1.x).Here the DataMember property must have unique value for each detail table (this value has to be defined previously by the developer) and the DataSourceID is the ID of the DataSource control responsible for the corresponding detail table content generation.

Here is a complete source code sample:

You can have all tables that have child tables in your grid expanded after each postback by setting the HierarchyDefaultExpanded property of the grid MasterTableView to true.

7.3.2 Creating Hierarchical Grid Dynamically

[VB.NET]Imports System.Data.SqlClientImports Telerik.WebControlsImports System.Data.OleDb

Public Class TwoTablesAtLevelInherits System.Web.UI.Page

r.a.d.grid v3.0 | 64

© 2002-2006, telerik. All Rights Reserved.

Page 65: r.a.d.grid v3

#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

End SubProtected WithEvents PlaceHolder1 As System.Web.UI.WebControls.PlaceHolderProtected WithEvents RadGrid1 As Telerik.WebControls.RadGrid

'NOTE: The following placeholder declaration is required by the Web Form Designer. 'Do not delete or move it. Private designerPlaceholderDeclaration As System.Object

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init 'CODEGEN: This method call is required by the Web Form Designer 'Do not modify it using the code editor.InitializeComponent()DefineGridStructure()

End Sub

#End Region

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub Private Sub DefineGridStructure()

Me.RadGrid1 = New RadGrid

AddHandler Me.RadGrid1.NeedDataSource, New GridNeedDataSourceEventHandler(AddressOf Me.RadGrid1.CssClass = "RadGrid" Me.RadGrid1.Width = Unit.Percentage(100) Me.RadGrid1.PageSize = 5 Me.RadGrid1.AllowPaging = True Me.RadGrid1.AutoGenerateColumns = False Me.RadGrid1.MasterTableView.DataMember = "Orders" Me.RadGrid1.MasterTableView.DataKeyNames = New String() {"CustomerID", "EmployeeID" Me.RadGrid1.MasterTableView.PageSize = 15

Dim column1 As New GridBoundColumncolumn1.DataField = "OrderID"column1.HeaderText = "OrderID"

Me.RadGrid1.MasterTableView.Columns.Add(column1)

column1 = New GridBoundColumncolumn1.DataField = "OrderDate"column1.HeaderText = "Date Ordered"

Me.RadGrid1.MasterTableView.Columns.Add(column1)

column1 = New GridBoundColumncolumn1.DataField = "EmployeeID"column1.HeaderText = "EmployeeID"

Me.RadGrid1.MasterTableView.Columns.Add(column1)

Dim view1 As New GridTableView(Me.RadGrid1)view1.DataKeyNames = New String() {"CustomerID"}view1.DataMember = "Customers"

Me.RadGrid1.MasterTableView.DetailTables.Add(view1)

Dim field As GridRelationFields = New GridRelationFieldsfield.MasterKeyField = "CustomerID"field.DetailKeyField = "CustomerID"view1.ParentTableRelation.Add(field)

column1 = New GridBoundColumn

r.a.d.grid v3.0 | 65

© 2002-2006, telerik. All Rights Reserved.

Page 66: r.a.d.grid v3

column1.DataField = "CustomerID"column1.HeaderText = "CustomerID"view1.Columns.Add(column1)

column1 = New GridBoundColumncolumn1.DataField = "ContactName"column1.HeaderText = "ContactName"view1.Columns.Add(column1)

column1 = New GridBoundColumncolumn1.DataField = "CompanyName"column1.HeaderText = "Company"view1.Columns.Add(column1)

Me.PlaceHolder1.Controls.Add(Me.RadGrid1) End Sub Public Sub RadGrid1_NeedDataSource(ByVal source As System.Object, ByVal e As Telerik.WebControls.GridNeedDataSourceEventArgs)

Dim MyOleDbConnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" Dim daOrders As New OleDbDataAdapter Dim daCustomers As New OleDbDataAdapter Dim daEmployee As New OleDbDataAdapter Dim dtOrders As New DataTable Dim dtCustomers As New DataTable Dim dtEmployees As New DataTable

MyOleDbConnection. Open() If Not e.IsFromDetailTable Then

daOrders.SelectCommand = New OleDbCommand("SELECT * FROM Orders", MyOleDbConnection)Try

daOrders.Fill(dtOrders)Finally

MyOleDbConnection. Close() End Try

RadGrid1.DataSource = dtOrders Else

daCustomers.SelectCommand = New OleDbCommand("SELECT * FROM Customers", MyOleDbConnection)daCustomers.Fill(dtCustomers)MyOleDbConnection. Close()RadGrid1.MasterTableView.DetailTables(0).DataSource = dtCustomers

daEmployee.SelectCommand = New OleDbCommand("SELECT EmployeeID, LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate FROM Employees"daEmployee.Fill(dtEmployees)MyOleDbConnection. Close()RadGrid1.MasterTableView.DetailTables(1).DataSource = dtEmployees

MyOleDbConnection. Close() End If

End SubEnd Class

[C#]using System.Data.SqlClient;using Telerik.WebControls;using System.Data.OleDb;public class TwoTablesAtLevel : System.Web.UI.Page {

protected System.Web.UI.WebControls.PlaceHolder PlaceHolder1;

protected Telerik.WebControls.RadGrid RadGrid1;

r.a.d.grid v3.0 | 66

© 2002-2006, telerik. All Rights Reserved.

Page 67: r.a.d.grid v3

// This call is required by the Web Form Designer.[System.Diagnostics.DebuggerStepThrough()]

private void InitializeComponent() {}

private void Page_Init(object sender, System.EventArgs e) {// CODEGEN: This method call is required by the Web Form Designer// Do not modify it using the code editor.InitializeComponent();DefineGridStructure();

}

private void Page_Load(object sender, System.EventArgs e) {}

private void DefineGridStructure() {this.RadGrid1 = new RadGrid();this.RadGrid1.NeedDataSource += new GridNeedDataSourceEventHandler(// TODO: Warning!!!! NULL EXPRESSION DETECTED....);this.RadGrid1.CssClass = "RadGrid";this.RadGrid1.Width = Unit.Percentage(100);this.RadGrid1.PageSize = 5;this.RadGrid1.AllowPaging = true;this.RadGrid1.AutoGenerateColumns = false;this.RadGrid1.MasterTableView.DataMember = "Orders";this.RadGrid1.MasterTableView.DataKeyNames = new string[] {

"CustomerID", "EmployeeID"};

this.RadGrid1.MasterTableView.PageSize = 15;GridBoundColumn column1 = new GridBoundColumn();column1.DataField = "OrderID";column1.HeaderText = "OrderID";this.RadGrid1.MasterTableView.Columns.Add(column1);column1 = new GridBoundColumn();column1.DataField = "OrderDate";column1.HeaderText = "Date Ordered";this.RadGrid1.MasterTableView.Columns.Add(column1);column1 = new GridBoundColumn();column1.DataField = "EmployeeID";column1.HeaderText = "EmployeeID";this.RadGrid1.MasterTableView.Columns.Add(column1);GridTableView view1 = new GridTableView(this.RadGrid1);view1.DataKeyNames = new string[] {

"CustomerID"};view1.DataMember = "Customers";this.RadGrid1.MasterTableView.DetailTables.Add(view1);GridRelationFields field = new GridRelationFields();field.MasterKeyField = "CustomerID";field.DetailKeyField = "CustomerID";view1.ParentTableRelation.Add(field);column1 = new GridBoundColumn();column1.DataField = "CustomerID";column1.HeaderText = "CustomerID";view1.Columns.Add(column1);column1 = new GridBoundColumn();column1.DataField = "ContactName";column1.HeaderText = "ContactName";view1.Columns.Add(column1);column1 = new GridBoundColumn();column1.DataField = "CompanyName";column1.HeaderText = "Company";view1.Columns.Add(column1);this.PlaceHolder1.Controls.Add(this.RadGrid1);

}

public void RadGrid1_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e) {OleDbConnection MyOleDbConnection = new OleDbConnection(("Provider=Microsoft.Jet.OLEDB.4.0; Data Source="

r.a.d.grid v3.0 | 67

© 2002-2006, telerik. All Rights Reserved.

Page 68: r.a.d.grid v3

There are two general steps to implement a hierarchical grid.

1. Design the Grid HierarchyThe first step when creating hierarchical grids is to specify the structure of the hierarchical tables. This step must be completed before binding the data.

This is related to populating the collection of DetailTables of RadGrid.MasterTableView and the respective columns. It is important that this step be completed before RadGrid is bound to any data. For example a grid can have a structure like this:

MasterTableView and DetailTable are controls of type GridTableView. They are represented by an HTML table (runtime) object. This object has a Column, AutoGeneratedColumn collections, properties for setting styles, etc.

The whole structure of RadGrid with its detail tables is saved in the ViewState. If you build programmatically the grid, you can safely define the structure in Page_Load event handler if there was no PostBack.

OleDbDataAdapter daOrders = new OleDbDataAdapter();OleDbDataAdapter daCustomers = new OleDbDataAdapter();OleDbDataAdapter daEmployee = new OleDbDataAdapter();DataTable dtOrders = new DataTable();DataTable dtCustomers = new DataTable();DataTable dtEmployees = new DataTable();MyOleDbConnection. Open();

if (!e.IsFromDetailTable) {daOrders.SelectCommand = new OleDbCommand("SELECT * FROM Orders", MyOleDbConnection);try {

daOrders.Fill(dtOrders);}finally {

MyOleDbConnection. Close();}RadGrid1.DataSource = dtOrders;

} else {

daCustomers.SelectCommand = new OleDbCommand("SELECT * FROM Customers", MyOleDbConnection);daCustomers.Fill(dtCustomers);MyOleDbConnection. Close();RadGrid1.MasterTableView.DetailTables(0).DataSource = dtCustomers;daEmployee.SelectCommand = new OleDbCommand("SELECT EmployeeID, LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate FROM Employees"daEmployee.Fill(dtEmployees);MyOleDbConnection. Close();RadGrid1.MasterTableView.DetailTables(1).DataSource = dtEmployees;MyOleDbConnection. Close();

}}

}

7.3.3 Binding Hierarchical Grids

- MasterTableView - DetailTable(0)

- DetailTable(0, 0)

C# Codeprivate void DefineGridStructure(){

this.RadGrid1 = new RadGrid();

this.RadGrid1.NeedDataSource += new GridNeedDataSourceEventHandler(this.RadGrid1_NeedDataSource);this.RadGrid1.DetailTableDataBind += new GridDetailTableDataBindEventHandler(this.RadGrid1_DetailTableDataBind);

this.RadGrid1.CssClass = "RadGrid";

r.a.d.grid v3.0 | 68

© 2002-2006, telerik. All Rights Reserved.

Page 69: r.a.d.grid v3

this.RadGrid1.Width = Unit.Percentage(100);this.RadGrid1.PageSize = 5;this.RadGrid1.AllowPaging = true;this.RadGrid1.AutoGenerateColumns = false;

this.RadGrid1.MasterTableView.DataMember = "Customers";this.RadGrid1.MasterTableView.PageSize = 15;

GridBoundColumn boundColumn;boundColumn = new GridBoundColumn();boundColumn.DataField = "CustomerID";boundColumn.HeaderText = "CustomerID";this.RadGrid1.MasterTableView.Columns.Add(boundColumn);

boundColumn = new GridBoundColumn();boundColumn.DataField = "ContactName";boundColumn.HeaderText = "Contact Name";this.RadGrid1.MasterTableView.Columns.Add(boundColumn);

this.RadGrid1.MasterTableView.Columns.Add( new GridExpandColumn() );

this.RadGrid1.MasterTableView.GroupByExpressions.Add( new GridGroupByExpression("Country Group By Country"

GridTableView tableViewOrders = new GridTableView(RadGrid1);tableViewOrders.DataMember = "Orders";this.RadGrid1.MasterTableView.DetailTables.Add( tableViewOrders );

boundColumn = new GridBoundColumn();boundColumn.DataField = "OrderID";boundColumn.HeaderText = "OrderID";tableViewOrders.Columns.Add(boundColumn);

boundColumn = new GridBoundColumn();boundColumn.DataField = "OrderDate";boundColumn.HeaderText = "Date Ordered";tableViewOrders.Columns.Add(boundColumn);

GridTableView tableViewOrderDetails = new GridTableView(RadGrid1);tableViewOrderDetails.DataMember = "OrderDetails";tableViewOrders.DetailTables.Add( tableViewOrderDetails );

boundColumn = new GridBoundColumn();boundColumn.DataField = "UnitPrice";boundColumn.HeaderText = "Unit Price";tableViewOrderDetails.Columns.Add(boundColumn);

boundColumn = new GridBoundColumn();boundColumn.DataField = "Quantity";boundColumn.HeaderText = "Quantity";tableViewOrderDetails.Columns.Add(boundColumn);

this.PlaceHolder1.Controls.Add( RadGrid1 );

}

VB.NET CodePrivate Sub DefineGridStructure() Me.RadGrid1 = New RadGrid

AddHandler Me.RadGrid1.NeedDataSource, New GridNeedDataSourceEventHandler(AddressOfAddHandler Me.RadGrid1.DetailTableDataBind, New GridDetailTableDataBindEventHandler(

Me.RadGrid1.CssClass = "RadGrid" Me.RadGrid1.Width = Unit.Percentage(100) Me.RadGrid1.PageSize = 5

r.a.d.grid v3.0 | 69

© 2002-2006, telerik. All Rights Reserved.

Page 70: r.a.d.grid v3

(http://www.telerik.com/r.a.d.grid/Default.aspx?Tab=Examples&Example=Programming/GroupBy)

2. Binding Detail Tables RuntimeAt runtime, when binding the data, RadGrid builds the structure of items (grid rows), with respect of the structure of the detail tables as it was defined in Step 1. RadGrid will create a new control GridTableView for each item in the master table. Then RadGrid will assign it as a child of the master item. This control will be a copy of the corresponding table - this should be DetailTable(0). So for example if you have 3 items in the MasterTableView in the second level of hierarchy the grid will look like this:

Me.RadGrid1.AllowPaging = True Me.RadGrid1.AutoGenerateColumns = False Me.RadGrid1.MasterTableView.DataMember = "Customers" Me.RadGrid1.MasterTableView.PageSize = 15

Dim column1 As New GridBoundColumncolumn1.DataField = "CustomerID"column1.HeaderText = "CustomerID"

Me.RadGrid1.MasterTableView.Columns.Add(column1) column1 = New GridBoundColumncolumn1.DataField = "ContactName"column1.HeaderText = "Contact Name"

Me.RadGrid1.MasterTableView.Columns.Add(column1) Dim view1 As New GridTableView(Me.RadGrid1)view1.DataMember = "Orders"

Me.RadGrid1.MasterTableView.DetailTables.Add(view1) column1 = New GridBoundColumncolumn1.DataField = "OrderID"column1.HeaderText = "OrderID"view1.Columns.Add(column1)

column1 = New GridBoundColumncolumn1.DataField = "OrderDate"column1.HeaderText = "Date Ordered"view1.Columns.Add(column1)

Dim view2 As New GridTableView(Me.RadGrid1)view2.DataMember = "OrderDetails"view1.DetailTables.Add(view2)

column1 = New GridBoundColumncolumn1.DataField = "UnitPrice"column1.HeaderText = "Unit Price"view2.Columns.Add(column1)

column1 = New GridBoundColumncolumn1.DataField = "Quantity"column1.HeaderText = "Quantity"view2.Columns.Add(column1)

Me.PlaceHolder1.Controls.Add(Me.RadGrid1)

End Sub

MasterTableView+ Item(0)

DetailTable0 (copy 0)+ Item(1)

DetailTable0 (copy 1)+ Item(2)

DetailTable0 (copy 2)

r.a.d.grid v3.0 | 70

© 2002-2006, telerik. All Rights Reserved.

Page 71: r.a.d.grid v3

In this structure Item(0) is the parent item for DetailTable(0). You can get its instance using the GridTableView.ParentItem property, where GridTableView is DetailTable0 (copy 0). In our example grid structure there is third level of the hierarchy and each item of the copies of DetailTable(0) should have a detail table that is copy of DetailTable(0, 0). For example let's say that the copy of DetailTable(0) with index 0 has 2 items:

Each copy of the detail tables should be bound in order to have its item populated. RadGrid delegates the full control of how this should be done to the developer - you should filter or select just the records that correspond to each detail table. The only restriction is when this should happen. This is the DetailTableDataBind event. RadGrid fires this event for each DetailTable that is about to be bound. Firing of this event also depends on the HierarchyLoadMode (Section 13.7) of the corresponding GridTableView as stated when it is declared in Step 1.

l If the HierarchyLoadMode is set to ServerBind then the DetailTableDataBind event will be fired immediately after the corresponding parent item is bound.

l If it is ServerOnDemand the detail table will be bound as soon as its parent item is expanded.

You can determine which is detail table that is about to be databound using its DataMember property, that should be properly assigned in step 1.

When RadGrid constructs each copy of the detail tables it assigns its data-source of the grid itself. This is useful when the DataSource is a DataSet that contains all the detail table data. Then in DetailTableDataBind you can obtain the instance of the DataSet from the DataSource property of the detail table that is an argument of the event handler (referred as e.DetailTable). This is also the reason that prior to MasterTableView or any of the detail tables of RadGrid is about to be rebound RadGridfires NeedDataSource event so the developer can assign a DataSource. Note that it will be fired only once for a group of detail tables and only if the DataSource of RadGrid is not already assigned.

In order to display hierarchical data, r.a.d.grid renders one or more detail tables for each item in the MasterTableView (i.e. for each data-row that MasterTableView renders). In three level hierarchy for each item of each detail table there are one or more detail items as well. The level of hierarchy may be virtually infinite. To bind each detail table-view r.a.d.grid fires the DetailTableDataBind event. The argument carries all needed information such as the table that should be databound, parent item(s), etc.

In the code of DetailTableDataBind event handler, you should write code for constructing detail data-source (list of objects) that should be used by the table to be bound to the hierarchical structure. The DataSource should be filtered in the appropriate manner, i.e. it should contain only child-records of the one that the parent item is bound to.

Below are described the possible scenarios for table binding.

Binding r.a.d.grid DetailTable using database select

DetailTable0 (copy 0)+ Item(0)

DetailTable(0, 0) (copy 0)+ Item(1)

DetailTable(0, 0) (copy 1)

7.3.4 Examples For Detail Table Binding

Tip: You can use the DetailTableDataBind event handler to assign NoRecordsTemplate for the GridTableView. This is a template that will be displayed if there are no records in the assigned DataSource (see Data Binding (Section 7.2.1)).

VB.NET Code

Private Sub RadGrid1_DetailTableDataBind(ByVal source As Object, ByVal e As GridDetailTableDataBindEventArgs) Dim parentItem As GridDataItem = CType(e.DetailTableView.ParentItem,GridDataItem) If parentItem.Edit Then

Return End If

If (e.DetailTableView.DataMember = "OrderDetails") Then Me.dsNWind1.OrderDetails.Clear Me.daOrderDetails.SelectCommand.CommandText = ("Select * from [Order Details] where OrderID = " Me.daOrderDetails.Fill( Me.dsNWind1.OrderDetails)

r.a.d.grid v3.0 | 71

© 2002-2006, telerik. All Rights Reserved.

Page 72: r.a.d.grid v3

Binding r.a.d.grid DetailTable using DataTable.Select

Binding r.a.d.grid DetailTable using filtered DataView

End IfEnd SubC# Code

private void RadGrid1_DetailTableDataBind(object source, Telerik.WebControls.GridDetailTableDataBindEventArgs e){

GridDataItem parentItem = e.DetailTableView.ParentItem as GridDataItem; if ( parentItem.Edit ){

return;}

if ( e.DetailTableView.DataMember == "OrderDetails" ){

dsNWind1.OrderDetails.Clear();daOrderDetails.SelectCommand.CommandText = "Select * from [Order Details] where OrderID = "daOrderDetails.Fill( dsNWind1.OrderDetails);

}}

VB.NET Code

Private Sub RadGrid1_DetailTableDataBind(ByVal source As Object, ByVal e As GridDetailTableDataBindEventArgs) Dim parentItem As GridDataItem = CType(e.DetailTableView.ParentItem,GridDataItem) If parentItem.Edit Then

Return End If

If (e.DetailTableView.DataMember = "OrderDetails") Then Dim ds As DataSet = CType(e.DetailTableView.DataSource, DataSet)e.DetailTableView.DataSource = ds.Tables("OrderDetails").Select( "CustomerID = '"

End IfEnd SubC# Code

private void RadGrid1_DetailTableDataBind(object source, Telerik.WebControls.GridDetailTableDataBindEventArgs e){

GridDataItem parentItem = e.DetailTableView.ParentItem as GridDataItem; if ( parentItem.Edit ){

return;}

if ( e.DetailTableView.DataMember == "OrderDetails" ){

DataSet ds = (DataSet)e.DetailTableView.DataSource;e.DetailTableView.DataSource = ds.Tables["OrderDetails"].Select( "CustomerID = '"

}}

VB.NET Code

Private Sub RadGrid1_DetailTableDataBind(ByVal source As Object, ByVal e As GridDetailTableDataBindEventArgs) Dim parentItem As GridDataItem = CType(e.DetailTableView.ParentItem,GridDataItem) If parentItem.Edit Then

Return End If

If (e.DetailTableView.DataMember = "OrderDetails") Then Dim ds As DataSet = CType(e.DetailTableView.DataSource, DataSet) Dim dv As DataView = ds.Tables("OrderDetails").DefaultView

r.a.d.grid v3.0 | 72

© 2002-2006, telerik. All Rights Reserved.

Page 73: r.a.d.grid v3

Bind programmatically to hierarchical XML dataIf you want to add dynamically r.a.d.grid to the page, you need to do it in the OnInit event, just before loading the ViewState.

dv.RowFilter = "CustomerID = '" + parentItem("CustomerID").Text + "'"e.DetailTableView.DataSource = dv

End IfEnd SubC# Code

private void RadGrid1_DetailTableDataBind(object source, Telerik.WebControls.GridDetailTableDataBindEventArgs e){

GridDataItem parentItem = e.DetailTableView.ParentItem as GridDataItem; if ( parentItem.Edit ){

return;}

if ( e.DetailTableView.DataMember == "OrderDetails" ){

DataSet ds = (DataSet)e.DetailTableView.DataSource;DataView dv = ds.Tables["OrderDetails"].DefaultView;dv.RowFilter = "CustomerID = '" + parentItem["CustomerID"].Text + "'";e.DetailTableView.DataSource = dv;

}}

7.3.5 Bind Programmatically To Hierarchical XML Data

C# Code

private Telerik.WebControls.RadGrid RadGrid1;protected System.Web.UI.WebControls.PlaceHolder PlaceHolder1;protected System.Web.UI.WebControls.Label Label1;

private void CreateHierachicalGrid(){

this.RadGrid1 = new RadGrid();

this.RadGrid1.ShowFooter = true;this.RadGrid1.ShowHeader = false;this.RadGrid1.AutoGenerateColumns = false;this.RadGrid1.GridLines = GridLines.None;

GridTableView tableViewLevel1 = new GridTableView(RadGrid1);this.RadGrid1.MasterTableView.DetailTables.Add( tableViewLevel1 );

GridTableView tableViewLevel2 = new GridTableView(RadGrid1);tableViewLevel1.DetailTables.Add( tableViewLevel2 );

GridBoundColumn boundColumn1;boundColumn1 = new GridBoundColumn();boundColumn1.DataField = "Text";boundColumn1.HeaderText = "Text";

this.RadGrid1.MasterTableView.Columns.Add( boundColumn1 );tableViewLevel1.Columns.Add(boundColumn1);tableViewLevel2.Columns.Add(boundColumn1);

GridBoundColumn boundColumn2;boundColumn2 = new GridBoundColumn();boundColumn2.DataField = "Node_Id";boundColumn2.HeaderText = "Node_Id";

r.a.d.grid v3.0 | 73

© 2002-2006, telerik. All Rights Reserved.

Page 74: r.a.d.grid v3

boundColumn2.Visible = false;

this.RadGrid1.MasterTableView.Columns.Add( boundColumn2 );tableViewLevel1.Columns.Add(boundColumn2);tableViewLevel2.Columns.Add(boundColumn2);

GridBoundColumn boundColumn3;boundColumn3 = new GridBoundColumn();boundColumn3.DataField = "Node_Id_0";boundColumn3.HeaderText = "Node_Id_0";boundColumn3.Visible = false;

this.RadGrid1.MasterTableView.Columns.Add( boundColumn3 );tableViewLevel1.Columns.Add(boundColumn3);tableViewLevel2.Columns.Add(boundColumn3);

this.RadGrid1.NeedDataSource += new GridNeedDataSourceEventHandler(this.RadGrid1_NeedDataSource);this.RadGrid1.DetailTableDataBind += new GridDetailTableDataBindEventHandler(this.RadGrid1_DetailTableDataBind);

this.PlaceHolder1.Controls.Add( RadGrid1 );}

private void RadGrid1_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e){

DataSet ds = GetHierarchicalDsFromXml();RadGrid1.DataSource = ds.Tables[0].Select( "Node_Id_0 Is NULL" );

}

private void RadGrid1_DetailTableDataBind(object source, Telerik.WebControls.GridDetailTableDataBindEventArgs e){

DataSet ds = GetHierarchicalDsFromXml(); string parentItemId = e.DetailTableView.ParentItem["Node_Id"].Text;e.DetailTableView.DataSource = ds.Tables[0].Select("Node_Id_0 = " + parentItemId);

}

private DataSet tmpDataSet; private DataSet GetHierarchicalDsFromXml(){ if (tmpDataSet != null){

return tmpDataSet;}

this.tmpDataSet = new DataSet();XmlTextReader reader = new XmlTextReader(Server.MapPath("Tree.xml"));tmpDataSet.ReadXml(reader);

return tmpDataSet;}

VB.NET Code

Private RadGrid1 As Telerik.WebControls.RadGridProtected PlaceHolder1 As System.Web.UI.WebControls.PlaceHolderProtected Label1 As System.Web.UI.WebControls.Label

Private Sub CreateHierachicalGrid() Me.RadGrid1 = New RadGrid()

Me.RadGrid1.ShowFooter = True Me.RadGrid1.ShowHeader = False Me.RadGrid1.AutoGenerateColumns = False Me.RadGrid1.GridLines = GridLines.None

Dim tableViewLevel1 As New GridTableView(RadGrid1) Me.RadGrid1.MasterTableView.DetailTables.Add(tableViewLevel1)

r.a.d.grid v3.0 | 74

© 2002-2006, telerik. All Rights Reserved.

Page 75: r.a.d.grid v3

1. Setup the DataSourceControlsIn order to start data binding RadGrid, you need to set a separate DataSourceControl for each table in the grid (Master table and all detail tables). In case you have a three level hierarchy, you will need three DataSourceControl objects. The example below demonstrates the resulting code for setting the three controls.

Dim tableViewLevel2 As New GridTableView(RadGrid1)tableViewLevel1.DetailTables.Add(tableViewLevel2)

Dim boundColumn1 As GridBoundColumnboundColumn1 = New GridBoundColumn()boundColumn1.DataField = "Text"boundColumn1.HeaderText = "Text"

Me.RadGrid1.MasterTableView.Columns.Add(boundColumn1)tableViewLevel1.Columns.Add(boundColumn1)tableViewLevel2.Columns.Add(boundColumn1)

Dim boundColumn2 As GridBoundColumnboundColumn2 = New GridBoundColumn()boundColumn2.DataField = "Node_Id"boundColumn2.HeaderText = "Node_Id"boundColumn2.Visible = False

Me.RadGrid1.MasterTableView.Columns.Add(boundColumn2)tableViewLevel1.Columns.Add(boundColumn2)tableViewLevel2.Columns.Add(boundColumn2)

Dim boundColumn3 As GridBoundColumnboundColumn3 = New GridBoundColumn()boundColumn3.DataField = "Node_Id_0"boundColumn3.HeaderText = "Node_Id_0"boundColumn3.Visible = False

Me.RadGrid1.MasterTableView.Columns.Add(boundColumn3)tableViewLevel1.Columns.Add(boundColumn3)tableViewLevel2.Columns.Add(boundColumn3)

AddHandler Me.RadGrid1.NeedDataSource, AddressOf Me.RadGrid1_NeedDataSourceAddHandler Me.RadGrid1.DetailTableDataBind, AddressOf Me.RadGrid1_DetailTableDataBindAddHandler Me.RadGrid1.ItemCreated, AddressOf Me.RadGrid1_ItemCreatedAddHandler Me.RadGrid1.ItemCommand, AddressOf Me.RadGrid1_ItemCommand

Me.PlaceHolder1.Controls.Add(RadGrid1)End Sub 'CreateHierachicalGrid

Private Sub RadGrid1_NeedDataSource([source] As Object, e As Telerik.WebControls.GridNeedDataSourceEventArgs) Dim ds As DataSet = GetHierarchicalDsFromXml()RadGrid1.DataSource = ds.Tables(0).Select("Node_Id_0 Is NULL")

End Sub 'RadGrid1_NeedDataSource

Private Sub RadGrid1_DetailTableDataBind([source] As Object, e As Telerik.WebControls.GridDetailTableDataBindEventArgs) Dim ds As DataSet = GetHierarchicalDsFromXml() Dim parentItemId As String = e.DetailTableView.ParentItem("Node_Id").Texte.DetailTableView.DataSource = ds.Tables(0).Select(("Node_Id_0 = " + parentItemId))

End Sub 'RadGrid1_DetailTableDataBind

7.3.6 Declarative Data Binding for Hierarchical Structures

<asp:AccessDataSource ID="AccessDataSource1" DataFile="~/Grid/Data/Access/Nwind.mdb"

r.a.d.grid v3.0 | 75

© 2002-2006, telerik. All Rights Reserved.

Page 76: r.a.d.grid v3

You can easily generate this code using the wizard for configuring DataSourceControl in VS.NET.2005 The image below shows how to set the DataSource control for the second level of hierarchy. Using the Smart Tag for this control, you can start the configuration wizard. First you need to choose the Database (not shown on the image). Then you need to choose which table of this database will be included, and what will be the relation with the previous database (by setting the WHERE statement). In our case, all columns from Orders table will be included, where CustomerID will be used as a filtering parameter.

2. Assign RadGrid and each detail GridTableView DataSourceID to the right DataSourceControlAfter you set all DataSourceControls, you need to pair each GridTableView with the corresponding DataSourceControl. Each GridTableView (here are MasterTableView and DetailTableViewobjects) has a property DataSourceID . You need to set this property to point the correct DataSourceControl.

SelectCommand="SELECT * FROM Customers" runat="server"></asp:AccessDataSource><asp:AccessDataSource ID="AccessDataSource2" DataFile="~/Grid/Data/Access/Nwind.mdb"

SelectCommand="SELECT * FROM [Orders] WHERE ([CustomerID] = ?)" runat="server"><SelectParameters>

<asp:Parameter Name="CustomerID" Type="String" /></SelectParameters>

</asp:AccessDataSource><asp:AccessDataSource ID="AccessDataSource3" DataFile="~/Grid/Data/Access/Nwind.mdb"

SelectCommand="SELECT * FROM [Order Details] WHERE ([OrderID] = ?)" runat="server"<SelectParameters>

<asp:Parameter Name="OrderID" Type="Int32" /></SelectParameters>

</asp:AccessDataSource>

r.a.d.grid v3.0 | 76

© 2002-2006, telerik. All Rights Reserved.

Page 77: r.a.d.grid v3

You can access the DetailTables through its parent table Collection:

1. Choose properties for RadGrid control

2. Go to MasterTableView section. If you have set the DataSourceID property for RadGrid (as stated above), the DataSourceID property for MasterTableView will be autoset.

3. Go to DetailTables collection.

4. Add a DetailTable.

5. Set the DataSourceID property.

You need to set a DataSourceControl to the RadGrid object itself in order to have RadGrid automatically bound on page load.

r.a.d.grid v3.0 | 77

© 2002-2006, telerik. All Rights Reserved.

Page 78: r.a.d.grid v3

After setting the second level tables, you need to go on and set the third level, i.e. the DetailTable of the DetailTable.

1. Select the parent DetailTable.

2. Go to the DetailTables Collection.

3. Add the third level DetailTable.

4. Set the DataSourceID property to the third DataSource control.

r.a.d.grid v3.0 | 78

© 2002-2006, telerik. All Rights Reserved.

Page 79: r.a.d.grid v3

3. Setup DataKeyNames corresponding to the primary keysSetup DataKeyNames of MasterTableView and each DetailTable corresponding to the primary keys of the tables and DataBase relations. Below is the scheme of the sample Northwind database. For our sample grid, the first level (MasterTableView) is the Customers table. The second level is the Orders table. It is related to its parent through CustomerID field. The third level is order details table and it is related to the second level through OrderID field.

r.a.d.grid v3.0 | 79

© 2002-2006, telerik. All Rights Reserved.

Page 80: r.a.d.grid v3

4 Setup ParentTableRelations for each Detail TableViewThe names of the fields - DetailKeyField should exist in the DataSource of the corresponding GridTableView,

MasterKeyField should correspond exactly to a filed specified in DataKeyNames specified for both GridTableViews. Consider the screenshot below. It show the sequence to set the relation between a table and its child.

1. Set the DataKeyNames for the parent table. This field should exist in the DataSource specified by the DataSource Control.

2. Go to the DetailTables Collection

3. Choose the detail table.

4. Set the DataKeyNames of the detail table

5. Go to the ParentTableRelations collection

6. Add a new relation

7. Set the DataKeyField. This field should exist in the detail table data source.

8. Set the MasterKeyField - it should match the DataKeyNames field as it was set in the Parent table (Step 1).

r.a.d.grid v3.0 | 80

© 2002-2006, telerik. All Rights Reserved.

Page 81: r.a.d.grid v3

<radG:RadGrid ID="RadGrid1" runat="server" DataSourceID="AccessDataSource1" HorizontalAlign=OnNeedDataSource="RadGrid1_NeedDataSource">

<MasterTableView DataKeyNames="CustomerID" AllowMultiColumnSorting="True"><DetailTables>

<radG:GridTableView DataKeyNames="OrderID" DataSourceID="AccessDataSource2"><ParentTableRelation>

<radG:GridRelationFields DetailKeyField="CustomerID" MasterKeyField="CustomerID"</ParentTableRelation><DetailTables>

<radG:GridTableView DataKeyNames="OrderID, ProductID" DataSourceID="AccessDataSource3"<ParentTableRelation>

<radG:GridRelationFields DetailKeyField="OrderID" MasterKeyField="OrderID"</ParentTableRelation>

</radG:GridTableView></DetailTables>

</radG:GridTableView></DetailTables>

</MasterTableView></radG:RadGrid>

r.a.d.grid v3.0 | 81

© 2002-2006, telerik. All Rights Reserved.

Page 82: r.a.d.grid v3

r.a.d.grid provides an API for inserting new data, updating existing data and deleting data from the specified data source. The new ASP.NET 2.0 framework allows using these features with writing very little code.

Controlling the automatic data source operationsr.a.d.grid has to be bound to any DataSource control that supports insert/update/delete Then r.a.d.grid can take an advantage of the data source capabilities and will perform the required operations arbitrary codeless with only the error handling code required. In order to achieve this, though developer should set the properties related to the automatic data source operations. There are three properties that control the grid behavior for automatic insert/update/delete:

l AllowAutomaticDeletes="True"

l AllowAutomaticInserts="True"

l AllowAutomaticUpdates="True"

8.1.1 Extracting values r.a.d.grid has four types of columns capable of editing data that will be persisted automatically. These are:

l GridBoundColumn

l GridCheckboxColumn

l GridDropDownColumn

l GridTemplateColumn

By default r.a.d.grid will extract the values from the corresponding editors of the currently edited GridItem when updating or inserting a new record of all columns unless they are set as read-only. When deleting an item, r.a.d.grid will extract the values from the cells of the GridItem which will be deleted. The extraction of all values is necessary when the datasource control has ConflictDetection="CompareAllValues" (the default DataSource control behavior).

Extracting values from an Item is supported only when the grid is InPlace or EditForms when those edit forms are autogenerated or use a template.

r.a.d.grid can extract values even from columns that are set as read-only, if the column's property ForceExtractValue is set to:

l "InBrowseMode" - when deleting records

l "InEditMode" - when inserting/updating records

l "Always" - for all modes

The default value for this property is "None", i.e. the extraction of the default values will not be performed only for read-only columns.

Values from a template column will be extracted only for properties bound using the ASP.NET2.0 syntax:

On this example:

8 Performing Insert/Update/Delete

8.1 Automatic Insert/Update/Delete in r.a.d.grid

ASP.NET 2.0 does not support extracting values from UserControls

<radG:GridTemplateColumn HeaderText="UnitPrice" SortExpression="UnitPrice" UniqueName=<HeaderStyle Width="80px" /><ItemTemplate>

<asp:Label runat="server" ID="lblUnitPrice" Text='<%# Eval("UnitPrice", "{0:C}"</ItemTemplate><EditItemTemplate>

<asp:TextBox runat="server" ID="tbUnitPrice" Text='<%# Bind("UnitPrice") %>'</asp:RequiredFieldValidator>

</EditItemTemplate></radG:GridTemplateColumn>

r.a.d.grid v3.0 | 82

© 2002-2006, telerik. All Rights Reserved.

Page 83: r.a.d.grid v3

l When deleting records - r.a.d.grid will try to extract the values for the Item cells from the ItemTempate. As the text for the Label ID="lblUnitPrice" is bound using the Eval expression r.a.d.grid will NOT extract a value from this Label.

l When inserting/updating records - r.a.d.grid will extract the values using the EditItemTemplate. When is set in edit mode r.a.d.grid will manage to extract the value from the ID="tbUnitPrice"text box for Update/Insert operation as it s bound using the Bind expression.

8.1.2 Command itemThe [Add new record] button will be automatically placed in a command item (GridCommandItem). In order to show the command item, you should set CommandItemDisplay property of GridTableView. It can take four values: None, Top, Bottom, TopAndBottom corresponding to the place where it will appear. The command item content can be customized using the template of a GridTableView.CommandItemTemplate.

This code will result in:

In the CommandItemTemplate you can add any type of buttons that rise command event and r.a.d.grid will fire the ItemCommandEvent (see below) on the server when this button is clicked.

For example:

will automatically set r.a.d.grid in "Insert" mode as the "InitInsert" command is processed internally by r.a.d.grid. You can also fetch the command in ItemCommandEvent checking the value of the event argument CommandName for the value of "InitInsert" (corresponding to the value of the static member RadGrid.InitInsertCommandName).

8.1.3 Handling custom commands - Delete command (Command Item example)Generally you can handle any command, using the ItemCommandEvent. The example below shows hot to handle a custom command "DeleteSelected". It will delete all selected Items. In the ASPX file, we set the CommandName property to "DeleteSelected". Then in the ItemCommandEvent handler, we check if the CommandName was "DeleteSelected" and call the PerfromDelete method, which will delete all selected items.

<CommandItemTemplate>Custom command item template <asp:LinkButton Style="vertical-align: bottom" ID="btnEditSelected" runat="server"

CommandName= "EditSelected" Visible='<%# RadGrid1.EditIndexes.Count == 0 %><asp:LinkButton ID="btnUpdateEdited" runat="server" CommandName="UpdateEdited"

<asp:LinkButton ID="btnCancel" runat="server" CommandName="CancelAll" Visible='<%# RadGrid1.EditIndexes.Count > 0 || RadGrid1.MasterTableView.IsItemInserted %>

<asp:LinkButton ID="LinkButton2" runat="server" CommandName="InitInsert" Visible='<%# !RadGrid1.MasterTableView.IsItemInserted %><asp:LinkButton ID="LinkButton3" runat="server" CommandName="PerformInsert"

<asp:LinkButton ID="LinkButton1" OnClientClick="javascript:return confirm('Delete all selected customers?')"

runat= "server" CommandName="DeleteSelected"><img style="border:0px"

<asp:LinkButton ID="LinkButton4" runat="server" CommandName="Re bindGrid"><img style=<br/>

</CommandItemTemplate>

<asp:LinkButton ID="LinkButton2" runat="server" CommandName="InitInsert">Add New</asp:LinkButton>

ASPX<CommandItemTemplate>

<asp:LinkButton ID="LinkButton1" OnClientClick="javascript:return confirm('Delete all selected customers?')"

r.a.d.grid v3.0 | 83

© 2002-2006, telerik. All Rights Reserved.

Page 84: r.a.d.grid v3

Codebehind:

There are three basic functions of GridTableView that control the r.a.d.grid behavior when we want to perform automatic updates:

l PerformDelete (GridEditableItem, [boolean suppressRebind]) - performs automatic delete using the DataSource control

l PerformUpdate (GridEditableItem, [boolean suppressRebind]) - performs automatic update using the DataSource control

l PerformInsert (GridEditableItem, [boolean suppressRebind]) - performs automatic insert using the DataSource control

The suppressRebind is optional parameter. It sets if the grid will be rebound after the automatic update. The default value for suppressRebind is false, i.e. the grid will rebound unless you set otherwise.

When placing r.a.d.grid in "Insert" mode you can use the overloaded versions of GridTableView.InsertItem method. This can help you set predefined values to specific fields. The example below demonstrates how to set predefined values to a dropdown list in an edit form with a single row of code.

runat= "server" CommandName="DeleteSelected"><img style="border:0px"

</CommandItemTemplate>

C# Codeprotected void RadGrid1_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e){....

if (e.CommandName == "DeleteSelected"){ if (RadGrid1.SelectedIndexes.Count == 0){ return;

}

foreach (GridDataItem item in RadGrid1.SelectedItems){

e.Item.OwnerTableView.PerformDelete(item, true);}

e.Item.OwnerTableView.Rebind(); return;

}....

}VB.NET Code Protected Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As Telerik.WebControls.GridCommandEventArgs) Handles RadGrid1.ItemCommand

If e.CommandName = "DeleteSelected" Then

If RadGrid1.SelectedIndexes.Count = 0 Then Return

End If

For Each item As GridDataItem In RadGrid1.SelectedItemse.Item.OwnerTableView.PerformDelete(item, True)

Nexte.Item.OwnerTableView.Rebind()

Return End If

End Sub

8.2 API For Controlling the Automatic Operations

VB.NET Code

r.a.d.grid v3.0 | 84

© 2002-2006, telerik. All Rights Reserved.

Page 85: r.a.d.grid v3

l InsertItem() - no default values

l InsertItem(object dataItem) - the new Item of r.a.d.grid will be bound to the dataItem object. This method can be used to set the default values of the editors that will appear in the InsertItem.

l InsertItem(IDictionary newValues) - the new Item of r.a.d.grid will be bound to an empty object with only values taken from the newValues dictionary. This method can be used to set the default values of the editors that will appear in the InsertItem.

r.a.d.grid will place the newly inserted item just below the header item on the last page. This item can be accessed after grid is bound in "Insert" mode (after InsertItem method has been executed or "InitInsert" command has bubbled) using the GetInsertedItem() method of GridTableView.

RadGrid can fire three events after an automatic action occurred:

l ItemUpdated

l ItemInserted

l ItemDeleted

Protected Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As Telerik.WebControls.GridCommandEventArgs) Handles RadGrid1.ItemCommand If e.CommandName = RadGrid.InitInsertCommandName Then '"Add new" button clicked

e.Canceled = True 'Prepare an IDictionary with the predefined values Dim newValues As System.Collections.Specialized.ListDictionary = New System.Collections.Specialized.ListDictionary()newValues( "TitleOfCourtesy") = "Mrs."

'Insert the item and rebinde.Item.OwnerTableView.InsertItem(newValues)

End IfEnd SubC# Codeprotected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)

{ if (e.CommandName == RadGrid.InitInsertCommandName) //"Add new" button clicked{

e.Canceled = true;//Prepare an IDictionary with the predefined valuesSystem.Collections.Specialized.ListDictionary newValues = new System.Collections.Specialized.ListDictionary();newValues["TitleOfCourtesy"] = "Mrs.";//Insert the item and rebind

e.Item.OwnerTableView.InsertItem(newValues);}

}

8.3 Error Handling

protected void RadGrid1_ItemUpdated(object source, Telerik.WebControls.GridUpdatedEventArgs e){

if (e.Exception != null){

==>> e.KeepInEditMode = true;

r.a.d.grid v3.0 | 85

© 2002-2006, telerik. All Rights Reserved.

Page 86: r.a.d.grid v3

The default behavior of r.a.d.grid is to let the DataSource control rise an exception when error occurs when inserting/updating/deleting. To prevent this exception you should handle the corresponding event and in case (e.Exception != null) or (Not e.Exception Is Nothing) you should set e.ExceptionHandled to true and display error message.

e.ExceptionHandled = true;DisplayMessage(true, "Product " + e.Item["ProductID"].Text + " cannot be updated. Reason: "

} else{

DisplayMessage(false, "Product " + e.Item["ProductID"].Text + " updated"}

}

protected void RadGrid1_ItemInserted(object source, GridInsertedEventArgs e){

if (e.Exception != null){

e.ExceptionHandled = true;e.KeepInInsertMode = true;DisplayMessage(true, "Product cannot be inserted. Reason: " + e.Exception.Message);

} else{

DisplayMessage(false, "Product inserted");}

}

protected void RadGrid1_ItemDeleted(object source, GridDeletedEventArgs e){

if (e.Exception != null){

e.ExceptionHandled = true;DisplayMessage(true, "Product " + e.Item["ProductID"].Text + " cannot be deleted. Reason: "

} else{

DisplayMessage(false, "Product " + e.Item["ProductID"].Text + " deleted"}

}

private void DisplayMessage(bool isError, string text){

this.Label1.Font.Bold = true;this.Label1.Visible = true;

if (isError){

this.Label1.ForeColor = Color.Red;}

else{

this.Label1.ForeColor = Color.Green;}

this.Label1.Text = text;}

}

protected void RadGrid1_ItemDeleted(object source, GridDeletedEventArgs e){

if (e.Exception != null){

e.ExceptionHandled = true;DisplayMessage(true, "Product " + e.Item["ProductID"].Text + " cannot be deleted. Reason: "

}....

}

r.a.d.grid v3.0 | 86

© 2002-2006, telerik. All Rights Reserved.

Page 87: r.a.d.grid v3

r.a.d.grid provides an API for inserting new data, updating existing data and deleting data from the specified data source.

8.4.1 Extracting values r.a.d.grid has four types of columns capable of editing data that will be persisted automatically. These are:

l GridBoundColumn

l GridCheckboxColumn

l GridDropDownColumn

l GridTemplateColumn

By default r.a.d.grid will extract the values from the corresponding editors of the currently edited GridItem when updating or inserting a new record of all columns unless they are set as read-only. When deleting an item, r.a.d.grid can extract the values from the cells of the GridItem which will be deleted when in "Browse" mode. The extraction of all values might be necessary when you need to know all the values of the item that should be deleted to perform this operation consistently in the database.

Extracting values from an Item is supported only when the grid is InPlace or EditForms only when those edit forms are autogenerated. r.a.d.grid can extract values even from columns that are set as read-only, if the column's property ForceExtractValue is set to:

l "InBrowseMode" - when deleting records

l "InEditMode" - when inserting/updating records

l "Always" - for all modes

The default value for this property is "None", i.e. the extraction of the values will not be performed for read-only columns.

The example below demonstrates a sample usage of the ExtractValuesFromItem method for update.

8.4 Data Editing Support

private void RadGrid1_UpdateCommand(object source, Telerik.WebControls.GridCommandEventArgs e){

GridEditableItem editedItem = e.Item as GridEditableItem;DataTable ordersTable = this.OrdersData.Tables["Orders"];//Locate the changed row in the DataSourceDataRow[] changedRows = ordersTable.Select( "DependentID = " + (editedItem["DependentID"].Controls[0] as TextBox).Text );

if (changedRows.Length != 1){

this.Label1.Text += "Unbale to locate the Order for updating.";e.Canceled = true;

return;}//Update new valuesHashtable newValues = new Hashtable();

//The GridTableView will fill the values from all editable columns in the hashe.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);DataRow changedRow = changedRows[0];changedRow.BeginEdit();try{

foreach( DictionaryEntry entry in newValues ){

changedRow[(string)entry.Key] = entry.Value;}changedRow.EndEdit();

}catch( Exception ex )

{changedRow.CancelEdit();Label1.Text += "Unable to update Orders. Reason: " + ex.Message;

e.Canceled = true;

r.a.d.grid v3.0 | 87

© 2002-2006, telerik. All Rights Reserved.

Page 88: r.a.d.grid v3

In order to extract values from a Template column you should specify the bindings description collection of the corresponding template column. (GridTemplateColumn.BindingsDescription property). Each entry in the collection is an object of type BindingDescription. This object contains properties that describe binding a single value from the datasource to a property of a control in template. In this example the BindingsDescription specifies that for the Text property for the text box with ID "tbShipPostalCode" is bound to the "ShipPostalCode" DataField.

8.4.2 Command itemThe [Add new record] button will be automatically placed in a command item (GridCommandItem). In order to show the command item, you should set CommandItemDisplay property of GridTableView. It can take four values: None, Top, Bottom, TopAndBottom corresponding to the place where it will appear.

will automatically set r.a.d.grid in "Insert" mode as the "InitInsert" command is processed internally by r.a.d.grid. You can also fetch the command in ItemCommandEvent checking the value of the event argument CommandName for the value of "InitInsert" (corresponding to the value of the static member RadGrid.InitInsertCommandName).

8.4.3 Handling custom commands - Delete command (Command Item example)Generally you can handle any command, using the ItemCommandEvent. The example below shows hot to handle a custom command "DeleteSelected". It will delete all selected Items. In the ASPX file, we set the CommandName property to "DeleteSelected". Then in the ItemCommandEvent handler, we check if the CommandName was "DeleteSelected" and call a method, which will delete all selected items.

Codebehind:

}//Code for updating the database can go here...Label1.Text += "Order " + changedRow["OrderID"] + " updated";

}

<radg:GridTemplateColumn HeaderText="Ship Postal Code" Visible="false" UniqueName="TemplateColumn"<EditItemTemplate>

<span style="color:green;">Template column, that will be updated, automatically</span><asp:TextBox ID="tbShipPostalCode" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem,

</EditItemTemplate><BindingsDescription>

<radg:BindingDescription ControlID="tbShipPostalCode" PropertyName="Text"</BindingsDescription>

</radg:GridTemplateColumn>

<asp:LinkButton ID="LinkButton2" runat="server" CommandName="InitInsert">Add New</asp:LinkButton>

ASPX<CommandItemTemplate>

<asp:LinkButton ID="LinkButton1" OnClientClick="javascript:return confirm('Delete all selected customers?')"runat= "server" CommandName="DeleteSelected"><img style="border:0px"

</CommandItemTemplate>

C# Codeprotected void RadGrid1_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e){....

r.a.d.grid v3.0 | 88

© 2002-2006, telerik. All Rights Reserved.

Page 89: r.a.d.grid v3

When placing r.a.d.grid in "Insert" mode you can use the overloaded versions of GridTableView.InsertItem method. This can help you set predefined values to specific fields. The example below demonstrates how to set predefined values to a dropdown list in an edit form with a single row of code.

if (e.CommandName == "DeleteSelected"){ if (RadGrid1.SelectedIndexes.Count == 0){ return;

}

foreach (GridDataItem item in RadGrid1.SelectedItems){

Hashtable itemValues = new Hashtable ();e.Item.OwnerTableView.ExtractValuesFromItem(itemValues, item);DeleteItem (itemValues); //This function is supposed to delete the selected data item

}

e.Item.OwnerTableView.Rebind(); return;

}....

}VB.NET Code Protected Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As Telerik.WebControls.GridCommandEventArgs) Handles RadGrid1.ItemCommand

If e.CommandName = "DeleteSelected" Then

If RadGrid1.SelectedIndexes.Count = 0 Then Return

End If

For Each item As GridDataItem In RadGrid1.SelectedItemsDim itemValues as Hashtable = new Hashtablee.Item.OwnerTableView.PerformDelete(item, True)DeleteItem (itemValues) 'This function is supposed to delete the selected data item

Nexte.Item.OwnerTableView.Rebind()

Return End If

End Sub

8.5 API For Controlling Insert Operation

VB.NET CodeProtected Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As Telerik.WebControls.GridCommandEventArgs) Handles RadGrid1.ItemCommand

If e.CommandName = RadGrid.InitInsertCommandName Then '"Add new" button clickede.Canceled = True

'Prepare an IDictionary with the predefined values Dim newValues As System.Collections.Specialized.ListDictionary = New System.Collections.Specialized.ListDictionary()newValues( "TitleOfCourtesy") = "Mrs."

'Insert the item and rebinde.Item.OwnerTableView.InsertItem(newValues)

End IfEnd SubC# Codeprotected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)

{ if (e.CommandName == RadGrid.InitInsertCommandName) //"Add new" button clicked{

e.Canceled = true;//Prepare an IDictionary with the predefined valuesSystem.Collections.Specialized.ListDictionary newValues = new System.Collections.Specialized.ListDictionary();

r.a.d.grid v3.0 | 89

© 2002-2006, telerik. All Rights Reserved.

Page 90: r.a.d.grid v3

l InsertItem() - no default values

l InsertItem(object dataItem) - the new Item of r.a.d.grid will be bound to the dataItem object. This method can be used to set the default values of the editors that will appear in the InsertItem.

l InsertItem(IDictionary newValues) - the new Item of r.a.d.grid will be bound to an empty object with only values taken from the newValues dictionary. This method can be used to set the default values of the editors that will appear in the InsertItem.

r.a.d.grid will place the newly inserted item just below the header item on the last page. This item can be accessed after grid is bound in "Insert" mode (after InsertItem method has been executed or "InitInsert" command has bubbled) using the GetInsertedItem() method of GridTableView.

r.a.d.grid supports different edit forms for editing item content. You can switch the types of edit forms using the GridEditFormType Enumeration. There are three types of forms:

l AutoGenerated - Form is autogenerated, based on the column that each GridTableView exposes. This is the default type.

l WebUserControl - edit form is a WebUserControl specified by UserControlName Property

l Template - The template specified by FormTemplate Property is used as an edit form.

The GridEditFormSettings class provides settings for the edit forms generated by a GridTableView for each item that is in edit mode and the EditMode Property is set to GridEditMode.EditForms.

The ColumnNumber property sets the number of vertical columns, across which an autogenerated edit form will span. Each GridColumn has a GridColumn.EditFormColumnIndex to choose the column where the editor would appear. On the screenshot below you can see that there are 2 columns spanned:

newValues["TitleOfCourtesy"] = "Mrs.";//Insert the item and rebind

e.Item.OwnerTableView.InsertItem(newValues);}

}

8.6 Customizing Edit Forms

Note that only the columns that are editable wil be included. Those are the standard columns that have editing capabilities - such as GridBoundColumn that has GridBoundColumn.ReadOnly set to false. All the style properties (like FormStyle, FormMainTableStyle, FormCaptionStyle) apply only to the autogenerated edit form.

r.a.d.grid v3.0 | 90

© 2002-2006, telerik. All Rights Reserved.

Page 91: r.a.d.grid v3

Editable columns in r.a.d.grid (GridBoundColumn, GridDropdownColumn,GridCheckBoxColumn) can have their default editor replaced with custom ones. As a result you can facilitate enhanced functionality such as validation, rich-text editing, third-party controls, etc.

Editable columns implement the IGridEditableColumn interface.

Default Column EditorsBy default GridBoundColumn contains GridTextBoxColumnEditor, which is an instance of GridTextColumnEditor. You can use GridBoundColumn only with editors of type GridTextColumnEditor.

By default GridDropdownColumn contains GridDropDownListColumnEditor, which is an instance of GridDropDownColumnEditor. You can use GridDropdownColumn only with editors of type GridDropDownColumnEditor.

By default GridCheckBoxColumn contains GridCheckBoxListColumnEditor, which is an instance of GridBoolColumnEditor. You can use GridCheckBoxColumn only with editors of type GridBoolColumnEditor.

Declarative Column EditorsYou can set the column editors declaratively by setting the ColumnEditorID property of the corresponding column to the ID of the column editor. This gives you great flexibility for very easy customization of the look of the column editors. Column editors are added automatically in the toolbox with r.a.d.grid. You should drag them in the WebForm and then you can customize their properties.

8.7 Editors In Grid Columns

Once created, you can then easily re-use the custom editors for other grid implementations.

r.a.d.grid v3.0 | 91

© 2002-2006, telerik. All Rights Reserved.

Page 92: r.a.d.grid v3

Setting the column editor to the column:

Custom Column Editors

Replacing the default editor:

8.7.1 Implementing Custom Column EditorsThe examples below demonstrates an implementation of GridTextColumnEditor that can be used in GridBoundColumn. It represents an editor with multi-line textbox.

//ASPX declaration of the column editor<radG:GridTextBoxColumnEditor ID="GridTextBoxColumnEditor1" runat="server">

<TextBoxStyle BackColor="Blue" BorderColor="#00C000" BorderStyle="Groove" BorderWidth=Font-Names="Verdana,Arial,Geneva" ForeColor="Yellow" />

</radG:GridTextBoxColumnEditor>

<radG:GridBoundColumn DataField="CustomerID" FooterText="Customer ID" HeaderText="Customer ID"UniqueName="column" ColumnEditorID="GridTextBoxColumnEditor1">

</radG:GridBoundColumn>

private void RadGrid1_CreateColumnEditor(object sender, Telerik.WebControls.GridCreateColumnEditorEventArgs e){

if ( e.Column is GridBoundColumn ){

if ( (e.Column as GridBoundColumn).DataField == "ShipAddress" ){

e.ColumnEditor = new MultiLineTextBoxColumnEditor();}else if ( (e.Column as GridBoundColumn).DataField == "OrderDate" ){

e.ColumnEditor = new DateColumnEditor();}

}}

public class MultiLineTextBoxColumnEditor: GridTextColumnEditor{

private TextBox textBox;protected override void LoadControlsFromContainer(){

this.textBox = this.ContainerControl.Controls[1] as TextBox;}public override bool IsInitialized{

get{

return this.textBox != null;

r.a.d.grid v3.0 | 92

© 2002-2006, telerik. All Rights Reserved.

Page 93: r.a.d.grid v3

You have two options regarding the implementation of the web user control depending on the desired mode of exchanging data between r.a.d.grid and the UserControl instances:

l binding directly to RadGrid's Item

l declaring and binding to DataItem property of the UserControl

Binding to RadGrid ItemIn order to access data from the object, that the edit form is binding to, the binding expression used in the UserControl should be implemented in a slightly different than the traditional way. The problem is that the controls are inside UserControl. And the UserControl is at its turn a binding container. You have to bind to GridEditFormItem instead of UserControl. That's why the binding expression should be designed to calculate properties for the parent's binding container.

Here is an example of declaration of a TextBox server control that should be bound to the Regionproperty of the DataItem in RadGrid:

The container object is always the UserControl itself. That is why you should refer the parent object, which is actually an edit for table cell in the grid's GridEditFormItem. Then the BindingContainerwould refer the binding GridEditFormItem instance.

}}public override string Text{

get{

return this.textBox.Text;}set{

this.textBox.Text = value;}

}protected override void AddControlsToContainer(){this.ContainerControl.Controls.Add( new LiteralControl("<strong>Custom multi-line text editor<strong><br>") );this.textBox = new TextBox();this.textBox.TextMode = TextBoxMode.MultiLine;this.textBox.Rows = 4;this.textBox.Columns = 40;this.textBox.BackColor = Color.Crimson;this.textBox.ForeColor = Color.White;this.ContainerControl.Controls.Add(this.textBox);

}}

8.8 Web User Controls In Edit Forms

<asp:TextBoxid="TextBox1"runat="server"Text='<%# DataBinder.Eval( Container, "Parent.BindingContainer.DataItem.Region") %>

[C#]

GridEditableItem editedItem = this.Parent.NamingContainer

[VB.NET]

r.a.d.grid v3.0 | 93

© 2002-2006, telerik. All Rights Reserved.

Page 94: r.a.d.grid v3

Then the UserControl will have access to all properties of the item - cell text values, DataItem object (available in DataBinding event handler), etc.

Using the DataItem PropertyIf using this kind of expression seems in some way uncomfortable, you have another option. Your user control should implement a property with name DataItem. This property should be public and assignable from the type of the object that construct the datasource for RadGrid.

For example if you bind to a DataSet then the DataItem can be declared as:

Note that DataItem should be declared as of type object. After loading the UserControl, RadGrid will try to assign the value of the DataItem property. This allows you to write in the user control code, an expression binding the text of a TextBox control to the Country property of the datasource item can be declared this way:

Dim editedItem As GridEditableItem = Me.Parent.NamingContainer

[C#]

private DataRowView _dataItem = null;

public DataRowView DataItem{ get{ return this._dataItem;}

set{this._dataItem = value;

}}

[VB.NET]

private _dataItem As DataRowView = Nothing

Public Property DataItem As DataRowView Get Return Me._dataItem

End Get Set (ByVal value As DataRowView) Me._dataItem = value

End Set End Property

<asp:TextBoxid="TextBox1"

runat="server"Text='<%# DataBinder.Eval( Container, "DataItem.Country" ) %>'>

</asp:TextBox>

r.a.d.grid v3.0 | 94

© 2002-2006, telerik. All Rights Reserved.

Page 95: r.a.d.grid v3

Referring UserControl in EditFormsIn some scenarios you may need to have a reference to the UserControl, when the Update button is pressed. Having in mind that the UserControl is a Container, placed in a Container (EditFormCell), you should refer the control this way:

Referring Controls in UserControls

8.8.1 Retrieving valuesHere is a quick hint on how to retrieve the value from the textbox with ID TextBox7 in a user control used as EditForm in r.a.d.grid:

[C#]UserControl MyUserControl = editFormItem.FindControl("EditFormControl") as UserControl;[VB.NET]Dim MyUserControl As UserControl = CType(editFormItem.FindControl("EditFormControl"), UserControl)

[VB.NET]'in the page which holds the r.a.d.grid instancePrivate Sub RadGrid1_UpdateCommand(ByVal source As Object, ByVal e As Telerik.WebControls.GridCommandEventArgs) Handles RadGrid1.UpdateCommand

If TypeOf e.Item Is GridEditFormItem Then Dim editFormItem As GridEditFormItem = CType(e.Item, GridEditFormItem) Dim MyUserControl As UserControl =CType(editFormItem.EditFormCell.Controls(0).Controls(0), UserControl)Response.Write(CType(MyUserControl.FindControl( "TextBox7"), TextBox).Text)

End IfEnd Sub[C#]//in the page which holds the r.a.d.grid instanceprivate void RadGrid1_UpdateCommand(object source, Telerik.WebControls.GridCommandEventArgs e) {

if ((e.Item.GetType() == GridEditFormItem)) {GridEditFormItem editFormItem = ((GridEditFormItem)(e.Item));UserControl MyUserControl = ((UserControl)(editFormItem.EditFormCell.Controls[0].Controls[0]));Response.Write(((TextBox)(MyUserControl.FindControl( "TextBox7"))).Text);

}}

r.a.d.grid v3.0 | 95

© 2002-2006, telerik. All Rights Reserved.

Page 96: r.a.d.grid v3

You will be able to update the altered data in the respective grid cell. Similar actions can be undertaken when you would like to delete/insert an item performing the task from the user control.

8.8.2 Setting propertiesYou can hook the ItemCreated event of the grid to access the controls/properties of the user control edit form. In the respective handler, you should check whether the type of item is GridEditFormItem and also whether the item is in edit mode. Then you can locate the user control inside the GridEditFormItemand make the modifications you wish. Here is an example which will set text for TextBox with ID = "TextBox1" which resides inside the user control:

Accessing the PageYou can access the Page from within the user control. In the example below Page is a reference to the page object:

Now you can reference all properties of the actual Page.

You can fine tune the behavior of r.a.d.grid when inserting/editing items. Consider the scenarios below:

8.9.1 Update to Insert modeA selected item is in edit mode. You click the "Add New Record" button, the edited record closes and after that the new item is inserted. This is accomplished by the following code:

[C#]private void RadGrid1_ItemCreated(object sender, Telerik.WebControls.GridItemEventArgs e){

if(e.Item is GridEditFormItem && e.Item.IsInEditMode){UserControl MyUserControl = e.Item.FindControl

(GridEditFormItem.EditFormUserControlID) asUserControl;TextBox box = (TextBox)MyUserControl.FindControl("TextBox1");box.Text = "default text";

}}[VB.NET]Private Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As Telerik.WebControls.GridItemEventArgs) If (e.Item _

= (GridEditFormItem AndAlso e.Item.IsInEditMode)) Then Dim MyUserControl As UserControl = CType(e.Item.FindControl(GridEditFormItem.EditFormUserControlID),UserControl) Dim box As TextBox = CType(MyUserControl.FindControl("TextBox1"),TextBox)box.Text = "default text"

End IfEnd Sub

[C#]

MyPageClassName myPage = this.Page[VB.NET]

Dim myPage as MyPageClassName = Me.Page

8.9 Switching the Insert/Updade/ Regular Modes

[C#]private void RadGrid1_ItemCommand(object source, GridCommandEventArgs e){

RadGrid grid = (source as RadGrid); if (e.CommandName == RadGrid.InitInsertCommandName){

if (grid.EditItems.Count > 0){

grid.MasterTableView.ClearEditItems();

r.a.d.grid v3.0 | 96

© 2002-2006, telerik. All Rights Reserved.

Page 97: r.a.d.grid v3

8.9.2 Insert to Update modeYou click "Add New Record" button and a new record is inserted in r.a.d.grid. Then you click the edit button at another record. The selected item goes in edit mode and the insert new record closes. You should modify the setting for the IsItemInserted property of the respective GridTableView:

}}

}[VB.NET]Private Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As GridCommandEventArgs) Dim grid As RadGrid = CType(source,RadGrid) If (e.CommandName = RadGrid.InitInsertCommandName) Then If (grid.EditItems.Count > 0) Then

grid.MasterTableView.ClearEditItems End If

End IfEnd Sub

[C#]private void RadGrid1_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e){

RadGrid grid = (source as RadGrid); if(e.CommandName == RadGrid.InitInsertCommandName){grid.MasterTableView.ClearEditItems();

} if(e.CommandName == RadGrid.EditCommandName){e.Item.OwnerTableView.IsItemInserted = false;

}}[VB.NET]Private Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As Telerik.WebControls.GridCommandEventArgs) Dim grid As RadGrid = CType(source,RadGrid) If (e.CommandName = RadGrid.InitInsertCommandName) Then

grid.MasterTableView.ClearEditItems End If If (e.CommandName = RadGrid.EditCommandName) Then

e.Item.OwnerTableView.IsItemInserted = false End IfEnd Sub

r.a.d.grid v3.0 | 97

© 2002-2006, telerik. All Rights Reserved.

Page 98: r.a.d.grid v3

r.a.d.grid has a rich design-time support, which allows you to build a grid, customize it and see the changes reflected immediately.

Before you start your work with the design-time, you will need to set the necessary dataSets and DataAdapters (SqlDataAdapter, OleDbDataAdapter, etc.) in order to use them directly in the

property builder. When setting the dataset, you may also set the table relations.

In order to use the r.a.d.grid design-time support effectively, you need to set the DataSource property in the ASPX declaration of the grid.

If you don't set the DataSource property here, you will not see the changes you have made in the design-time.

After you drag and drop an instance of r.a.d.grid from the toolbox onto the webform, right-click it and select the [r.a.d.grid Property Builder] command.

Before you start your work with the design-time, you will need to set the necessary DataSource

9 Design-time Support

9.1 Overview

<radg:radgrid id=RadGrid1runat="server"

AllowPaging="True" DataSource="<%# dataSet11 %>" DataMember="Customers" AutoGenerateColumns="False"

>

r.a.d.grid v3.0 | 98

© 2002-2006, telerik. All Rights Reserved.

Page 99: r.a.d.grid v3

controls ('Data Source' in the on-line documentation).

This will pop up the r.a.d.grid builder dialog.

When you first start the property builder, you will see a RadGrid and one Master table. The r.a.d.gridproperty builder has three main panes:

The screenshot below shows the initial state of the r.a.d.grid property builder's General Settings page.

9.2 Setting RadGrid

l A pane with Grid hierarchy objects -in this pane you can add/remove detail tables.

l A pane with a treeview of property pages for the selected objects

l A pane with properties for the selected object

r.a.d.grid v3.0 | 99

© 2002-2006, telerik. All Rights Reserved.

Page 100: r.a.d.grid v3

9.2.1 Data options

9.2.2 Header and FooterUse the check-boxes to enable the Header or Footer cells.

9.2.3 SortingCheck the box to enable the data Sorting option. When this option is enabled, the Header cell for each column will be a link and will sort the data.

9.2.4 FilteringCheck the box to enable the data Filtering option.

This page provides options that if set, will be available for all grid tables. If you set [Show header] option, all tables in your grid will have headers.

Property Description

DataSource

Sets the DataSource property, specifying the data-source object that will be used for building the grid. If you have set a dataSet, it will appear in the drop down list.

Generate Columns automatically at runtime

All columns, available in the specified dataSet will be generated as GridBoundColumns at runtime. This option sets the AutoGenerateColumns property to true.

r.a.d.grid v3.0 | 100

© 2002-2006, telerik. All Rights Reserved.

Page 101: r.a.d.grid v3

The Paging section of the r.a.d.grid Property Builder lets you specify whether your grid will use pages and the specific paging options.

9.3.1 PagingIn order to turn the paging on (enable dividing data into portions called pages) you must check the [Allow Paging] box [sets the AllowPaging Property] on the top of the Property Builder. This will enable the default paging mechanism of r.a.d.grid. However you are free to use your own pagingsystem. All you need to do is to check the [Allow Custom Paging] box [sets the AllowCustomPaging Property] .

The size of a given Page in r.a.d.grid is defined by the number of rows, this page will hold. You can define the page size using the [Page size] [sets the PageSize Property] field.

9.3.2 Page NavigationThis dialog allows you to customize the way navigation is performed. You can show the navigation buttons, which will help the site-visitor to navigate through the data visualized by r.a.d.grid . In order to enable the buttons, check the [Show navigation buttons] check box.

Now you can customize the navigation button properties:

l Position - use the drop-down list to specify the position of the navigation buttons relative to the grid.

9.3 Paging

r.a.d.grid v3.0 | 101

© 2002-2006, telerik. All Rights Reserved.

Page 102: r.a.d.grid v3

l Mode - Specify the way navigation buttons are displayed. You can have navigation buttons appear as page numbers or as previous/next buttons with text. The custom text can be set in the fields below. Note, that you can even enter HTML tags for formatting the custom text.

l Numeric buttons: specifies the maximum number of page numbers, that will be shown. If you set this to "5" and your grid has 10 pages, you will see them in series of five numbers ("... ,2, 3, 4, 5, 6, ..." for example).

The Style Manager lets you fully customize the appearance of r.a.d.grid. Here you can set the colors for the grid elements, the style for the strings and the element alignment.

9.4.1 Object treeThis tree shows the customizable r.a.d.grid objects. The first three nodes present settings for the whole grid. The Nodes below present settings for specific grid elements. The latter will override the general settings.

The Columns node appears only if you use custom column-bounding. If you use the automatic columns generation (see below) you will not see Columns settings.

9.4.2 AppearanceThis section of the dialog is common for all objects in the Object tree. Here you can set the appearance options for the selected grid element.

9.4 Style Manager

r.a.d.grid v3.0 | 102

© 2002-2006, telerik. All Rights Reserved.

Page 103: r.a.d.grid v3

Below are the customization options:

l Fore color - the color of the text

l Back Color - the color of the text background

l Font Name - the font for the text of the selected element

l Font size - the font size in the selected units

Below are the style customization options:

l Horizontal Alignment - left, right or center

l Vertical Alignment - top, middle, bottom

The Borders section of the r.a.d.grid Property Builder dialog gives you access to the properties defining the appearance of the borders in the grid cells.

9.5.1 Cell MarginsYou can set cell options like in every HTML table:

l Cell padding

l Cell spacing

9.5 Borders

r.a.d.grid v3.0 | 103

© 2002-2006, telerik. All Rights Reserved.

Page 104: r.a.d.grid v3

9.5.2 Border linesThe [Grid lines] drop-down lets you specify which lines will be shown in your grid. The available options are:

l horizontal lines

l vertical lines

l both lines

l none

The [Border color] sets the color of the border lines.

The [Border width] sets the width of the border lines in the specified units.

The Columns section allows you to set the way columns are generated and visualized.

9.6.1.1 Automatic column generationAt the top of the r.a.d.grid Property Builder dialog, there is a check box called "Create columns automatically at runtime". This will set the AutoGenerateColumns property to true.

9.6 Table Related Properties

9.6.1 Columns

Ticking this check box will override the options for bound columns below. If you need to bound

r.a.d.grid v3.0 | 104

© 2002-2006, telerik. All Rights Reserved.

Page 105: r.a.d.grid v3

9.6.1.2 Manual Column BindingColumn binding will let you display only specific data fields from a given database. Moreover, you can define custom header and footer texts for the columns that present these fields. From the "Available Columns" list choose the columns, which you want to bind (display) and click the [>] button. The column will appear in the "Selected Columns" list. You can use the Up and Down buttons to re-order the columns and the [X] button to remove a column from this list. In the "Available Columns" list there are some special columns. These columns do not represent a data field. They present specific r.a.d.grid features such as:

l GridBoundColumn

l GridButtonColumn

l GridEditCommandColumn

l HyperlinkColumn

l TemplateColumn

l GridCheckBoxColumn

l GridDropDownColumn

These columns are described in the Column Types (Section 6.2.1) topic.

Creating Detail TablesUsing the r.a.d.grid property builder, the creation of the Detail tables is an easy task. Just point the table, for which you need to add a Detail table and click the [+] button on the right panel.

Then you will need to set the DataSource for the newly created detail table and set the relation to the master table.

9.7.1 Data binding DetailTableIn order to data bind a detail table, you need to go to the TableView setting property page and there set the DataMember and DataKeyNames properties. These are dropdowns and depend on how you have set your data source. The DataKeyNames property will be used for settin the proper relation to the child table of the current table.

columns, uncheck this box.

9.7 Creating Hierarchical Grids

=>

r.a.d.grid v3.0 | 105

© 2002-2006, telerik. All Rights Reserved.

Page 106: r.a.d.grid v3

9.7.2 Setting Table RelationsIn order to set the relation to the parent table, you need to display the property grid for the selected detail table. Use the [Toggle property grid] link in the properties pane.

Consider the image below:

1. Open the ParentTableRelation Collection

2. Add new relation

3. Go to the relation

4. Set DataKeyField and MasterKeyField. DataKeyField should match a field in the current data source for this detail table. MasterKeyField should match the DataKeyNames field as set in the parent (master) table.

r.a.d.grid v3.0 | 106

© 2002-2006, telerik. All Rights Reserved.

Page 107: r.a.d.grid v3

9.7.3 Setting Detail Table PropertiesThe properties of the detail tables are set in the same way as for the master table.

Deleting Detail TablesIn order to delete a detail table, point it in the Grid hierarchy objects tree and click the [X] button. Note that if this detail table has children tables, they will also be deleted.

The master table cannot be deleted.

r.a.d.grid v3.0 | 107

© 2002-2006, telerik. All Rights Reserved.

Page 108: r.a.d.grid v3

r.a.d.grid v3.0 | 108

© 2002-2006, telerik. All Rights Reserved.

Page 109: r.a.d.grid v3

Once you have built the r.a.d.grid you need to set its appearance. If you don't do this, the default look & feel of will be used.

The look-and-feel of the component can be defined using a combination of CSS and images referred to as skins. The images are located in individual sub-folders of the folder:

"~/RadControls/Grid/Skins"

By default there is only one sub-folder called "Default".

The stylesheet has to be defined in your page.

PropertiesThe appearance of the r.a.d.grid control may be customized by setting the style properties for the different parts of the control. The following table lists the different style properties.

10.1.1 Group Panel CustomizationIf grouping is enabled, r.a.d.grid will allow grouping by column(s). You need to drag-and-drop the headers of one or more columns on the group panel to define the grouping.

10 Customizing Appearance

10.1 Skins

Instead of setting properties for each GridTableView, you can use RadGrid global properties for:PageSize, AllowSorting, AllowPaging , AllowCustomPaging, ShowFooter, ShowHeader, BackColor, BorderColor, PagerStyle.Thus they will be set for each table in the hierarchy, unless specified otherwise.

Style Property Description

AlternatingItemStyle Specifies the style for alternating items in the RadGrid control.

EditItemStyle Specifies the style for the item being edited in the RadGrid control.

FooterStyle Specifies the style for the footer section in the RadGrid control.

HeaderStyle Specifies the style for the header section in the RadGrid control.

ItemStyle Specifies the style for the items in the RadGrid control.

PagerStyle Specifies the style for the page selection section of the RadGrid control.

SelectedItemStyle Specifies the style for the selected item in the RadGrid control.

GroupHeaderItemStyle Specifies the style for the group header in the RadGrid control.

r.a.d.grid v3.0 | 109

© 2002-2006, telerik. All Rights Reserved.

Page 110: r.a.d.grid v3

You can modify panel's appearance using PanelStyle and PanelItemsStyle properties. The PanelStyle property customizes the panel itself, and the PanelItemStyle property customizes the items in this panel.

With r.a.d.grid you can easily perform even more advanced tasks such as Calculations In Group Header Item (Section 13.3).

ImagesThe skin's images have to be named as follows:

Working with CSS classes

You can use css style selectors to get the desired appearance. You need to define those css settings in separate classes and then assign them to the grid through the CssClass property of the control.

There are cases when one would like to have different visualization for the links in the grid, compared to the ones outside the grid. Below is an example code which will make the default color of the links in the HyperLinkColumn of the grid brown. The links will turn orange and will have smaller font size on mouse hover.

Image Name

SingleMinus.gif

SinglePlus.gif

SortAsc.gif

SortDesc.gif

SelectedRow.gif

<HTML><HEAD>

<title>WebForm1</title> <style>

.RadGrid A { COLOR: brown }

.RadGrid A:hover { FONT-SIZE: 15px; COLOR: orange }</style>

</HEAD>

...<radg:RadGrid id="RadGrid1" CssClass="RadGrid" style="Z-INDEX: 101; LEFT: 336px; POSITION: absolute; TOP: 16px"

runat="server" AutoGenerateColumns="False">

r.a.d.grid v3.0 | 110

© 2002-2006, telerik. All Rights Reserved.

Page 111: r.a.d.grid v3

r.a.d.grid populates auto generated columns (generated if the AutoGenerateColumns property is set to true) as an array with objects of type GridBoundColumn. This set of columns can be accessed using the AutoGeneratedColumns property of each GridTableView. You can force RadGrid to populate this array before it is data bound using the GridTableView.CreateColumnSet(true) method. (Note that CreateColumnSet(bool) method was deprecated since r.a.d.grid v3.0 and using it will issue a warning).

This method can be generally used in NeedDataSource event handler when the page loads for the first time - note that the changes made to AutoGeneratedColumns are persisted into the ViewState. Modifying the array returned by the property AutoGeneratedColumns would not affect the original column array that the corresponding GridTableView uses. If you need to add columns to a table in RadGrid you should use the GridTableView.Columns property.

Examples:

Instead using the CreateColumnSet(bool) you should handle the RadGrid.ColumnCreated event. In the event argument, you can find the column that r.a.d.grid is currently creating and customize it as needed.

The object model and events in RadGrid provide opportunities for customization and conditional formatting of grid elements. In order to format some data based on column type, you need to use the properties of the respective column. GridBoundColumn for example has DataFormatString property that you can use to format the appearance of the data in the cells of that column. The formatting is based on the general formatting rules in .NET, i.e. r.a.d.grid uses internally the string.Format( string, args ) function. This way you should just provide the corresponding format string in the DataFormatString property.For example the format string "{0:C}" would format the values in the cells of the column as currency.

The example below shows how to use conditional formatting in a sample mailbox implementation. Selected Items and recently received mail are marked red:

10.2 Customizing AutoGenerated Columns

Note that prior to a call to this method the DataSource property should be assigned.

C# Code...//Assign grid's DataSourceRadGrid1.DataSource = YourDataSource;

if ( !this.IsPostBack ){

RadGrid1.MasterTableView.CreateColumnSet( true );RadGrid1.MasterTableView.AutoGeneratedColumns[3].DataFormatString = "{0:C}";//... customize more

}...VB.NET Code...'Assign grid's DataSourceRadGrid1.DataSource = YourDataSource

If Not Me.IsPostBack ThenRadGrid1.MasterTableView.CreateColumnSet( True)RadGrid1.MasterTableView.AutoGeneratedColumns(3).DataFormatString = "{0:C}"

'... customize moreEnd If...

10.3 Conditional Formatting

r.a.d.grid v3.0 | 111

© 2002-2006, telerik. All Rights Reserved.

Page 112: r.a.d.grid v3

C# Code

private void RadGrid1_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e){

//Is it a GridDataItem if (e.Item is GridDataItem){

//Get the instance of the right typeGridDataItem dataBoundItem = e.Item as GridDataItem;

//Check the formatting condition if (int.Parse(dataBoundItem["Size"].Text) > 100 )

{dataBoundItem[ "Received"].ForeColor = Color.Red;dataBoundItem[ "Received"].Font.Bold = true;//Customize more...

}}

}VB.NET Code

Private Sub RadGrid1_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.WebControls.GridItemEventArgs) 'Is it a GridDataItem If (TypeOf (e.Item) Is GridDataItem) Then

'Get the instance of the right type Dim dataBoundItem As GridDataItem = e.Item

'Check the formatting condition If (Integer.Parse(dataBoundItem( "Size").Text) > GridItemType.Footer)

dataBoundItem( "Received").ForeColor = Color.ReddataBoundItem( "Received").Font.Bold = True 'Customize more...

End If End If

End Sub

r.a.d.grid v3.0 | 112

© 2002-2006, telerik. All Rights Reserved.

Page 113: r.a.d.grid v3

Hiding the Expand-Collapse button for empty Detail TablesYou can hide the Expand-Collapse button on Page_PreRender. Here's an example:

Please take into account that this solution will work only in case of HierarchyLoadMode = "Server" or HierarchyLoadMode = "Client". You can find more information about the grid loading modes in Hierarchy Load (Section 13.7) topic.

10.4 Customizations related to Hierarchy

[VB.NET]Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRender

For Each item As GridItem In RadGrid1.MasterTableView.Controls(0).Controls If TypeOf item Is GridNestedViewItem Then

Dim nestedViewItem As GridNestedViewItem =CType(item, GridNestedViewItem)

If nestedViewItem.NestedTableViews(0).Items.Count = 0 Then Dim cell As TableCell =nestedViewItem.NestedTableViews(0).ParentItem( "ExpandColumn")

Dim expandCollapseButton As ImageButton =CType(cell.Controls(0), ImageButton)expandCollapseButton.Visible = False

End If End If

NextEnd Sub[C#]private void Page_PreRender(object sender, System.EventArgs e) {foreach (GridItem item in RadGrid1.MasterTableView.Controls[0].Controls) { if ((item.GetType() == GridNestedViewItem)) {

GridNestedViewItem nestedViewItem = ((GridNestedViewItem)(item)); if ((nestedViewItem.NestedTableViews(0).Items.Count == 0)) {

TableCell cell = nestedViewItem.NestedTableViews(0).ParentItem( "ExpandColumn");ImageButton expandCollapseButton = ((ImageButton)(cell.Controls[0]));expandCollapseButton.Visible = false;

}}

}}

r.a.d.grid v3.0 | 113

© 2002-2006, telerik. All Rights Reserved.

Page 114: r.a.d.grid v3

r.a.d.grid takes full advantage of the AJAX technology (Asynchronous JavaScript with XMLHttpRequests) to deliver an unsurpassed responsiveness and user experience for an ASP.NET grid control.

The main idea of the AJAX framework is the elimination of full-page postbacks. In contrast, only the relevant parts of the page are updated, without a disturbing refresh. Moreover, the markup that is transferred between the client machine and the server is reduced dramatically, which results in a significant performance improvement.

telerik r.a.d.grid implements the AJAX technology completely behind the scenes eliminating the need for further intervention of the developer. All you have to do is set a single property (EnableAsyncRequests) to true. This will make all elements of the grid, which typically make a postback (e.g. Buttons, ImageButtons, LinkButtons) to perform a silent AJAX callback instead.

Furthermore, there is a mechanism for making any control integrated in the grid to perform AJAX callbacks instead of postbacks. For example, the drag-and-drop for grouping and column reordering uses that mechanism to facilitate no-postback experience.

The AJAX technology implemented in r.a.d.grid , preserves the page lifecycle completely. The developer can continue to set properties of the grid itself or of other controls inside the grid (including third party controls). The only limitation is that upon a callback request you cannot affect other controls on the page, i.e. the callback functionality is limited to the grid and the controls it contains.

How the AJAX technology is implemented in r.a.d.gridWhen AJAX mode is enabled (EnableAsyncRequests is set to true) r.a.d.grid checks for all elements that typically make postback and assigns an OnClick JavaScript event to them. When one of the elements attempts a postback, r.a.d.grid handles the event and passes the request to the AJAX client-side engine, using an internal JavaScript function. The AJAX client-side engine in turn sends the request to the server. There AJAX server-side engine then handles the request and sends it to the ASP.NET platform as normal postback. On the way back the AJAX server-side engine forms the data as XML and returns it to the r.a.d.grid AJAX client-side engine for rendering in the browser.

As a result, the normal lifecycle of the page is preserved. The whole responsibility for the AJAX callback lies with r.a.g.grid, eliminating the need for any other code modifications.

11 AJAX in r.a.d.grid

11.1 AJAX in r.a.d.grid

An AJAX request from r.a.d.grid cannot affect other controls on the page. The AJAX functionality is limited to the grid and the controls it contains.

r.a.d.grid gives you the advantage of having your pages indexed by search engines even when working in AJAX mode.

r.a.d.grid v3.0 | 114

© 2002-2006, telerik. All Rights Reserved.

Page 115: r.a.d.grid v3

There are cases when you may want to update the information inside the grid by triggering a callback externally from other control on the page. Generally, this is a simple task with the integrated AJAX mechanism of r.a.d.grid . You need to make a call to the RadGridInstance.AsyncRequest() method (passing the necessary information as parameters to it) and then override the RaisePostBackEventmethod to apply the changes. Here is a sample implementation:

11.2 Using AJAX mechanism outside of the grid

ASPX/ASCX<radg:radgrid id="RadGrid1" runat="server"

EnableAsyncRequests= "True" AllowSorting="True" AllowPaging="True"></radg:radgrid><br /><input type=button value="Refresh"onclick='RadGridNamespace.AsyncRequest( "<%= RadGrid1.ClientID %>"

VB.NET CodeProtected Overrides Sub RaisePostBackEvent(ByVal source As IPostBackEventHandler, ByVal

MyBase.RaisePostBackEvent(source, eventArgument) Select Case eventArgument

Case "Rebind"RadGrid1.Rebind()

End SelectEnd Sub

C# Codeprotected override void RaisePostBackEvent(IPostBackEventHandler source, String eventArgument){

base.RaisePostBackEvent(source, eventArgument);switch(eventArgument){ case "Rebind":

RadGrid1.Rebind();

r.a.d.grid v3.0 | 115

© 2002-2006, telerik. All Rights Reserved.

Page 116: r.a.d.grid v3

In scenarios where some control performs redirection you can still have r.a.d.grid working in AJAX mode. All you need to do is:

1. Set EnableAsyncRequests to true

2. Use RadGrid.AsyncRequest instead of Response.Redirect in the code-behind to perform the redirection.

When working with large data sets it is convenient to use the paging mechanism of r.a.d.grid. However for really huge datasets crawling through pages using only the grid pager may become hard and boring task. For such scenarios r.a.d.grid gives you the Virtual scrolling/paging functionality. Holding the Shift key and using the grid scrollbar, you can change the grid pages just like in Microsoft Word®. When scrolling with the virtual scrollbar, r.a.d.grid uses AJAX requests to change the pages, i.e. no Postbacks are performed. The overall behavior is smooth and with no flicker.

In order to enable virtual scrolling/paging for large record sets browsing use the ClientSettings.Scrolling.EnableAJAXScrollPaging property of r.a.d.grid. Note that you should have AJAX enabled for r.a.d.grid by setting the EnableAsyncRequests="True".

break;}

}

11.3 Redirecting with AJAX

11.4 Virtual Scrolling/Paging

<radg:radgrid id="RadGrid1" Width="95%" EnableAJAXLoadingTemplate="True" cssclass="RadGrid"allowsorting="True" pagesize="50" showfooter="True" showgrouppanel="True" allowpaging=runat="server" style="border-collapse:separate;">

<grouppanel><panelitemsstyle cssclass="GroupPanelItems" /><panelstyle cssclass="GroupPanel" />

</grouppanel><headerstyle cssclass="GridHeader" /><footerstyle cssclass="GridFooter" /><groupheaderitemstyle cssclass="GroupHeader" /><pagerstyle mode="NumericPages" cssclass="GridPager" /><itemstyle cssclass="GridRow" /><alternatingitemstyle cssclass="GridRow" /><mastertableview editmode="InPlace" cssclass="MasterTable" ><RowIndicatorColumn>

<ItemStyle CssClass="ResizeItem"></ItemStyle></RowIndicatorColumn>

</mastertableview><clientsettings allowdragtogroup="True" allowcolumnsreorder="True" reordercolumnsonclient=

<resizing allowrowresize="true" allowcolumnresize="True" enablerealtimeresize=<scrolling allowscroll="True" enableajaxscrollpaging="True" usestaticheaders=

</clientsettings></radg:radgrid>

r.a.d.grid v3.0 | 116

© 2002-2006, telerik. All Rights Reserved.

Page 117: r.a.d.grid v3

r.a.d.grid v3.0 | 117

© 2002-2006, telerik. All Rights Reserved.

Page 118: r.a.d.grid v3

r.a.d.grid provides the following objects on the client-side:

RadGrid events

MasterTableView events

12 r.a.d.grid Client-Side

12.1 Client-Side Object Model

Object Description

RadGridThis is the main class. You can use it to access the whole grid object. See Rad Grid Class Overview (on-line documentation) for details.

MasterTableViewThis is an object of type RadGridTable. This object is used to access the root table in hierarchical structures.

DetailTablesCollectionThis collection represents the detail tables when you have a hierarchical structured grid. Every table is of type RadGridTable.

RadGridTableClient-side object for RadGridTable. Each RadGridTable has TableColumn and TableRow objects for manipulating the Rows and Columns client-side.

RadGridTable.ColumnsThese are objects of type TableColumn - the client-side object for MasterTableView/DetailTablesView columns.

RadGridTable.Rows These are objects of type TableRow

Error This object is for handling errors.

12.2 Client-Side JavaScript Events

Event Description

OnGridCreating This event is fired before the grid is created.

OnGridCreated This event is fired after the grid is created.

OnGridDestroyingThis event is fired when the r.a.d.grid object is destroyed, i.e. on each window.onunload

OnError You can handle this event if you need to have your code executed when an error occurs in r.a.d.grid.

OnRequestStart

Handle RadGrid.OnRequestStart to execute code that should perform any operations before the AJAX request has started. Those can be - cleanup operations, check if the request can be performed at this moment to prevent any loss of user data, etc.

OnRequestEndRadGrid.OnRequestEnd can be used to recreate any javascript objects related to RadGrid, execute scripts related to the initial load state of the control.

Event Description

OnMasterTableViewCreating This event is fired before the MasterTableView is created.

r.a.d.grid v3.0 | 118

© 2002-2006, telerik. All Rights Reserved.

Page 119: r.a.d.grid v3

MasterTableView, DetailTables events

OnMasterTableViewCreated This event is fired after the MasterTableView is created.

Event Description

Table Creation

OnTableCreating This event is fired before the table is created.

OnTableCreated This event is fired after the table is created.

OnTableDestroying This event is fired when table object is destroyed.

Column Creation

OnColumnCreating This event is fired before column is created on client-side.

OnColumnCreated This event is fired after a column is created on client-side.

OnColumnDestroying This event is fired when a column object is destroyed.

Column Resizing

Each time you have

or respectively

executed, and where grid is the client-side RadGrid object, following events are fired:

grid.MasterTableView.ResizeColumn(columnIndex, newWidth)

grid.DetailTableView.ResizeColumn(columnIndex, newWidth)

OnColumnResizing This event is fired before a column is resized.

OnColumnResized This event is fired after a column is resized.

Columns Ordering

OnColumnSwaping This event is fired before two columns are swapped.

OnColumnSwaped This event is fired after two columns are swapped.

OnColumnMovingToLeft This event is fired before a column is moved to the left.

OnColumnMovedToLeft This event is fired after a column is moved to the left.

OnColumnMovingToRight This event is fired before a column is moved to the right.

OnColumnMovedToRight This event is fired after a column is moved to the right.

Row Creation

OnRowCreating This event is fired before a row available client-side is created.

OnRowCreated This event is fired after a row available client-side is created.

OnRowDestroying This event is fired when a row object is destroyed.

Row Resizing

Each time you have

or respectively

executed, and where grid is the client-side RadGrid object, following events are fired:

grid.MasterTableView.ResizeRow(rowIndex, newWidth)

grid.DetailTableView.ResizeRow(rowIndex, newWidth)

OnRowResizing This event is fired before a row is resized.

OnRowResized This event is fired after a row is resized.

Row Selection

OnRowSelecting This event is fired before row selection.

OnRowSelected This event is fired after row selection.

OnRowDeselecting This event is fired before row deselection.

OnRowDeselected This event is fired after row deselection.

r.a.d.grid v3.0 | 119

© 2002-2006, telerik. All Rights Reserved.

Page 120: r.a.d.grid v3

r.a.d.grid provides extensive client-side API for manipulation of the RadGridTable object and its members.

Obtaining RadGridTable properties

12.3.1 Obtaining table elementsYou can further refer to the elements of the RadGridTable using the functions below:

RadGridTable.Columns[n].Control = the real HTML table cell for the n-th column (<th> for the header cell)RadGridTable.Rows[n].Control = the real HTML table row for the n-th row (will be <tr> for the header cell)

Manipulating RadGridTable elementsr.a.d.grid provides means for client-side manipulation of the table elements.

OnClick and OnDblClick Events

OnRowClick This event is fired when a row is clicked.

OnRowDblClick This event is fired when a row is double-clicked.

OnColumnClick This event is fired when a column is clicked.

OnColumnDblClick This event is fired when a column is double-clicked.

Mouse Events

OnRowMouseOver This event is fired when the mouse hovers over a row.

OnRowMouseOut This event is fired when the mouse leaves a row.

OnColumnMouseOver This event is fired when the mouse hovers over a column.

OnColumnMouseOut This event is fired when the mouse leaves a column.

Context Menus

OnColumnContextMenu This event is fired when the context menu for a column is called.

OnRowContextMenu This event is fired when the context menu for a row is called.

Column Visibility

OnColumnHiding This event is fired before a column is hidden.

OnColumnHidden This event is fired after a column is hidden.

Row Visibility

OnRowHiding This event is fired before a row is hidden.

OnRowHidden This event is fired after a row is hidden.

12.3 RadGridTable client-side API

Property Description

RadGridTable.Control Returns the real HTML table (<table>) in the document

RadGridTable.ClientID Returns the ID of the real HTML table in the document

RadGridTable.Columns Returns a collection of columns (columns Array)

RadGridTable.Rows Returns a collection of rows (rows Array)

RadGridTable.ColGroupReturns the <colgroup> object of the real HTML table (of type Array)

r.a.d.grid v3.0 | 120

© 2002-2006, telerik. All Rights Reserved.

Page 121: r.a.d.grid v3

12.3.2 Working with table rows

12.3.3 Working with Columns

If you want the columns in your grid to be resizable, you need to set the client-side AllowColumnResize property to true. Then when you drag the handle between two columns, you can resize them. The default value for this property is true.

Similarly, when you want rows to be resizable, set client-side AllowRowResize property to true. Then you can drag the handle between two rows to resize them. The default value for this property is false.

12.4.1 Real-Time ResizingThere are two modes of columns resizing with respect to visualization. The content of the resized columns can be rendered real-time as you drag the handle. This feature put a significant load on client computer's CPU. Alternatively, you can see only the handle moving during the resizing, and only after you drop it the columns will be rendered. As a result, the load of the CPU is much lower.

You can control the behavior of the real-time resizing using the EnableRealTimeResize property. The default value for this property is false.

12.4.2 Resizing Grid on Column Resizer.a.d.grid allows you to control the behavior of the grid during column resizing. This behavior is

Method Description

ResizeRow (index, height)Sets a new height for the row at index index. The new height will be height.

Method Description

ResizeColumn (index, width)Resizes the column at the specified index, to the given width.

SwapColumns (columnIndex1, columnIndex2)

Swaps the row at index specified by columnIndex1 with the row at index specified by columnIndex2.

MoveColumnToLeft (index)

MoveColumnToRight (index)

12.4 Resizing

EnableRealTimeResize = falseOnly the resizing handle is rendered.

EnableRealTimeResize = trueThe whole content is rendered during resizing.

r.a.d.grid v3.0 | 121

© 2002-2006, telerik. All Rights Reserved.

Page 122: r.a.d.grid v3

controlled by the ResizeGridOnColumnResize client-side property.

When this property is set to false the grid will preserve its size and resize the rest of the columns evenly, preserving the overall size of the whole grid.If you set ResizeGridOnColumnResize to true, and resize a column the grid will change its size dynamically. All other columns will retain their original sizes. The default value for this property is false.

12.4.3 Clipping Cell Content On ResizeOften, when working with grids, you don't need to see the whole content of a given cell. In other words it may be clipped in case the column is resized. You can control this by setting the ClipCellContentOnResize property. By default it is set to true.

AllowColumnResize property has a priority over Resizable (client-side) property. Yet you need to set both the same in order to have resizing enabled. Here is an example set of resizing-related properties:

Example:

ResizeGridOnColumnResize = false

After resizing the CustomerID column, the grid has preserved its overall size. All other columns have been shrunk.

ResizeGridOnColumnResize = trueAfter resizing the CustomerID column, the grid changed its overall size and exceeded the page limits. All other columns kept their original sizes.

ClipCellContentOnResize = falseThe handle is dragged but, the cell won't be resized anymore because clipping is needed and it is turned off.

ClipCellContentOnResize = trueYou can reduce the column size as much as you wish because the clipping is turned on.

// declaration<radG:RadGrid runat="server" ... /><ClientSettings><Resizing AllowColumnResize="True"AllowRowResize = "false"ResizeGridOnColumnResize = "false"ClipCellContentOnResize = "true"EnableRealTimeResize = "false">

// code...RadGrid RadGrid1 = new RadGrid();RadGrid1.ClientSettings.Resizing.AllowColumnResize = true;

r.a.d.grid v3.0 | 122

© 2002-2006, telerik. All Rights Reserved.

Page 123: r.a.d.grid v3

Very often, when constructing a grid, there are design limitations regarding the size of the grid. In such cases you will need to enable the client-side grid scrolling option in order to fit it in the allowed space. In order to do that you need to set the AllowScroll property to true. By default its value is false. The ScrollHeight property specifies the height beyond which the scrolling will be turned on. The default value is 300px.

12.5.1 Static HeadersThe most common problem when scrolling is losing the context of the current column, i.e. its header name. r.a.d.grid lets you keep the header at the top even when scrolling the grid. You just need to set the UseStaticHeaders property to true. Its default value is false.

RadGrid1.ClientSettings.Resizing.AllowRowResize = false;RadGrid1.ClientSettings.Resizing.ResizeGridOnColumnResize = false;RadGrid1.ClientSettings.Resizing.ClipCellContentOnResize = true;RadGrid1.ClientSettings.Resizing.EnableRealTimeResize = false;

...

12.5 Scrolling

AllowScroll=true

The grid exceeds its ScrollHeight limit and the scrollbar appears.

AllowScroll=false

The whole grid is displayed, but you need to scroll the page in order to see it completely.

UseStaticHeaders

r.a.d.grid v3.0 | 123

© 2002-2006, telerik. All Rights Reserved.

Page 124: r.a.d.grid v3

Here is an example for setting the scrolling-related properties:

Using Static Headers and Percent Sizesr.a.d.grid allow you to use static headers even when it is set to 100% width and 100% height. You will see only the grid scrollbars. The browser scrollbars will be hidden. Thus r.a.d.grid can mimic Microsoft Excell application.

Single-row Selectionr.a.d.grid supports client-side selection of rows. You just need to enable the AllowRowSelect property. Then you will be able to select a row by just clicking on one of its cells. However you will not be able to select the Header, Footer or Pager rows. By default the row selection is turned off (AllowRowSelect is false).

Multi-row Selectionr.a.d.grid allows further enhancement thanks to the multi-row selection feature. In order to use it, you need to set AllowMultiRowSelection property to true (default is false).

When you want to select multiple rows, hold the Ctrl key and click to add a row to selection. If you hold the Shift key and click on rows, you will add all rows between the clicked ones.

Alternatively, you may drag a range over the rows, which you want to select.

UseStaticHeaders =trueEven the grid is scrolled, the header row is still visible.

=false

The grid is scrolled and the header is scrolled as well (disappears).

Note that when you use scrolling with static headers, r.a.d.grid columns should declare HeaderStyle.Width.

// declaration<radG:RadGrid runat="server" ... /><ClientSettings><Scrolling AllowScroll="True"UseStaticHeaders="true">

// code...RadGrid RadGrid1 = new RadGrid();RadGrid1.ClientSettings.Scrolling.AllowScroll = true;...

12.6 Selecting

r.a.d.grid v3.0 | 124

© 2002-2006, telerik. All Rights Reserved.

Page 125: r.a.d.grid v3

Below is the code for selection-related properties:

You can use r.a.d.grid client events to perform Postbacks to the server.

In the ASPX file handle the client-side OnRowClick event:

On the server-side you will need to handle these two events: NeedDataSource and Page.PreRender

// declaration<radG:RadGrid AllowMultiRowSelection="true" runat="server" ... /> <ClientSettings> <Selecting AllowRowSelect="True" >

// code...RadGrid RadGrid1 = new RadGrid();RadGrid1.ClientSettings.Selecting.AllowRowSelect = true;RadGrid1.AllowMultiRowSelection = true;

12.7 Performing Postback With Client-Side Events

<radg:radgrid id="RadGrid1" runat="server"><ClientSettings>

<ClientEvents OnRowClick="RowClick"></ClientEvents></ClientSettings>

</radg:radgrid><script type="text/javascript">

function RowClick(index){

var PostBackRowClick = new String();PostBackRowClick = "<%= PostBackRowClick %>";var CustomerID = this.GetCellByColumnUniqueName(this.Rows[index], "CustomerID"PostBackRowClick = PostBackRowClick.replace("RowClicked","RowClicked,CustomerID:"eval(PostBackRowClick);

}</script>

[C#]protected string PostBackRowClick = "";

//should handle RadGrid1.NeedDataSource event private void RadGrid1_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e){

OleDbConnection MyOleDbConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source="OleDbDataAdapter MyOleDbDataAdapter = new OleDbDataAdapter();MyOleDbDataAdapter.SelectCommand = new OleDbCommand("SELECT TOP 10 * FROM Customers"

DataTable myDataTable = new DataTable();MyOleDbConnection. Open();try{

r.a.d.grid v3.0 | 125

© 2002-2006, telerik. All Rights Reserved.

Page 126: r.a.d.grid v3

MyOleDbDataAdapter.Fill(myDataTable);}finally{

MyOleDbConnection. Close();}RadGrid1.DataSource = myDataTable;

}protected override void RaisePostBackEvent( IPostBackEventHandler source, string{

if(!(source == this.RadGrid1)){

this.RaisePostBackEvent( source, eventArgument ); return;

} string postBackEventArgumentData = eventArgument.Split(",");switch (postBackEventArgumentData[0])

{ case "RowClicked":

string rowClickedEventArgumentData = postBackEventArgumentData[1].Split(Response.Write(rowClickedEventArgumentData[0] + ":" + rowClickedEventArgumentData[1]);

break;}

}//should handle Page.PreRender event

private void Page_PreRender( object sender, System.EventArgs e){

this.PostBackRowClick = this.GetPostBackEventReference(RadGrid1, "RowClicked"}

[VB.NET]Protected PostBackRowClick As String

Private Sub RadGrid1_NeedDataSource(ByVal source As Object, ByVal e As Telerik.WebControls.GridNeedDataSourceEventArgs) Dim MyOleDbDataAdapter As New OleDbDataAdapterMyOleDbDataAdapter.SelectCommand = New OleDbCommand("SELECT TOP 10 * FROM Customers"

Dim myDataTable As New DataTable

MyOleDbConnection.Open()Try

MyOleDbDataAdapter.Fill(myDataTable)Finally

MyOleDbConnection.Close() End Try

RadGrid1.DataSource = myDataTableEnd Sub

Protected Overrides Sub RaisePostBackEvent(ByVal source As IPostBackEventHandler, ByVal If Not ( source = Me.RadGrid1 )

MyBase.RaisePostBackEvent( source, eventArgument ) Return

End If Dim postBackEventArgumentData As String() = eventArgument.Split(",") Select Case postBackEventArgumentData(0)

Case "RowClicked" Dim rowClickedEventArgumentData As String() = postBackEventArgumentData(1).Split(Response.Write(rowClickedEventArgumentData(0) & ":" & rowClickedEventArgumentData(1))

End SelectEnd Sub

Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRenderPostBackRowClick = Me.GetPostBackEventReference(RadGrid1, "RowClicked")

End Sub

r.a.d.grid v3.0 | 126

© 2002-2006, telerik. All Rights Reserved.

Page 127: r.a.d.grid v3

r.a.d.grid v3.0 | 127

© 2002-2006, telerik. All Rights Reserved.

Page 128: r.a.d.grid v3

This topic describes how to access the column value (for example for column OrderID) depending on Display/ReadOnly/Visible properties of GridBoundColumn.

l if you set Display = False for OrderID column (displayed in r.a.d.grid), you can access the new OrderID value for the edited grid item (entered by the user) on Update command using the following syntax:

l if you set ReadOnly = True for OrderID column (displayed in r.a.d.grid), you can access the value for the OrderID field in the edited grid item on Update command using a slightly different syntax:

l if you set Visible = False for OrderID column (displayed in r.a.d.grid), you will not be able to access these column values on update.

Additional information concerning the differences between the Display/Visible/ReadOnly properties of GridBoundColumn you can find here (Section 6.2.1).

Each column in r.a.d.grid has a UniqueName property of type string. This property is assigned automatically by the designer (the first time you want to access the dynamically-built columns). You can also set it explicitly, if you like. The automatic generation handles most cases, for example a GridBoundColumn with DataField 'ContactName' would generate a UniqueName of 'ContactName'.

Note that the main idea when retrieving values from grid items is to obtain reference to e.Item and e.Item.OwnerTableView.ParentItem in the ItemComand handler. Then you can get the cell values using column UniqueNames. When you want to access a cell within a grid item, you should use the following code to obtain the right cell to access the Text property:

or

The indexer property is defined for objects of type GridDataItem or GridEditFormItem (or all descendants of GridEditableItem class). In events related to creating, binding or for commands in

13 r.a.d.grid Server-Side

13.1 Accessing Columns

[VB.NET]Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)string newValue = CType(editedItem("OrderID").Controls(0), TextBox).Text[C#]GridEditableItem editedItem = ((GridEditableItem)(e.Item));String newValue = ((TextBox)(editedItem("OrderID").Controls[0])).Text;

[VB.NET]Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)string newValue = editedItem("OrderID").Text[C#]GridEditableItem editedItem = ((GridEditableItem)(e.Item));String newValue = editedItem("OrderID").Text;

13.2 Accessing Cells And Rows

[VB.NET]Dim cell As TableCell = gridDataItem("ColumnUniqueName")[C#]TableCell cell = gridDataItem["ColumnUniqueName"];

[VB.NET]gridDataItem("ColumnUniqueName").Text =[C#]gridDataItem["ColumnUniqueName"].Text =

r.a.d.grid v3.0 | 128

© 2002-2006, telerik. All Rights Reserved.

Page 129: r.a.d.grid v3

items, the event argument has a property Item to access the item that event is fired for. To get an instance of type GridDataItem, use the following code:

The way to access each column for the currently edited row is through their names. Thus if you previously reordered the columns in the grid you will still be able to obtain the value from the respective column although it actually has new location in the grid hierarchy.

Here is a snippet of the code which demonstrates column value access for the edited row:

r.a.d.grid supports grouping of items in a way similar to Microsoft Outlook®. You can even have multilevel grouping based on different criteria. There is a special area at the top of the grid, in which the grouping options are displayed. This is the GridGroupPanel. When a TableView is grouped, all group fields appear in this GroupPanel as elements along with the sort order - e.g. Country, Order Date.You can easily add more sorting fields and rearrange the existing ones by just dragging and dropping the header of the column you wish to use for grouping. For this purpose set AllowDragToGroup property to true.

You can access the group panel using the GroupPanel property of RadGrid. You should use PanelStyle and PanelItemsStyle to control the style of the group panel and its items.

[VB.NET]'presume e is the event argument objectIf(TypeOfe.Item IsGridDataItem) Then

Dim gridDataItem AsGridDataItem = e.Item

End If[C#]//presume e is the event argument objectif (e.Item is GridDataItem){

GridDataItem gridDataItem = e.Item as GridDataItem;}

[C#]DataRow[] changedRows = this.OrdersData.Tables["Orders"].Select( "OrderID = " + editedItem[

[VB.NET]Dim changedRows() As DataRow = Me.OrdersData.Tables("Orders").Select(("OrderID = " + editedItem(

13.3 Grouping

ASPX Code<radG:RadGrid runat="server" ... /><ClientSettingsAllowDragToGroup="True"/>

C# CodeRadGrid RadGrid1 = new RadGrid();RadGrid1.ClientSettings.AllowDragToGroup = true;...

r.a.d.grid v3.0 | 129

© 2002-2006, telerik. All Rights Reserved.

Page 130: r.a.d.grid v3

Once grouped, you can additionally sort the grid data, using the default sorting mechanism.

When a TableView is grouped, RadGrid automatically adds a special column -GridGroupSplitterColumn. It holds the expand/collapse buttons, used to expand/collapse all items, that belong to a group.

When you want your data sorted and grouped, you need to provide the right expression syntax.

Controlling group-by behaviorWhen you want to enable the group-by functionality, you need to set RadGrid.GroupingEnabled to true. You can set a column not to be used for grouping with Groupable property set to false.

RadGrid.ShowGroupPanel shows/hides the group panel. However even if this is set to true, the Group Panel will not appear if RadGrid.GroupingEnabled is false (i.e. if grouping is disabled).

r.a.d.grid v3.0 | 130

© 2002-2006, telerik. All Rights Reserved.

Page 131: r.a.d.grid v3

13.3.1 Using Grouping with custom pagingThere is no universal mechanism for grouping when custom paging is allowed. The reason for this is that with the custom paging mechanism you fetch only part of the whole information from the grid data source. Thus when the grouping event is triggered the grid is restricted from operating with the entire available data and is not able to group the items accurately. Furthermore, the aggregate functions as Count, Sum , etc. (covering operations with the whole set of grid items) will return incorrect results.

A workaround solution could be to use hierarchy in the grid instead of grouping to single out the grid items logically and visually according to custom criteria. Thus you will be able to use custom paging without further limitations.

Another approach is to build your own complex SQL statements which to get the entire available data from the grid data source and then group the items in the grid with custom code logic.

The final alternative is to use standard paging with grouping.

13.3.2 Controlling the Group Load ModeYou can control where the grouping will be handled using the GroupLoadMode property of GridTableView. There are two options:

l Server-side - GridTableView.GroupLoadMode.Server - this is the default behavior. Groups are expanded after postback to the server for example:

l Client-side - GridTableView.GroupLoadMode.Client. Groups will be expanded client-side and no postback will be performed.

and set the client setting AllowGroupExpandCollapse to true:

13.3.3 Collapse all items on groupingIn case you want to collapse all groups when r.a.d.grid is grouped by column you should know that ExpandCollapseColumn make sense only in hierarchy mode.When r.a.d.grid control is grouped by column, you could look for GridGroupHeaderItem. The code bellow could be added to your code-behind in order to have the "all groups collapsed" effect:

Grouping is always applied before any other column sorting.

<MasterTableView GroupLoadMode="Server">

<MasterTableView GroupLoadMode="Client">

<ClientSettings AllowGroupExpandCollapse="True">

r.a.d.grid v3.0 | 131

© 2002-2006, telerik. All Rights Reserved.

Page 132: r.a.d.grid v3

C#

//Collapse all group header itemsprivate void CollapseAll(){

foreach( GridItem item inRadGrid1.MasterTableView.Controls[0].Controls ){

if( item is GridGroupHeaderItem ){

item.Expanded = false;}

}}private void Page_Load(object sender, System.EventArgs e){

if( !IsPostBack ){

this.RadGrid1.Rebind(); // this would bind the grid calling NeedDataSource//grid would be smart enough to suppress further binding//then collapse all groupsthis.CollapseAll();

}}//You should also consider handling ItemCommand event the following way:private void RadGrid1_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e){

if ( e.CommandName == "Sort" || e.CommandName == "Page" ) //add more commands if{

//execute command - sorting, paging etc, then bind automaticallye.ExecuteCommand( e.Item );//state that no further command execution is necessarye.Canceled = true;//collapse again all groupsthis.CollapseAll();

}}VB.NET

'Collapse all group header itemsPrivate Sub CollapseAll()

Dim item As GridItem For Each item In RadGrid1.MasterTableView.Controls(0).Controls

If TypeOf item Is GridGroupHeaderItem Thenitem.Expanded = False

End If Next item

End Sub 'CollapseAll

Private Sub Page_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load If Not IsPostBack Then

Me.RadGrid1.Rebind() ' this would bind the grid calling NeedDataSource 'grid would be smart enough to suppress further binding 'then collapse all groups Me.CollapseAll()

End IfEnd Sub 'Page_Load

Private Sub RadGrid1_ItemCommand([source] As Object, e As Telerik.WebControls.GridCommandEventArgs) Handles RadGrid1.ItemCommand If e.CommandName = "Sort" Or e.CommandName = "Page" Then 'add more commands if necessary

'execute command - sorting, paging etc, then bind automaticallye.ExecuteCommand(e.Item)

'state that no further command execution is necessarye.Canceled = True

'collapse again all groups

r.a.d.grid v3.0 | 132

© 2002-2006, telerik. All Rights Reserved.

Page 133: r.a.d.grid v3

This code will have effect if you already grouped by a column, i.e. if you add another group-by expression (see below), client-side grid groups would not collapse.

Group-by expression syntaxEach GridTableView object has a GroupByExpressions property, which is a collection of group expressions.

Adding GridGroupByExpression to this collection will cause the current table-view to display the items sorted and divided in groups separated by GridGroupHeaderItem, which display common group and aggregate field values. The GridGroupByExpression.Expression property defines the expressions syntax:

fieldname[ alias]|aggregate(fieldname)[ alias][, ...] Group By fieldname[ sort][, ...]

l fieldname - the name of any field from RadGrid.DataSource

l alias - the alias string. This cannot contain blanks or other reserved symbols like ',', '.' etc.

l aggregate - any of - min, max, sum, count, last, first etc (the same as in AggregateFunctionenumeration )

l sort: acs or desc - the sort order of the grouped items (ascending or descending)

Example expression:

Each column has its own group-by expression, which is used to group by it when that column is dropped on the GroupPanel region - client side. If no group by expression is specified, RadGrid will use the DataField, to which that column is bound (see GetDefaultGroupByExpression method).

13.3.4 Customizing GroupHeaderItemYou can get a complete control over the display of the fields in the GridGroupHeaderItem and even perform calculations and display the results in the group header.The DataItem property of a grid group header item is different from the items DataItems of the other items. It is always of type DataRowView and contains all the columns representing a group-field with the corresponding value. For example, if the grid is currently grouped by a field named Country the DataItem of any GridGroupHeaderItem will contain ["Country"], which is equal to the corresponding country for this group.

Me.CollapseAll()

End IfEnd Sub 'New

Country, City, count(Country) Items, ContactName Group By Country, City desc

C# Codeprivate void RadGrid1_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e){

r.a.d.grid v3.0 | 133

© 2002-2006, telerik. All Rights Reserved.

Page 134: r.a.d.grid v3

13.3.5 Performing calculations in GroupHeaderItemIn the following example we used the ItemDataBound event of the grid and accessed the totaland count field values from the grid group-by expression. These values can be retrieved from the GridGroupHeaderItem DataItem field.

You can have r.a.d.grid to handle the sorting automatically if you set the RadGrid.AllowSortingproperty to true. Then you can use the buttons displayed on the column headers or programmatically manipulate GridTableView.SortExpressions collection to sort the grid items by one or more data-fields (used as a sorting criteria).

There are three sorting modes in r.a.d.grid:

if ( e.Item is GridGroupHeaderItem ){GridGroupHeaderItem item = (GridGroupHeaderItem)e.Item;DataRowView groupDataRow = (DataRowView)e.Item.DataItem;

//Clear the present text of the cellitem.DataCell.Text = "";foreach( DataColumn column in groupDataRow.DataView.Table.Columns)

//Check the condition and add only the field you need if ( column.ColumnName == "Country" ){item.DataCell.Text += "Customized display - Country is " + groupDataRow["Country"].ToString();

}}

}

C# Codeprivate void RadGrid1_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e){

if ( e.Item is GridGroupHeaderItem ){

GridGroupHeaderItem item = (GridGroupHeaderItem)e.Item;DataRowView groupDataRow = (DataRowView)e.Item.DataItem;item.DataCell.Text+= " avg: ";item.DataCell.Text += ((System. Decimal) groupDataRow["total"] /( int.Parse(groupDataRow["count"].ToString()))).ToString();

}}

13.4 Sorting

Ascending Descending No Sort

r.a.d.grid v3.0 | 134

© 2002-2006, telerik. All Rights Reserved.

Page 135: r.a.d.grid v3

When you click on a column r.a.d.grid will add the GridColumn.SortExpression string to the corresponding GridTableView.SortExpressions collection. Removing the sorting will remove an item from that collection.

Multi-Column SortingIf GridTableView.AllowMultiColumnSorting is set to true, more than one column sort expression can be added. The sorting order is the same as the sequence of expressions in GridTableView.SortExpressions.On the example below, you see the grid sorted by Country ascending and then by City descending:

Sorting Programmatically

When you use the buttons that appear on the grid header item, clicking once will cause items to be sorted by that column ascending. Then an image

will appear to indicate that the column is sorted ascending.

Click on the header again to sort by that column descending. The sorting indicator will change to to indicate that column is sorted descending.

The third click will remove the sorting by that column.

r.a.d.grid v3.0 | 135

© 2002-2006, telerik. All Rights Reserved.

Page 136: r.a.d.grid v3

Programmatically grid sort can be manipulated through GridSortExpression class. An instance of this class represents a single 'column' sort.You should use similar code to the following :

SortExpressions items are preserved in the view state for a GridTableView in each hierarchy level.

Expression string should be a data-field name - the same as one to be use in DataView.Sort expression. Sorting is done internally by a DataView indeed. You should be sure that you have specified Expression property of GridSortExpression class the right way or an exception will be thrown when the grid is databound.

When using the Sort property of GridColumn objects you can also specify the button type of the button that would appear in GridTableView's header. You should assign a value of GridColumn.HeaderButtonType property accordingly to one of the values in GridHeaderButtonTypeenumeration. When using a GridTemplateColumn or other custom command-buttons to apply sorting you should set command name to Sort and sort-expression as a command argument.

In this case r.a.d.grid will handle the sorting and put the sorting indicator image automatically in the column header.

GridSortExpression expression = new GridSortExpression();

expression.FieldName = 'SortFieldName';

expression.SortOrder = GridSortOrder.Descending;

this.RadGrid1.MasterTableView.SortExpressions.AddSortExpression( expression );

this.RadGrid1.MasterTableView.Rebind();

<radg:GridTemplateColumn SortExpression="CompanyName">

<HeaderTemplate>

<asp:Button id="Button42" Text="GridTemplateColumn" Title="Sort by CompanyName" CommandName='Sort' CommandArgument='CompanyName' runat=

</HeaderTemplate>

...

13.5 Paging

r.a.d.grid v3.0 | 136

© 2002-2006, telerik. All Rights Reserved.

Page 137: r.a.d.grid v3

When displaying a large set of data in web applications it is a common practice that only a small sub-set of the data at a time would be transferred to the client and operated with. r.a.d.grid supports this functionality automatically and also provides a set of events, helper methods and properties if the paging operation requires custom intervention.

Set the RadGrid.AllowPaging property to true (default is false) to have r.a.d.grid handle paging.Set the RadGrid.AllowCustomPaging property to true if you want to handle paging in a custom manner, or leave it to its default value - false - to allow r.a.d.grid handle paging automatically.

If paging is enabled, r.a.d.grid will render pager item(s) (GridPagerItem) on the top and/or bottom of each GridTableView displayed in the hierarchy.

13.5.1 Pager AppearanceThe appearance of the pager item can be controlled using GridTableView.PagerStyle property. As most of appearance options, PagerStyle of each GridTableView can be predefined using RadGrid.PagerStyle property - this would apply to all GridTableViews in the hierarchy unless specified other for a certain table-view.As PagerStyle extends the TableItemStyle class the settings could apply to item's fore-color, back-color, border style, font etc. GridPagerStyle provides also properties to control the position of the items' PagerStyle.Position - Top, Bottom or TopAndBottom and type of pager buttons that appear.

The Pager buttons allow the user to navigate through the pages - change the display page by setting next or previous or use a page number to directly switch page. Use GridTableView.PagerStyle.Modeproperty to control the mode pager buttons would be display and would function. Use GridPagerMode.NumericPages to display a button for each page with the corresponding page number. Use GridPagerMode.PrevNext to specify that only buttons for previous/next page would appear.

All properties controlling paging behavior can be set using either development environment designers (Section 9.1) or programmatically. The values set programmatically are persisted into the view-state providing consistency in grid's page navigation and ease their use.

If you use any other button(s) to control paging in r.a.d.grid in a custom manner, you can use command button(s) with CommandName 'Page' and CommandArgument 'Next', 'Prev', or a number of any page -ex. CommandArgument = "42".

13.5.2 Pager templates

Note that using custom paging in your r.a.d.grid may affect the grouping functionality. Additional details are available here (Section 13.3).

r.a.d.grid v3.0 | 137

© 2002-2006, telerik. All Rights Reserved.

Page 138: r.a.d.grid v3

Pager item can use templates for setting its appearance and features. All command buttons in the template can take advantage of the command API. For example a button with CommandName "Page" and CommandArgument of "Last" will force r.a.d.grid to go to the last page when clicked. No additional code is necessary.

Using declarative binding expressions command buttons in the pager can control their visibility based on various paging-related properties provided by the PagerItem.Paging instance.

<PagerTemplate><table border="0" cellpadding="5" height="18px" width="100%">

<tr><td style="border-style:none;"><asp:LinkButton ID="LinkButton1" CommandName="Page" CausesValidation="false" CommandArgument=</td><td style="border-style:none;"><asp:LinkButton ID="LinkButton5" CommandName="Page" CausesValidation="false" CommandArgument=</td><td style="border-style:none;"><asp:TextBox ID="tbPageNumber" runat="server" Columns="3" Text='<%# (int)DataBinder.Eval(Container,

<asp:RangeValidator runat="Server" ID="RangeValidator1" ControlToValidate="tbPageNumber"Type="Integer"MaximumValue='<%# DataBinder.Eval(Container, "Paging.PageCount") %>'ErrorMessage='<%# "Value must be in the range of 1 - " + DataBinder.Eval(Container, Display="Dynamic"></asp:RangeValidator>

</td><td style="border-style:none;"><asp:LinkButton ID="LinkButton4" runat="server" CommandName="CustomChangePage">Go</asp:LinkButton></td><td style="border-style:none;"><asp:LinkButton ID="LinkButton3" CommandName="Page" CausesValidation="false" CommandArgument=</td><td style="border-style:none;"><asp:LinkButton ID="LinkButton2" CommandName="Page" CausesValidation="false" CommandArgument=</td><td style="border-style:none;width:100%" align="right"><asp:LinkButton ID="LinkButton6" CommandName="RebindGrid" CausesValidation="false" runat=</td></tr></table>

</PagerTemplate><PagerTemplate>

<table border="0" cellpadding="5" height="18px" width="100%"><tr>

<td style="border-style:none;"><asp:LinkButton ID="LinkButton1" CommandName="Page" CausesValidation="false" CommandArgument=</td><td style="border-style:none;"><asp:LinkButton ID="LinkButton5" CommandName="Page" CausesValidation="false" CommandArgument=</td><td style="border-style:none;"><asp:TextBox ID="tbPageNumber" runat="server" Columns="3" Text='<%# DataBinder.Eval(Container,

<asp:RangeValidator runat="Server" ID="RangeValidator1" ControlToValidate="tbPageNumber"Type="Integer"MaximumValue='<%# DataBinder.Eval(Container, "Paging.PageCount") %>'ErrorMessage='<%# "Value must be in the range of 1 - " & DataBinder.Eval(Container, Display="Dynamic"></asp:RangeValidator>

</td><td style="border-style:none;"><asp:LinkButton ID="LinkButton4" runat="server" CommandName="CustomChangePage">Go</asp:LinkButton></td><td style="border-style:none;"><asp:LinkButton ID="LinkButton3" CommandName="Page" CausesValidation="false" CommandArgument=</td><td style="border-style:none;"><asp:LinkButton ID="LinkButton2" CommandName="Page" CausesValidation="false" CommandArgument=

r.a.d.grid v3.0 | 138

© 2002-2006, telerik. All Rights Reserved.

Page 139: r.a.d.grid v3

13.5.3 Retain the selected row on paging In some scenarios you may want to select a row in r.a.d.grid , then use paging to view another grid page and on return to have the previously selected row preserved. You can use two Session variables to save the pageIndex and the selectedRowIndex. To modify these variables you should check for e.CommandName == "Select" in the ItemCommand handler. To ensure the preservation of the selected row you have to meet e.CommandName = "Page" condition in the same event handler. Then after retrieving the pageIndex and the selectedRowIndex values from the Session and verifying that:

simply add the selectedRowIndex to the RadGrid1.SelectedIndexes array.

The complete code for this example can be found here (http://www.telerik.com/Default.aspx?PageId=2514&b454K=qak&b454T=RfY).

</td><td style="border-style:none;width:100%" align="right"><asp:LinkButton ID="LinkButton6" CommandName="RebindGrid" CausesValidation="false" runat=</td></tr></table>

</PagerTemplate>

CommandName CommandArgument Description

Page First Goes to the first page

Page Last Goes to the last page

Page An Integer ("5" for example) Go to the specified page

Page Next Goes to the next page

Page Previous Goes to the previous page

RadGrid1.CurrentPageIndex == pageIndex && selectedRowIndex > -1

Note: The example will work when you select rows using the Select button column in the grid.

C# Codeprivate void RadGrid1_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)

{ if(e.CommandName == "Page"){

e.ExecuteCommand(source);e.Canceled = true;

RadGrid1.SelectedIndexes.Clear(); if(Session["SelectedRowIndex"] != null){

selectedRowIndex = (int)Session["selectedRowIndex"];pageIndex = (int)Session["pageIndex"];

if(RadGrid1.CurrentPageIndex == pageIndex && selectedRowIndex > -1){

RadGrid1.SelectedIndexes.Add(selectedRowIndex);}

}} if(e.CommandName == "Select"){

Session[ "selectedRowIndex"] = e.Item.ItemIndex;Session[ "pageIndex"] = RadGrid1.CurrentPageIndex;

}}

13.6 Filtering

r.a.d.grid v3.0 | 139

© 2002-2006, telerik. All Rights Reserved.

Page 140: r.a.d.grid v3

Filtering in r.a.d.grid can be enabled/disabled using RadGrid.AllowFilteringByColumn or GridTableView.AllowFilteringByColumn properties. Then each column that supports filtering (GridBoundColumn, GridCheckBoxColumn, etc) shows a filter box in a GridFilteringItem beneath the corresponding header. After pressing the filter button, next to the filter box the grid displays only the records matching the filter criteria regarding the settings of all filter boxes.

The filtering menu is independent for each column in RadGrid. Each column has a DataType property, which can define the filtering expressions for that column. This property is set automatically by r.a.d.gridwhen data binding. However you can set this property explicitly and change the data type of a column and therefore its filtering expressions.

For example you have a column with data type set to integer and for some reason you need to use "StartsWith" filtering expression. As this expression is not available for integers r.a.d.grid will not show it in the dropdown list. In order to use "StartsWith", you need to set the DataType for that column explicitly to string.

All filters in a single table are applied using AND operator, i.e. only items (grid rows) that comply all filters will be displayed.

When you have more than one value to filter on, values should be entered separated by a space.

RadGrid filters data internally, after data binding. In addition to the available filter expressions, you can create your own filter using the GridFilterFunction class.

User can set a filter expression based on the rules specified in the corresponding column properties: GridColumn.FilterFormatString.

You can set the default filter function and the default filter value that will appear in the filter text box through the properties of GridColumn - CurrentFilterFunction and CurrentFilterValue (r.a.d.gridwill display this value as an initial filter but will NOT perform the filtering).

You can specify the group of possible filter functions that r.a.d.grid would display setting the FilterListOptions property. It has three possible values:

l VaryByDataType - the default value. Filter functions list depends on the DataType of the column. For example filter functions "Starts with", "Ends With... " will not be available for columns with DataType integer.

l VaryByDataTypeAllowCustom - the same as the above, but additional custom filter functions will be enabled. This means that user can specify key words and fileds form the datasource in the filter text box.

l AllowAllFilters - all filtering functions will be available.

Filtering can be fully customized setting the value of GridTableView.FilterExpression property. Note that setting the value of this property will override all other filtering done by r.a.d.grid.

In some cases when you have r.a.d.grid positioned absolute, you may find the filtering popup hidden behind r.a.d.grid . You can easily fix the problem by setting the Z-index of the corresponding element in the ASPX:

It is up to the developer to set the proper constraints on event handler ItemCommand when command name is "Filter".

<radG:RadGrid id="RadGrid1" style = "Z-INDEX: 101; LEFT: 64; POSITION: absolute..."

r.a.d.grid v3.0 | 140

© 2002-2006, telerik. All Rights Reserved.

Page 141: r.a.d.grid v3

If you work in hierarchy mode, you can define when the DataBind for GridTableView will occur. In order to do this, you need to set the following property:

GridTableView.HierarchyLoadMode

The possible values are:

l HierarchyLoadMode.ServerBind - all child GridTableViews will be bound immediately when DataBind occurs for a parent GridTableView or RadGrid.

l HierarchyLoadMode.ServerOnDemand - DataBind of a child GridTableView would only take place when an item is Expanded (see GridItem.Expanded). This is the default value.

l HierarchyLoadMode.Client is similar to HierarchyLoadMode.ServerBind, but items are expanded client-side, using JavaScript manipulations, instead of postback to the server. In order to use client-side hierarchy expand, you will need to set also ClientSettings.AllowExpand.Collapse to true.

Changing this property value impacts the performance the following way:

l In HierarchyLoadMode.ServerBind mode:

¡ The roundtrip to the database happens only once - when the grid is bound.

¡ The ViewState holds all data for the detail tables.

¡ Only detail table-views of the expanded items are rendered.

¡ You need to postback to the server to in order to expand an item.

l In HierarchyLoadMode.ServerOnDemand mode:

¡ The roundtrip to the database happens when the grid is bound and when an item is expanded.

¡ The ViewState holds data only for the visible Items (the smallest possible ViewState).

¡ Only detail table-views of the expanded items are rendered.

¡ You need to postback to the server in order to expand an item.

l In HierarchyLoadMode.Client mode:

¡ The roundtrip to the database happens only when grid is bound.

¡ The ViewState holds all detail tables data.

¡ All items are rendered - even if not visible (not expanded).

¡ No postback to the server is needed to expand an item - expand/collapse of hierarchy items is managed client-side.

Using different load modes in r.a.d.grid

As HierarchyLoadMode is a GridTableView setting (not RadGrid property) you can even more fine tune the way that r.a.d.grid handles loading of hierarchy tables. You can set HierarchyLoadMode.Client for tables that need fast view and HierarchyLoadMode.ServerBind for tables that are less likely to be accessed.

Thus you can balance the loading of the grid between:

l the client - this will require more bandwidth but will assure less load to the server and database and quicker expand.

l the server - will save some client-load for the inner tables of the grid.

The example below shows the advanced hierarchy model of r.a.d.grid with mixed mode expand/collapse (client-side and server-side). A three level hierarchy is demonstrated with Customer Master Table and two nested Detail Tables: Orders and OrderDetails. The first level of hierarchy uses client-side (HierarchyLoadMode.Client) expand and the second level uses server-side mode (HierarchyLoadMode.ServerBind)

13.7 Hierarchy Load

r.a.d.grid v3.0 | 141

© 2002-2006, telerik. All Rights Reserved.

Page 142: r.a.d.grid v3

The DataSourcePersistenceMode property of GridTableView indicates where RadGrid would store its data and determine how DataSource of the GridTableView will be persisted on PostBack. It has two settings:

l NoPersistence- DataSource (or generated html tables) data will not be stored. RadGrid will fire NeedDataSource event and will bind after each postback

l ViewState - RadGrid stores data in the view-state bag (default).

Some operations in r.a.d.grid, like groups or hierarchical views expand/collapse, require that the DataSourcePersistenceMode is set to ViewState. If no data is persisted for items in r.a.d.grid(NoPersistence mode) then the state of items is lost through postback. Generally, data-source persistence optimization should be used if the small size/speed of a page, showing r.a.d.grid, is crucial for the application. If the value of this property is NoPersistence, RadGrid will fire NeedDataSource and will bind after each post back to restore its items. RadGrid and its table-views manage the state of the following features while in NoPersistence mode:

l Indexes of selected items

l Indexes of edited items

l Group-by expressions and settings (but not the expanded state of the grouped items)

l Sort expressions

l Style properties (but not if any style is applied on a single cell or row in ItemDataBound event)

l Columns order, and other column properties

l All settings concerning hierarchy structure (but not the expanded state of the items)

Following is a small application based on the WebMail example that demonstrates a way to persist runtime settings of r.a.d.grid in a single text-based format. The format is almost identical to ViewStateformat ASP.NET Page use, so it is possible to persist the settings on any medium - session, application

13.8 Optimizing Performance

13.9 Saving r.a.d.grid Settings On a Per User Basis

r.a.d.grid v3.0 | 142

© 2002-2006, telerik. All Rights Reserved.

Page 143: r.a.d.grid v3

variables, database, etc. For your convenience, the functionality is isolated in a single class called GridSettingsPersister. It is designed to save, load into r.a.d.grid the following runtime settings:

l Group-by expressions

l Sort expressions

l Columns order and width

You can modify the settings to fit your case:

[C#]using System;using System.Collections;using System.IO;using System.Web.UI;using System.Web.UI.WebControls;using Telerik.WebControls;

namespace WebApplication1{ public class GridSettingsPersister{ private RadGrid gridInstance;

public GridSettingsPersister( RadGrid gridInstance ){this.gridInstance = gridInstance;

}

public string SaveSettings(){object[] gridSettings = new object[3];

//Save groupByGridGroupByExpressionCollection groupByExpressions = gridInstance.MasterTableView.GroupByExpressions;object[] groupExpressions = new object[groupByExpressions.Count];

int count = 0;foreach( GridGroupByExpression expression in groupByExpressions ){groupExpressions[count] = ((IStateManager)expression).SaveViewState();count++;

}

gridSettings[0] = groupExpressions;

//Save sort expressionsgridSettings[1] = ((IStateManager)gridInstance.MasterTableView.SortExpressions).SaveViewState();

//Save columns order int columnsLength = gridInstance.MasterTableView.Columns.Count +

gridInstance.MasterTableView.AutoGeneratedColumns.Length;

Pair [] columnOrder = new Pair[ columnsLength ];

ArrayList allColumns = new ArrayList( columnsLength );

allColumns.AddRange(gridInstance.MasterTableView.Columns );allColumns.AddRange(gridInstance.MasterTableView.AutoGeneratedColumns);

int i = 0;foreach( GridColumn column in allColumns ){Pair p = new Pair();p.First = column.OrderIndex;p.Second = column.HeaderStyle.Width;

columnOrder[i] = p;

r.a.d.grid v3.0 | 143

© 2002-2006, telerik. All Rights Reserved.

Page 144: r.a.d.grid v3

i++;}

gridSettings[2] = columnOrder;

LosFormatter formatter = new LosFormatter();

StringWriter writer = new StringWriter();formatter.Serialize( writer, gridSettings );

return writer.ToString();}

public void LoadSettings( string settings ){LosFormatter formatter = new LosFormatter();StringReader reader = new StringReader( settings );

object[] gridSettings = (object[])formatter.Deserialize( reader );

//Load groupByGridGroupByExpressionCollection groupByExpressions = this.gridInstance.MasterTableView.GroupByExpressions;groupByExpressions.Clear();

object[] groupExpressionsState = (object[])gridSettings[0];

int count = 0;foreach( object obj in groupExpressionsState ){GridGroupByExpression expression = new GridGroupByExpression();((IStateManager)expression).LoadViewState( obj );groupByExpressions.Add( expression );count++;

}

//Load sort expressionsthis.gridInstance.MasterTableView.SortExpressions.Clear();((IStateManager)this.gridInstance.MasterTableView.SortExpressions).LoadViewState( gridSettings[1] );

//Load columns order int columnsLength = this.gridInstance.MasterTableView.Columns.Count +

this.gridInstance.MasterTableView.AutoGeneratedColumns.Length;

Pair [] columnOrder = (Pair[])gridSettings[2];

if ( columnsLength == columnOrder.Length){ArrayList allColumns = new ArrayList( columnsLength );

allColumns.AddRange(this.gridInstance.MasterTableView.Columns );allColumns.AddRange(this.gridInstance.MasterTableView.AutoGeneratedColumns);

int i = 0;foreach( GridColumn column in allColumns ){column.OrderIndex = (int)columnOrder[i].First;column.HeaderStyle.Width = (Unit)columnOrder[i].Second;

i++;}

}}

}}}[VB.NET]

r.a.d.grid v3.0 | 144

© 2002-2006, telerik. All Rights Reserved.

Page 145: r.a.d.grid v3

Namespace WebApplication1Imports SystemImports System.CollectionsImports System.IOImports System.Web.UIImports System.Web.UI.WebControlsImports Telerik.WebControls

Public Class GridSettingsPersister

Private gridInstance As RadGrid

Public Sub New(ByVal gridInstance As RadGrid)MyBase. New

Me.gridInstance = gridInstance End Sub

Public Function SaveSettings() As String Dim gridSettings() As Object = New Object((3) - 1) {} 'Save groupBy Dim groupByExpressions As GridGroupByExpressionCollection = gridInstance.MasterTableView.GroupByExpressions Dim groupExpressions() As Object = New Object((groupByExpressions.Count) Dim count As Integer = 0 For Each expression As GridGroupByExpression In groupByExpressions

groupExpressions(count) = CType(expression,IStateManager).SaveViewStatecount = (count + 1)

NextgridSettings(0) = groupExpressions

'Save sort expressionsgridSettings(1) = CType(gridInstance.MasterTableView.SortExpressions,IStateManager).SaveViewState

'Save columns order Dim columnsLength As Integer = (gridInstance.MasterTableView.Columns.Count + gridInstance.MasterTableView.AutoGeneratedColumns.Length) Dim columnOrder() As PaircolumnsLength

Dim allColumns As ArrayList = New ArrayList(columnsLength)allColumns.AddRange(gridInstance.MasterTableView.Columns)allColumns.AddRange(gridInstance.MasterTableView.AutoGeneratedColumns)

Dim i As Integer = 0 For Each column As GridColumn In allColumns

Dim p As Pair = New Pairp.First = column.OrderIndexp.Second = column.HeaderStyle.WidthcolumnOrder(i) = pi = (i + 1)

NextgridSettings(2) = columnOrder

Dim formatter As LosFormatter = New LosFormatter Dim writer As StringWriter = New StringWriterformatter.Serialize(writer, gridSettings)

Return writer.ToString End Function

Public Sub LoadSettings(ByVal settings As String) Dim formatter As LosFormatter = New LosFormatter Dim reader As StringReader = New StringReader(settings) Dim gridSettings() As Object = CType(formatter.Deserialize(reader),Object 'Load groupBy Dim groupByExpressions As GridGroupByExpressionCollection = Me.gridInstance.MasterTableView.GroupByExpressionsgroupByExpressions.Clear

Dim groupExpressionsState() As Object = CType(gridSettings(0),Object()) Dim count As Integer = 0 For Each obj As Object In groupExpressionsState

Dim expression As GridGroupByExpression = New GridGroupByExpressionCType(expression,IStateManager).LoadViewState(obj)groupByExpressions.Add(expression)count = (count + 1)

r.a.d.grid v3.0 | 145

© 2002-2006, telerik. All Rights Reserved.

Page 146: r.a.d.grid v3

The ASP.NET page framework provides a technique called event bubbling that allows a child control to propagate events up its containment hierarchy. Event bubbling enables events to be raised from a more convenient location in the controls hierarchy and allows event handlers to be attached to the original control as well as to the control that exposes the bubbled event.

When an event bubbles from a child control, RadGrid would fire ItemCommand event. A child control (as a Button server control) raises a bubble event if you set any value in CommandName property.For example the command name is "DoInsert" , then RadGrid will fire ItemCommandEvent and the event argument of the handler function (generally the "e" variable ) will have the same command name , i.e. "DoInsert" as a value for the e.CommandName property. Moreover, the e.Item argument will be a reference to the Item which is the parent of the control raised the bubble event (i.e. the Item where the button resides).

Some command names are predefined in RadGrid and the control will respond to them automatically (like the value of RadGrid.InitInsertCommandName constant or RadGrid.RefreshGridCommandName). The integrated paging in RadGrid is also based on commands, with CommandName "Page" (or RadGrid.PageCommandName) and command various arguments for different paging operations like the string "Next","Prev" or "First".

Here is a list of the available command names in r.a.d.grid:

Next 'Load sort expressions Me.gridInstance.MasterTableView.SortExpressions.ClearCType( Me.gridInstance.MasterTableView.SortExpressions,IStateManager).LoadViewState(gridSettings(1))

'Load columns order Dim columnsLength As Integer = (Me.gridInstance.MasterTableView.Columns.Count + Dim columnOrder() As Pair = CType(gridSettings(2),Pair()) If (columnsLength = columnOrder.Length) Then

Dim allColumns As ArrayList = New ArrayList(columnsLength)allColumns.AddRange( Me.gridInstance.MasterTableView.Columns)allColumns.AddRange( Me.gridInstance.MasterTableView.AutoGeneratedColumns)

Dim i As Integer = 0 For Each column As GridColumn In allColumns

column.OrderIndex = CType(columnOrder(i).First,Integer)column.HeaderStyle.Width = CType(columnOrder(i).Second,Unit)i = (i + 1)

Next End If

End Sub End Class

End Namespace

13.10 Event Bubbling in r.a.d.grid

Fired By controls within DataItems - showing and editing data

CancelCommandName Represents the Cancel command name. Fires RadGrid.CancelCommand event and sets Item.Editto false for the parent Item.

DeleteCommandName

Represents the Delete command name. Fires RadGrid.DeleteCommand event. Under .Net 2.0 Perfroms automatic delete operation and then sets Item.Edit to false.

UpdateCommandName

Represents the Update command name. Fires RadGrid.UpdateCommand event. Under .Net 2.0 Perfroms automatic update operation and then sets Item.Edit to false.

EditCommandName Represents the Edit command name.

SelectCommandName Represents the Select command name. Sets Item.Selected to true.

DeselectCommandName Represents the Deselect command name. Sets

r.a.d.grid v3.0 | 146

© 2002-2006, telerik. All Rights Reserved.

Page 147: r.a.d.grid v3

This examples can help you with this approach (look at the ASCX code):http://www.telerik.com/r.a.d.controls/Grid/Examples/DataEditing/UserControlEditForm/DefaultCS.aspx

The user control buttons [Update] and [Cancel] have CommandName property associated. Both commands are handled by RadGrid.

<td align="right" colspan="2"><asp:button id="btnUpdate" text="Update" CssClass="button" style="color:green;"

commandname="Update"></asp:button><asp:button id="btnCancel" text="Cancel" CssClass="button" runat="server" causesvalidation=

commandname="Cancel"></asp:button></td>

</tr>

When "Update" command bubbles, RadGrid will fire first ItemCommand event, and if the event is not canceled (e.Canceled set to false) then RadGrid will fire UpdateCommand event and then it will refresh automatically.

The "Cancel" command will close the edited item and will automatically refresh the grid.

Generally UserControl does not implement IPostBackEventHandler. That is why, to achieve your goal you need to implement the following interface when needed. Here is the bare bone logic:

Item.Selected to false.

Fired by controls within Items that have child items (in hierarchy structures or group structures)

ExpandCollapseCommandName toggles the expanded state of the child items.

Can be fired by controls within any Item

InitInsertCommandNameBy default grid renders an image button in the CommandItem. Opens the insert item.

PerformInsertCommandName

Fires RadGrid.InsertCommand event. Under .Net 2.0 Perfoms automatic insert operation and closes the insert item.

RebindGridCommandNameBy default grid renders an image button in the CommandItem. Forces RadGrid.Rebind

SortCommandName

Represents the Sort command name. By default it is fired by image buttons in the header item when Sorting is enabled. The argument for the SortCommand must be the DataField name for the DataField to be sorted.

Fired by controls within PagerItem

PageCommandName Represents the Page command name. See also: Paging (Section 13.5)

13.11 Raising Postback From User Control

[C#]public class WebUserControl1 : System.Web.UI.UserControl, IPostBackEventHandler

{ public void RaisePostBackEvent(string eventArgument){}

}

[VB.NET]Public Class WebUserControl1

Inherits System.Web.UI.UserControl Implements IPostBackEventHandler Public Sub RaisePostBackEvent(ByVal eventArgument As String)

r.a.d.grid v3.0 | 147

© 2002-2006, telerik. All Rights Reserved.

Page 148: r.a.d.grid v3

If you want to raise post-back event using __doPostBack() or RadGridNamespace.AsyncRequest()(i.e. in r.a.d.grid in AJAX mode) you should use for eventTarget UserControl.UniqueID. Here is some info about these JavaScript functions:

End SubEnd Class

__doPostBack(eventTarget, eventArgument)

or

RadGridNamespace.AsyncRequest(eventTarget, eventArgument, gridClientID)

eventTarget

The control which should raise post back event. If this control is directly on the HtmlForm than you can simply use the control ClientID otherwise if your control is in a INamingContainer you should use the control UniqueID. For UserControl you should use always the control UniqueID

eventArgument This is optional argument for the event

gridClientID*In case of RadGridNamespace.AsyncRequest

is ClientID of the grid which will be updated after AJAX.

r.a.d.grid v3.0 | 148

© 2002-2006, telerik. All Rights Reserved.

Page 149: r.a.d.grid v3

r.a.d.grid has been modified so that it can easily interoperate with r.a.d.callback controls. No additional efforts (such as writing JavaScript) are required to make any r.a.d.callback control update r.a.d.gridupon callback request.

r.a.d.callback controls suite is the telerik implementation of AJAX (Asynchronous JavaScript and XML) technology for standard ASP.NET controls (refer to r.a.d.callback manual for details).

When r.a.d.grid is used together wtih r.a.d.callback, r.a.d.grid works as usual. However to update it, callback is used instead of the normal page postback. This improves the user experience as there is no flicker and loss of scroll position, only the relevant control being updated just like in Windows applications. This leads to smoother interface transitions and superior user experience.

In order to allow r.a.d.grid to work with r.a.d.callback all you need to do is to drag and drop an instance of r.a.d.grid into CallbackPanel. CallbackPanel is mainly used for integration of other web controls (r.a.d.controls or other third party controls). It has a boolean property EvalScripts which needs to be set to true in order to evaluate the client-side scripts.

In case you need r.a.d.grid to perform callbacks (i.e. update a web page using callback), you will need to use the Generic Callback control from r.a.d.callback suite and write code to handle the client-side r.a.d.grid events.

How to use r.a.d.grid with r.a.d.callbackl drag callback panel to the webform

l drag r.a.d.grid to the webform

14 Interoperability with Other Controls

14.1 Interoperability of r.a.d.grid with r.a.d.callback

r.a.d.grid v3.0 | 149

© 2002-2006, telerik. All Rights Reserved.

Page 150: r.a.d.grid v3

l drag r.a.d.grid into the callback panel.

If you use other r.a.d.controls, we recommend using a separate callback panel for every instance of each control. In principle you can put as many controls in a r.a.d.callback panel as desired, but if you add all controls in a single panel, they will all be updated when you perform callback. In case you need to exclude a certain control from being updated by the callback although its content had been changed, you should include the control in the ExcludeList of the callback control which makes the request. This flexibility allows you to tailor your control to use either callback or postback depending on the requirement of the task. Refer to r.a.d.callback manual for additional details.

The described scenario is valid only if you have r.a.d.grid v2.0.2 or later and r.a.d.callbackinstalled. Both products are included in the r.a.d.controls Q3 2005 SP2 suite.

14.2 VAM Validators

r.a.d.grid v3.0 | 150

© 2002-2006, telerik. All Rights Reserved.

Page 151: r.a.d.grid v3

r.a.d.grid is one of the controls from telerik's r.a.d.controls suite that can establish support with Peter Blum's Validators of Professional Validation And More (“VAM”) (http://peterblum.com/). VAM requires a little setup to let its Validation framework work with r.a.d.grid .

To learn more about interoperability between telerik controls and VAM validators, visit http://peterblum.com/VAM/TypesOfControls.aspx?ReturnUrl=EssentialValidators.aspx. (http://peterblum.com/VAM/TypesOfControls.aspx?ReturnUrl=EssentialValidators.aspx)

Here are the guidelines for using the r.a.d.grid when there are any VAM Validators on the page (including outside the grid):

l Always substitute buttons supplied by VAM with those you normally would use:

¡ When using the <radg:GridEditCommandColumn>, use the GridEditCommandColumnsupplied with VAM in the PeterBlum.VAM.RadGrid assembly as a substitute. More details here (Section 14.2.3).

¡ When using the <radg:GridButtonColumn>, use the GridButtonColumn supplied with VAM in the PeterBlum.VAM.RadGrid assembly as a substitute. More details here (Section 14.2.3).

¡ When adding a <asp:Button>, <asp:LinkButton>, or <asp:ImageButton> control to a TemplateColumn, replace them with <vam:Button>, <vam:LinkButton>, or <vam:ImageButton> just as you would for any submit control elsewhere on the page.

l If you need a GridButtonColumn to validate, set its CausesValidation property to true.

l If you are using validation groups, both the VAM-supplied GridEditCommandColumn and GridButtonColumn controls offer a Group property where you define the validation group name. If you allow multiple rows to be editable at the same time, but only want each row to validate its own controls, add a plus (+) character as the first character of the Group property.

l Add VAM Validator controls to TemplateColumns. You cannot setup a Validator inside a GridBoundColumn, GridCheckBoxColumn, or GridDropDownColumn. Put the data entry control (textbox, dropdown, etc.) in the TemplateColumn and attach the Validator controls to it. If you are using validation groups on each row, assign the Group property to a name and if needed, add a plus (+) character as the first character of the Group property.

Before you can use r.a.d.grid with VAM, your web site needs some preparation to teach VAM about this control. Follow these steps:

1. Add the PeterBlum.VAM.RadGrid.dll to your web application. It is located in the [VAM installation]\Telerik r.a.d.controls folder.

Visual Studio.net Users (all versions)

Use the Add Reference command on your web application project and locate the assembly in the [VAM installation]\Telerik r.a.d. controls folder. The Add Reference command will automatically copy the assembly into the \bin folder.

All other development platforms

Copy the assembly from the [VAM installation]\Telerik r.a.d. controls folder into your web application’s \bin folder.

3. Make sure the RadGrid.dll is added to your web application. It must be version 2.0.0.0 or higher. Visual Studio.net users should use the Add Reference command. Other users should copy these files into the \bin folder.

4. Make sure the versions are correctly mapped in the web.config file. The file will have an <assemblyBinding> tag for the PeterBlum.VAM.dll and RadGrid.dll that allows the PeterBlum.VAM.RadGrid.dll to open newer versions of these assemblies.

14.2.1 Overview

This feature supports a minimum of VAM 3.0.2 and r.a.d controls suite Q3 2005. Do not attempt to use it with earlier versions of either product.

14.2.2 Setup Your Web Site

This feature requires version 2.0.0.0 or higher of the RadGrid.dll, which is included in the Q3 2005 release. If you have an older version, you must upgrade.

r.a.d.grid v3.0 | 151

© 2002-2006, telerik. All Rights Reserved.

Page 152: r.a.d.grid v3

For PeterBlum.VAM.dll, open the [VAM installation]\Assembly Version Info for the config file.txt and follow the directions in that file.

For RadGrid.dll, check the version number of the file. If it is 2.0.0.0, nothing needs to be done. If it is higher, add the <assemblyBinding> tag. Here is how it should look. Copy the text shown and insert the version number of your assembly in the newVersion= attribute:

1. Confirm that you have setup your web site as described in Setup Your Web Site (Section 14.2.2).

2. Add the RadGrid control to the page and set it up as desired.

3. Add this line to the top of your web form (aspx) or User Control (ascx) file:

<%@ Register TagPrefix="vrg" Namespace="PeterBlum.VAM.RadGrid" Assembly="PeterBlum.VAM.RadGrid" %>

4. Where you have added <radg:GridEditCommandColumn>, change it to <vrg:GridEditCommandColumn>. The PeterBlum.VAM.RadGrid.GridEditCommandColumn is a direct subclass of Telerik.WebControls.GridEditCommandColumn. So it is fully compatible with all of the properties you setup.

Original:

New:

If you create the column programmatically, just switch the class from Telerik.WebControls.GridEditCommandColumn to PeterBlum.VAM.RadGrid.GridEditCommandColumn.

5. Where you have added <radg:GridButtonColumn>, change it to <vrg:GridButtonColumn>. The PeterBlum.VAM.RadGrid.GridButtonColumn is a direct subclass of Telerik.WebControls.GridButtonColumn. So it is fully compatible with all of the properties you setup.

Original:

New:

If you create the column programmatically, just switch the class from Telerik.WebControls.GridButtonColumn to PeterBlum.VAM.RadGrid.GridButtonColumn.

6. Setup your VAM Validators. Use TemplateColumns to contain the data entry controls and their Validators.

7. Determine if any GridButtonColumn should validate. Set its CausesValidation property to true.

Each time you install an update of either of these products, you must update the <assemblyBinding> tags. It may help to keep a note to remind you.

<configuration><runtime>

---- COPY STARTS HERE ----<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

<dependentAssembly><assemblyIdentity name="RadGrid"

publicKeyToken="48124fdcdcfc8a53" culture="" /><bindingRedirect oldVersion="2.0.0.0"

newVersion="[Version Number]" /></dependentAssembly>

</assemblyBinding>---- COPY ENDS HERE -----

</runtime></configuration>

14.2.3 Adding the Control to the Page

<radg:GridEditCommandColumn [various properties]></radg:GridEditCommandColumn>

<vrg:GridEditCommandColumn [various properties]></vrg:GridEditCommandColumn>

<radg:GridButtonColumn [various properties]></radg:GridButtonColumn>

<vrg:GridButtonColumn [various properties]></vrg:GridButtonColumn>

<vrg:GridEditCommandColumn CausesValidation="true"[various properties]></vrg:GridEditCommandColumn>

r.a.d.grid v3.0 | 152

© 2002-2006, telerik. All Rights Reserved.

Page 153: r.a.d.grid v3

8. Determine if Validation Groups need to be used and set them up.

¡ Validation groups should be used when:

n There are Validators assigned to controls outside the RadGrid control which should not be fired when the user clicks on a button inside the grid. Rows in the grid should have a unique validation group name.

n There are Validators assigned to controls outside the RadGrid control which should be fired when the user clicks a button inside the grid and those Validators have a value assigned to the Group property. Rows in the grid should have the same group name as the Validators outside.

n You allow editing on multiple rows of the RadGrid simultanously but each row should be validated separately.Assign a group name that starts with the plus (+) character.

¡ Assign the group name to the Group property of each Validator, submit control (inside a TemplateColumn), GridEditCommandColumn , and GridButtonColumn in a row of the RadGrid.

r.a.d.grid v3.0 | 153

© 2002-2006, telerik. All Rights Reserved.

Page 154: r.a.d.grid v3

1. Incorrect structure of Columns or DetailTables.In order for RadGrid to work properly, it’s very important to build the grid structure correctly. Generally speaking, when the developer creates the structure using the designer (in VS.NET) there is less of a chance that mistakes will be made. The more difficult and error-prone task is creating the structure programmatically. Since RadGrid saves all its structure properties (DetailTables, Columns, etc.) into the ViewState, building a RadGrid dynamically is a task very similar to creating and adding controls dynamically to a web-page.

See http://support.microsoft.com/default.aspx?scid=kb;EN-US;317515

There are two possible approaches to dynamic RadGrid creation that you can use in order to be sure that RadGrid will behave normally.

1st Scenario:Create the RadGrid instance and the grid structure in the Page.Init event handler. Then the instance of RadGrid is added to the controls collection of the Page. In this case, no ViewState is required for grid structure to be persisted as it is recreated on each page initialization. There are no other special requirements in this case.

15 Troubleshooting

15.1 Most Common Mistakes

C# Codethis.RadGrid1 = new RadGrid();

this.RadGrid1.NeedDataSource += new GridNeedDataSourceEventHandler(this.RadGrid1_NeedDataSource);this.RadGrid1.DetailTableDataBind += new GridDetailTableDataBindEventHandler(this.RadGrid1_DetailTableDataBind);

this.RadGrid1.CssClass = "RadGrid";

this.RadGrid1.Width = Unit.Percentage(100);this.RadGrid1.PageSize = 5;this.RadGrid1.AllowPaging = true;this.RadGrid1.AutoGenerateColumns = false;this.RadGrid1.GroupingEnabled = true;this.RadGrid1.ShowGroupPanel = true;this.RadGrid1.ClientSettings.AllowDragToGroup = true;

this.RadGrid1.MasterTableView.DataMember = "Customers";this.RadGrid1.MasterTableView.PageSize = 15;

GridBoundColumn boundColumn;boundColumn = new GridBoundColumn();boundColumn.DataField = "CustomerID";boundColumn.HeaderText = "CustomerID";this.RadGrid1.MasterTableView.Columns.Add(boundColumn);

....//Add to page controls collectionthis.PlaceHolder1.Controls.Add( RadGrid1 );

VB.NET CodeMe.RadGrid1 = new RadGrid();

AddHandler Me.RadGrid1.NeedDataSource, New GridNeedDataSourceEventHandler(AddressOfAddHandler Me.RadGrid1.DetailTableDataBind, New GridDetailTableDataBindEventHandler(

Me.RadGrid1.CssClass = "RadGrid"

r.a.d.grid v3.0 | 154

© 2002-2006, telerik. All Rights Reserved.

Page 155: r.a.d.grid v3

15.1.1 2nd ScenarioAdd RadGrid to the page using the designer, but create the structure programmatically in the Page.Load event handler. You should remember that the structure should be built only in case where Page.IsPostBack is false. You should also add the instances of any created objects, such as columns and detail tables, to the RadGrid before any of those object’s properties have been set. This is important because no ViewState is managed for the object before it has been added to the corresponding collection.

Example:

2. Misusing or not using NeedDataSource eventThe NeedDataSource event helps developers easily control scenarios like paging, sorting, and grouping, with r.a.d.grid . Using these types of PostBack events, which RadGrid fires, can lead to a change in the Items collections of each GridTableView in a r.a.d.grid. A structural change here means that items should be recreated. In order to achieve that, the r.a.d.grid should have a DataSource assigned and the DataBind() method should be called. Then, instead of writing all the code to handle the appropriate

Me.RadGrid1.Width = Unit.Percentage(100)Me.RadGrid1.PageSize = 5Me.RadGrid1.AllowPaging = trueMe.RadGrid1.AutoGenerateColumns = falseMe.RadGrid1.GroupingEnabled = trueMe.RadGrid1.ShowGroupPanel = trueMe.RadGrid1.ClientSettings.AllowDragToGroup = true

Me.RadGrid1.MasterTableView.DataMember = "Customers"Me.RadGrid1.MasterTableView.PageSize = 15

Dim column1 As New GridBoundColumnboundColumn.DataField = "CustomerID"boundColumn.HeaderText = "CustomerID"Me.RadGrid1.MasterTableView.Columns.Add(boundColumn)

...

‘Add to page controls collectionMe.PlaceHolder1.Controls.Add( RadGrid1 )

C# Codeprivate void Page_Load(object sender, System.EventArgs e){ if ( !IsPostBack ){

GridBoundColumn boundColumn;//Important: first Add column to the collectionboundColumn = new GridBoundColumn();this.RadGrid1.MasterTableView.Columns.Add(boundColumn);//Then set propertiesboundColumn.DataField = "CustomerID";boundColumn.HeaderText = "CustomerID";

}}VB.NET CodePrivate Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) If Not IsPostBack Then

Dim column1 As New GridBoundColumn ‘Important: first Add column to the collection Me.RadGrid1.MasterTableView.Columns.Add(column1)

‘Then set propertiescolumn1.DataField = "CustomerID"column1.HeaderText = "CustomerID"

End IfEnd Sub

r.a.d.grid v3.0 | 155

© 2002-2006, telerik. All Rights Reserved.

Page 156: r.a.d.grid v3

scenario, the developer can just let r.a.d.grid handle these changes internally and only handle NeedDataSource which fires at the exact time the items should be recreated.

Often developers do not realize that NeedDataSource is called only when r.a.d.grid "knows" about the structural changes. If a sort or page command executed, for example. In all other cases, when developer has made changes to the structure of the grid that require binding, the developer should call the Rebind() method. This method will first check if the DataSource has been assigned, then it will force the RadGrid instance to fire NeedDataSource and then DataBind(). More information about using NeedDataSource and when this event fires can found in the r.a.d.grid knowledge base (http://www.telerik.com/Default.aspx?PageId=2514&b454K=FIr&b454T=wzk).

3. Not resetting CurrentPageIndex before binding to DataSource with different record countr.a.d.grid and its detail tables handle the CurrentPageIndex properties only in cases where RadGridchanges pages internally, when the end-user clicks on the buttons like the build-in pager buttons that fire a "Page" command event. In other cases the CurrentPageIndex property does not change. If, for example, we are implementing a web-based e-mail system and RadGrid handles the main view of the e-mail messages in a certain folder, based on a selection of a tree-view control. Then, when changing the current view, the number of records (e-mail messages) to be displayed should change too. Let's say then, that we have paging enabled in RadGrid. The user selects the 5th page using the default pager mechanism in RadGrid. Then the user changes the current e-mail folder view. The selected view does not have enough records to display on 5 pages. So the number of pages in RadGrid is actually smaller than the setting of the CurrentPageIndex property. If this case is not handled properly, RadGrid will throw an exception with the message "Invalid CurrentPageIndex" even though the developer did not explicitly set any CurrentPageIndex. To avoid this error, you should reset the CurrentPageIndex to "0" before rebinding RadGrid. In the general case this should be done in the corresponding event handler just before you call the Rebind() method.

4. Using NoPersistence DataSourcePersistence mode in scenarios not supportedSee Optimizing Performance (Section 13.8) topic for details abot DataSourcePersistenceproperty.

5. Not using NoPersistence DataSourcePersistence when you could, but setting EnableViewState to false insteadIf your scenario is similar to the one described in #4 and the small ViewState size is crucial to your application, you should use NoPersistence mode. In this mode RadGrid handles the most common scenarios with minimum ViewState usage. This feature is quite similar to the "ControlsState" concept introduced in ASP.NET 2.0.

6. Using cell numeric index to find a cell in a GridItem, instead using item's string index by Column.UniqueName

Important: Developers should avoid using NeedDataSource event handler to change the structure of an instance of RadGrid. If it is necessary to change the structure, you may need to use the event argument object to check the reason that NeedDataSource was being fired. Also the developer should not call the DataBind() method in the NeedDataSource event handler. It will be called internally when needed.

C# Code

private void FoldersTree_SelectedIndexChanged(object sender, System.EventArgs e){

this.CurrFolder = (FoldersTree.SelectedItems[0].Cells[3].Controls[0] as LinkButton).Text;RadGrid1.CurrentPageIndex = 0;RadGrid1.Rebind();

}VB.NET CodePrivate Sub FoldersTree_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles FoldersTree.SelectedIndexChanged Me.CurrFolder = CType(FoldersTree.SelectedItems(0).Cells(3).Controls(0), LinkButton).TextRadGrid1.CurrentPageIndex = 0RadGrid1.Rebind()

End Sub

r.a.d.grid v3.0 | 156

© 2002-2006, telerik. All Rights Reserved.

Page 157: r.a.d.grid v3

One of the major differences between RadGrid and the standard .NET DataGrid control is the dynamic column structure of RadGrid. Unlike the DataGrid, RadGrid supports operations such as column reordering and grouping which alter the Cells collection of GridItem objects in a way that can’t be predicted by the page developer. For example, when using a DataGrid, many developers used to search a cell in an item using the following code:

But imagine that the user has changed the column order using client-side drag/drop. Then the cell with index 4 will no longer refer the same field value. That's why RadGrid provides the ability to access cells in items using the corresponding column’s UniqueName. For example, if you have a column with the unique name "CustomerID" you can find the corresponding cell in a GridItem using:

This will prevent you from accessing the wrong cell.

7. Finding controls inside RadGridWhen reading the following important notes, keep in mind this MSDN article on common DataGrid mistakes: http://www.msdn.net/asp.net/archive/default.aspx?pull=/library/en-us/dnaspp/html/aspnet-commondatagridmistakes.asp

You should note the following about searching for controls in an item that is in edit mode. Unlike the DataGrid control, RadGrid supports EditForms feature which is set by default. It alters the "traditional" editing style by displaying an edit form item (row), below the item currently being edited, instead displaying the in-place editors. That's why, if you have template columns for example, and you have to search for a control that is in the edit template, you should search the EditFormItem instead of the edited item. This item is accessible using the GridDataItem.EditFormItem property.

8. Overusing hierarchical structure in treeview style scenariosTo better understand how r.a.d.grid deals with hierarchy, refer to the section: Hierarchical r.a.d.grid binding tips (http://www.telerik.com/help/radgrid/2.0/BindingHierarchicalGrids.html).

RadGrid only supports a hierarchical database structure. This means that in each level of hierarchy all items must have an equal number of details tables, unlike the r.a.d.treeview control which supports different number of sub-items on each level.

9. When handling the ItemDataBound or ItemCreated events, forgetting to check for the appropriatel GridItemType - see this article http://www.msdn.net/asp.net/archive/default.aspx?

pull=/library/en-us/dnaspp/html/aspnet-commondatagridmistakes.asp

l Detail table in the hierarchical structure - This check can be done using e.Item.OwnerTableView.DataMember property, where e is the event parameter of the event handler method. This way you can avoid possible problems when performing customization of items specific to a certain level of the hierarchy.

C# Codeitem.Cells[4]VB.NET Codeitem.Cells(4)

C# Codeitem.Cells["CustomerID"]VB.NET Codeitem.Cells("CustomerID")

Note that RadGrid will not behave correctly if you add detail tables programmatically in DetailTableDataBind event handler.

r.a.d.grid v3.0 | 157

© 2002-2006, telerik. All Rights Reserved.

Page 158: r.a.d.grid v3

In case you need to contact telerik with a technical question, please copy the following URL in your browser or click to open the telerik Client.NET(http://www.telerik.com/Default.aspx?PageId=2069).

16 Ask Technical Questions

r.a.d.grid v3.0 | 158

© 2002-2006, telerik. All Rights Reserved.