HOME PAGE | DOWNLOAD | TUTORIALS | XtraReports
Devexpress

Thursday, July 19, 2012

How to: Create a Column and Assign an Editor to It

The internal structure of the XtraGrid allows access to all important elements from code, during runtime. In this video I’ll show you how to add a column and assign an editor to it, by writing a few lines of code.

1.       I start off with a new WinForms project.

2.       I drop an XtraGrid control on the form and make it fill the available client area.

3.       Through the popup menu in the designer, I convert the standard view into  a BandedGridView.

4.       I change the property OptionsView.NewItemRowPosition to Top on the BandedGridView, so that I can easily test the assigned editor once I get to that point.

 

5.       I’m now going to add a few lines of code to the constructor of my form.

6.       The first line creates a new column and adds it to the view’s Columns collection. I have to add the namespace DevExpress.XtraGrid.Views.BandedGrid to make this line compile.

using DevExpress.XtraGrid.Views.BandedGrid;
...
BandedGridColumn newColumn = bandedGridView1.Columns.Add()
  as BandedGridColumn;

 

7.       Now I set the caption for the new column to “Country”.

   newColumn.Caption = "Country";

8.       Since I’m using a banded grid view, I have to make the new column visible in the correct band, in addition to adding it to the view. I’m going to add it to the one and only band I have in my simple configuration.

   bandedGridView1.Bands[0].Columns.Add(newColumn);

9.       Finally I make the column visible.

   newColumn.Visible = true;

10.   My second step is to create an editor for the column. In fact, for embedded editors I must create a so-called repository item. The grid will take care of creating the actual editor control as needed. Nevertheless I’m going to use the words “editor” and “repository item” interchangeably.

11.   I’m going to create a calc editor for this example. I need to add DevExpress.XtraEditors.Repository to my namespace list, so I can access the type RepositoryItemCalcEdit.

   using DevExpress.XtraEditors.Repository;
   ...
   RepositoryItemCalcEdit columnEditor = new RepositoryItemCalcEdit();

12.   If I had any customization work to do on the editor, this would be the place to do it. In this case I’m going to leave the editor on its default settings.

13.   The grid has collection of repository items, and I need to add the new item to that list.

   gridControl1.RepositoryItems.Add(columnEditor);

14.   Finally I can assign the editor to the column.

   newColumn.ColumnEdit = columnEditor;

15.   I’m done! I run my application and the new item row lets me see the editor working for the column I have added.

By modifying the XtraGrid and its related controls from code, you can easily create dynamic setups for the grid, configuring your columns and editors exactly as needed for your data source.

 

No comments:

Post a Comment