Quantcast
Channel: DevExpress Support Center (Examples)
Viewing all 7205 articles
Browse latest View live

How to implement XPO data models connected to different databases within a single application

$
0
0

Scenario

This example demonstrates how to create custom XAF modules with custom business objects and logic that would work with separate databases. These modules do not depend on each other and thus can be reused in other applications as a whole.
Usually, the connection to the database is set up in the executable application project. Typically, it is performed in the configuration file or directly in the code of the application's designer or within the Main function/Global application class. To learn more, please check out this help topic: Connect an XAF Application to a Database Provider In this example, you will learn how to establish a connection to the database directly from your module projects.


Steps to implement

0. Create a new XAF solution using one of predefined project templates;

1. Add two XAF modules into this solution using the DevExpress vXX.X XAF Module project template;

2. Add required persistent classes into these modules as shown in the ClassLibraryN/PersistentClassN.xx files of this example solution;

3. Add service ModuleInfo classes into these modules as shown in the ClassLibraryN/ModuleInfoN.xx files of this example solution;

4. In YourModuleName/Module.xx files, override the Setup(XafApplication application) methods of the ModuleBase descendants to handle the CreateCustomObjectSpaceProvider event of the XafApplication class as shown in the ClassLibraryX/XafModuleN.xx files of this example solution;

5. Build the solution, invoke the Module Designer for the platform-agnostic module (YourSolutionName.Module/Module.xx), and drag the created custom modules from the Toolbox:

Alternatively, you can add the same modules via the Application Designer invoked for the executable projects (as demonstrated in this example).

6. Declare connection strings in the configuration files of your application as shown in the TwoXpoModelsForDifferentDatabases.Web\Web.config and TwoXpoModelsForDifferentDatabases.Win\App.config files (see ConnectionStringDatabaseX under the <connectionStrings/> element). These connection strings are used in the modules via the ConfigurationManager.ConnectionStrings API, but you can always modify the way your modules obtains this data.

Important notes

1. Each module has a single static XPObjectSpaceProvider instance, which is initialized only once during the application life cycle.

2. Each ModuleUpdater class checks the ObjectSpace property to determine whether it is valid to create initial data of a certain type from this module.
3. Business classes linked to different ObjectSpaceProviders are considered to be isolated from each other and thus cannot have any links between them (e.g., have an association). Consider using the How to prevent altering the legacy database schema when creating an XAF application or alternative solutions if you need interlinks between classes from different data stores.

See also:
How to prevent altering the legacy database schema when creating an XAF application


OBSOLETE - How to setup a connection to the database from a Module project instead of an executable application project

$
0
0

=====================================
This example is now obsolete. Instead, refer to the How to implement XPO data models connected to different databases within a single application one.
=====================================
Usually, the connection to the database is set up in the executable application project. Usually, it is performed in the configuration file or directly in the code of the application's designer or within the Main function/Global application class. To learn more, please check out this help topic: Connect an XAF Application to a Database Provider
In this example, you will learn how to establish a connection to the database directly from your Module project. To do this, you will have to override the Setup method of your Module class and handle the CreateCustomObjectSpaceProvider event of the XafApplication class.

See Also:
How to implement XPO data models connected to different databases within a single application

How to setup a connection to the database from a Module project instead of an executable application project

How to use a custom ObjectSpaceProvider in XAF

How to reorder grid rows by drag and drop

$
0
0

This example extends the example provided in the How to allow an end-user to move the rows in a grid up and down if the grid is bound to a DataTable article with drag and drop functionality.

Question Comments

Added By: Micha Ben-Efraim at: 6/11/2012 2:11:54 AM    

I copied this example for reordering the element of a list bound to the control and it works almost perfectly. The problem is that the control doesn't scroll during D&D: the list is longer as the displayed window. If I select the first or the last item in the list (first/last row) and want o move to the last/first position, which is not visible, the view should scroll somehow in order to show the target drop row. But it doesn't do it when I move the cursor to the top/bottom of the view.
Can it

Added By: Fmonteiro at: 11/5/2013 3:34:26 AM    

Is possible to make this with the AdvBandedGridView?
I've tryed to make the same but in the:
Private Sub GridControl1_DragOver(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles GridControl1.DragOver
    ' If e.Data.GetDataPresent(GetType(GridHitInfo))

allways returns False, so never enters the IF.

Added By: softwaresupport@smec.com softwaresupport@smec.com at: 6/4/2014 5:43:37 AM    

Hi created a new ticket for this implementation as i dont find that it works

Added By: softwaresupport@smec.com softwaresupport@smec.com at: 6/4/2014 5:44:03 AM    

Here is the ticket ID : T114366

How to implement multi-row editing in the ASP.NET ListView

$
0
0

The ASPxGridListEditor does not natively support multi-row editing. It is recommended to either use the single-row inline editing by setting the AllowEdit property of the ListView model to True in the Model Editor, or edit objects in a DetailView. The multi-row editing functionality is rarely required, but since our customers usually experience difficulties implementing it, I decided to create this example.

There are several examples on how to implement this functionality in the ASPxGridView without XAF. From my point of view, the How to perform ASPxGridView instant updating using different editors in the DataItem template example is the most appropriate for XAF, because:

- this approach can be easily implemented using runtime code

- we already use DataItem templates to show data in grid cells.


All functionality is implemented in a single controller - the MultiRowEditingController. It performs the following operations:

1. Creates an ASPxCallback control and adds it to a page. This control is used to send callbacks from client-side editors used in grid cells.

2. Replaces the default DataItemTemplate with a custom one (EditItemTemplate). The custom template is required to show editors for the user input in grid cells. This template is based on the DataItemTemplate class used in XAF by default. The only difference is that controls from this template are always in the Edit mode.

3. Assigns the client-side script that performs a callback when the value is changed to the editors added to grid cells via the custom DataItemTemplate. This is done in the editor's Init event handler, because at this moment, the NamingContainer that contains the key of the bound object is available.

4. Handles the callback sent from the client side and changes the value of a corresponding object's property.


I recommend that you review the following help topics for additional information:

Access Grid Control Properties
ASPxGridView.Templates Property
How to use custom ASPxGridView template in a Web XAF application


Important notes
We have not tested this solution under all possible scenarios, so feel free to modify and test the code to better suit your needs. It this approach does not meet your requirements, implement a custom List Editor or ViewItem based on a custom Web user control with the ASPxGridView control configured at design time, as you would do in a standard non-XAF ASP.NET application.

 

Question Comments

Added By: Yuriy Konytskyy at: 6/3/2013 3:44:39 AM    

I doesn't work in v12.2.10

Added By: Anatol (DevExpress Support) at: 7/1/2013 4:19:13 AM    

I have updated the example. Please see implementation details for version 13.1.

Added By: Sandro Welter (Intelligix) at: 7/5/2013 3:02:00 PM    

I'm getting the error below.

The error occurred:
     Type: NullReferenceException
     Message: Object reference not set to an instance of an object.
     Data: 0 entries
     Stack trace:

Added By: Anatol (DevExpress Support) at: 1/10/2014 8:32:12 AM    

The NullReferenceException issue is solved.

Added By: PHN at: 1/30/2014 10:55:55 AM    

Hi,
I have some modifications to support ASPxDateTimePropertyEditor,ASPxLookupPropertyEditor:

using System;
using System.Linq;
using System.ComponentModel;
using System.Web.UI;

using DevExpress.ExpressApp.Web.Editors.ASPx;
using DevExpress.Web.ASPxGridView;
using DevExpress.ExpressApp.Web;
using DevExpress.ExpressApp.Editors;
using DevExpress.Web.ASPxClasses;
using DevExpress.ExpressApp.DC;
using DevExpress.Web.ASPxCallback;
using DevExpress.ExpressApp.Model;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxEditors;
using DevExpress.Xpo;
using DevExpress.ExpressApp;

namespace WebExample.Module.Web
{
    [ListEditor(typeof(object), false)]
    public class MultiEditASPxGridListEditor : ASPxGridListEditor
    {
        const String CallbackArgumentFormat = "function (s, e) {{ {0}.PerformCallback(\"{1}|{2}|\" + {3}); }}"; // ASPxCallback, key, fieldName, value
        public MultiRowEditASPxGridListEditor(IModelListView model)
            : base(model) { }
        ASPxCallback callback;
        protected override object CreateControlsCore()
        {
            Panel panel = new Panel();
            callback = new ASPxCallback();
            callback.ID = ObjectTypeInfo.Type.Name + "aspxCallback1";
            callback.ClientInstanceName = ObjectTypeInfo.Type.Name + "_callback1";
            callback.Callback += new CallbackEventHandler(callback_Callback);
            panel.Controls.Add(callback);
            ASPxGridView grid = (ASPxGridView)base.CreateControlsCore();
            grid.HtmlDataCellPrepared += new ASPxGridViewTableDataCellEventHandler(grid_HtmlDataCellPrepared);
            panel.Controls.Add(grid);
            return panel;
        }
        
        void grid_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
        {
            if (e.DataColumn is GridViewDataColumnWithInfo && IsColumnSupported(((GridViewDataColumnWithInfo)e.DataColumn).Model))
            {
                e.Cell.Attributes["onclick"] = RenderHelper.EventCancelBubbleCommand;
            }
        }

        protected override ITemplate CreateDataItemTemplate(IModelColumn columnInfo)
        {
            if (IsColumnSupported(columnInfo))
            {
                EditModeDataItemTemplate editModeTemplate = (EditModeDataItemTemplate)CreateDefaultColumnTemplate(columnInfo, this, ViewEditMode.Edit);
                editModeTemplate.PropertyEditor.ImmediatePostData = false;
                editModeTemplate.CustomCreateCellControl += new EventHandler<DevExpress.ExpressApp.Web.Editors.CustomCreateCellControlEventArgs>(editModeTemplate_CustomCreateCellControl);
                return editModeTemplate;
            }
            else
            {
                return base.CreateDataItemTemplate(columnInfo);
            }
        }
        
        void editModeTemplate_CustomCreateCellControl(object sender, DevExpress.ExpressApp.Web.Editors.CustomCreateCellControlEventArgs e)
        {
            if (e.PropertyEditor.Editor is ASPxWebControl)
            {
                e.PropertyEditor.Editor.Init += new EventHandler((s, args) => Editor_Init(s, args, e.PropertyEditor.Editor));
            }
            else if (e.PropertyEditor is ASPxLookupPropertyEditor)
            {
                ASPxLookupPropertyEditor editor = e.PropertyEditor as ASPxLookupPropertyEditor;
                editor.DropDownEdit.DropDown.Init += new EventHandler((s, args) => Editor_Init(s, args, e.PropertyEditor.Editor));
            }
            
        }

        void Editor_Init(object sender, EventArgs e,WebControl baseEditor)
        {
            ASPxWebControl editor = (ASPxWebControl)sender;
            editor.Init -= new EventHandler((s, args) => Editor_Init(s, args, baseEditor));
            // Uncomment to remove editors borders
            //editor.Border.BorderStyle = BorderStyle.None;
            GridViewDataItemTemplateContainer container = baseEditor.NamingContainer as GridViewDataItemTemplateContainer;
            var columnInfo = container.Column as GridViewDataColumnWithInfo;
            editor.SetClientSideEventHandler("ValueChanged", String.Format(CallbackArgumentFormat,
                callback.ClientInstanceName, container.KeyValue, columnInfo.Model.PropertyName, editor is ASPxDateEdit ? "s.GetText()" : "s.GetValue()"));
        }

        void callback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
        {
            String[] p = e.Parameter.Split('|');
            Object key = TypeDescriptor.GetConverter(ObjectTypeInfo.KeyMember.MemberType).ConvertFromString(p[0]);
            IMemberInfo member = ObjectTypeInfo.FindMember(p[1]);
            Object value = null;
            if (typeof(IXPSimpleObject).IsAssignableFrom(member.MemberType))
            {
                Type memberKeyType = XafTypesInfo.Instance.FindTypeInfo(member.MemberType).KeyMember.MemberType;
                int index1 = p[2].LastIndexOf("(");
                int index2 = p[2].LastIndexOf(")");
                if (index1 > 0 && index2 > index1)
                {
                    string memberKeyText = p[2].Substring(index1 + 1, index2 - index1 - 1);
                    value = ObjectSpace.GetObjectByKey(member.MemberType, Convert.ChangeType(memberKeyText, memberKeyType));
                }
            }
            else
            {
                value = TypeDescriptor.GetConverter(member.MemberType).ConvertFromString(p[2]); ;
            }
            object obj = ObjectSpace.GetObjectByKey(ObjectTypeInfo.Type, key);
            member.SetValue(obj, value);
            ObjectSpace.CommitChanges();
        }

        private Type[] supportedPropertyEditorTypes()
        {
            return new Type[]{
                typeof(ASPxStringPropertyEditor),
                typeof(ASPxIntPropertyEditor),
                typeof(ASPxBooleanPropertyEditor),
                typeof(ASPxEnumPropertyEditor),
                typeof(ASPxDateTimePropertyEditor),
                typeof(ASPxLookupPropertyEditor)
            };
        }

        protected virtual bool IsColumnSupported(IModelColumn model)
        {
            if (model.GroupIndex >= 0)
            {
                return false;
            }
            foreach (Type type in supportedPropertyEditorTypes())
            {
                if (type.IsAssignableFrom(model.PropertyEditorType))
                {
                    return true;
                }
            }
            return false;
        }
        // Sorting and grouping are not supported
        protected override ColumnWrapper AddColumnCore(IModelColumn columnInfo)
        {
            ASPxGridViewColumnWrapper columnWrapper = (ASPxGridViewColumnWrapper)base.AddColumnCore(columnInfo);
            if (IsColumnSupported(columnWrapper.Column.Model))
            {
                columnWrapper.Column.Settings.AllowSort = DevExpress.Utils.DefaultBoolean.False;
                columnWrapper.Column.Settings.AllowGroup = DevExpress.Utils.DefaultBoolean.False;
            }
            return columnWrapper;
        }
    }
}

Added By: Anatol (DevExpress Support) at: 1/31/2014 12:04:45 AM    

Thank you for sharing your code. It looks good. I hope it will be useful for others.

Added By: Apostolis Bekiaris (DevExpress) at: 2/17/2014 7:12:23 AM    

Added in eXpandFramework 13.2.7.4

Added By: HEUNGGI LEE at: 6/4/2014 6:10:47 AM    

Hi,
Is it possible to set width length on each column in GridView? It is ugly...especially Character field grid width is too narrow ..

How to create a Doughnut chart

$
0
0

The following example demonstrates how to create a Doughnut chart at runtime.

Note that this series view type is associated with the Simple Diagram type, and you should cast your diagram object to this type, in order to access its specific options.

Starting from v2014 vol 1, text pattern properties (AxisLabel.TextPattern, SeriesLabelBase.TextPattern, SeriesBase.LegendTextPattern) have been introduced instead of point options.
Text pattern properties simplify text customization of series labels, axis labels and legend items (when the SeriesViewColorEachSupportBase.ColorEach  mode is enabled)

How to: Use TransitionManager to animate tab switching in XtraTabControl

$
0
0
This example contains an XtraTabControl with two tabs. The TransitionManager component is used to animate switching between these tabs, using a certain animation effect (specified by the Transition Type combobox). Animated tab switching is initiated in the XtraTabControl.SelectedPageChanging event handler and is finished in the XtraTabControl.SelectedPageChanged event handler.

Before the transition starts, it is created in the SelectedIndexChanged event of the combobox control. 

By default, the entire area occupied by the control is animated by the TransitionManager. In the example, the CustomTransition event is handled to exclude the tab region from animation.

How to change the appearance of a focused data row and selected rows

$
0
0

This example demonstrates how to use the View's RowStyle property to apply custom styles to focused and selected rows. To identify whether a row is focused and selected, the attached IsFocusedRow and IsSelected properties are used.

Question Comments

Added By: Jeremy Manley at: 6/4/2014 7:18:58 AM    

Please update for v14.1.

ASPxGridView - Batch Editing - How to show save and cancel buttons only when any row/cell has been changed

$
0
0

This example demonstrates how to hide the Save changes and Cancel changes buttons, and show them only when an end-user edits any cell or row.


How to implement a radio list control

$
0
0

This example demonstrates how to customize the CheckedListBox control, so it looks like a radio group and can be bound to a datasource.

Question Comments

Added By: Valentin Badea at: 4/7/2014 6:42:11 AM    

In this example is a problem if you want to have always an item selected !

Added By: Valentin Badea at: 4/7/2014 6:43:03 AM    

At the click on the selected item all items becomes unselected !!

Added By: David Lemieux at: 6/3/2014 12:51:06 PM    

DevExpress, why does it have to be so complicated? Why not simply add the CheckStyle property to the basic CheckedListBox control?

Added By: Andrew Ser (DevExpress Support) at: 6/4/2014 8:10:26 AM    Hello David,
It seems that you have already asked a similar question in CheckedListBoxControl radio buttons. Let's continue discuss this issue there.

ASPxGridView - Batch Edit - How to calculate values on the fly

How to add a custom summary item to the grid's footer menu

$
0
0

Sometimes it's necessary to specify a way of calculating summaries that is different from the default one. Assume you don't want to take into account cells with no data when calculating summaries. It's possible to accomplish this task using two events: use the GridView.CustomSummaryCalculate event to provide a custom summary and the GridView.PopupMenuShowingevent to add a corresponding item to the grid's footer menu.
See also:
Custom Aggregate Functions

Question Comments

Added By: Sir Kevin Heathfield at: 7/23/2013 3:49:25 AM    

Not a single code comment.. Nice..

Added By: Matteo Lazzari at: 6/5/2014 3:12:58 AM    

Why do you do:

foreach (DevExpress.Utils.Menu.DXMenuItem item in footerMenu.Items)
               item.Enabled = true;

I see this is necessary for enable the menu items... But I would like to maintain disabled the summarization items not available for a particular field type (for example, the sum for the strings). Is this possible?
Thank you.

ASPxGridView - How to update total summaries on the client side in Batch Edit mode

ASPxGridView - How to implement copy functionality in Batch Edit mode

How to create a control that shows a list of tags

$
0
0

OBSOLETE 
Since the 14.1 we provide a special TokenEdit that fully supports this functionality out-of-the-box



This example demonstrates how to create a TagList control editor that supports both standalone and in-place modes.

Question Comments

Added By: Santiago Moscoso at: 3/15/2013 12:42:07 PM    

Nice.
One problem though, try resizing the form while the cursor is at cell of the gridview.

Added By: Nikita (DevExpress Support) at: 3/19/2013 6:10:12 AM    

Hi Santiago,

Thank you for your feedback. I have updated the example to resolve the issue, and it now works correctly.

OBSOLETE - How to use VGridControl instead of the LayoutControl in the DetailView

$
0
0

========================================

This example is now obsolete and is no longer maintained, because this custom VGridControl layout implementation is now quite rare. Second, it is better to implement a custom LayoutManager for this task, rather than embedding a fake ViewItem into the existing DetailView layout.

========================================
In this example, I have created a custom ViewItem based on the VGridControl.
The idea is to remove all layout items that you want to show in the vertical grid and instead of them place our single ViewItem onto the layout.
Then, all the editors for business object properties will be generated with the help of the VGridControl.

To use this custom item, you should customize the required DetailView in the Model Editor as shown in the WinSolution.Module.Win\Model.DesignedDiffs.xafml file.

See Also:
XtraVerticalGrid Home
Implement Custom Detail View Items


OBSOLETE - How to create a custom translation provider for the Localization tool

How to collapse large editors in the Detail View on the Web

$
0
0

===========================
This example is now obsolete. Instead, implement custom LayoutItemTemplate, LayoutGroupTemplate or TabbedGroupTemplate templates as demonstrated in the FeatureCenter demo (%Public%\Documents\DevExpress Demos 1X.X\Components\eXpressApp Framework\FeatureCenter\CS\FeatureCenter.Module.Web\Layout\)
===========================
Sometimes when your detail view contains a lot of editors, it is necessary to effectively use the space on the page. For example, usually editors in which collection properties are shown take a lot of space. You can reduce the space if you provide the capability to collapse large editors.
In this example, I show how to put a large editor into the ASPxNavBar control that can expand/collapse its groups.

See Also:
Access Editor Settings

GridLookUpEdit: multiple selection using checkbox (web style)

$
0
0

The current example extends multiple selection in the web style (via check boxes) functionality, described in the Multiple selection using checkbox (web style) example, for the GridLookUpEdit. In case of GridLookUpEdit bound data source is initialized only after the popup window is shown, so it is impossible, for example, to select all entries on popup window load. To handle this, data source should be used directly. The following example illustrates this approach.

See also:
How to use an unbound check box column to select grid rows
Multiple selection using checkbox (web style)

Question Comments

Added By: Larry Hendren at: 6/5/2014 7:38:27 AM    

The code from this example would be very helpful; however, I cannot compile it in vb.  Several of these type erros:
"Error 514 Type 'DevExpress.XtraGrid.Views.Grid.ViewInfo.GridGroupRowInfo' is not defined. C:\Users\myname\Documents\Samples\XtraGrid Suite\13.2.9\E4048\VB\GridLookUpEditCBMultipleSelection\GridCheckMarksSelection.vb 309 16 GridLookUpEditCBMultipleSelection

I have converted it to version 14.1.3

How to create a Windows 8 style toggle switch control

GridView - Batch Editing - How to cancel editing or disable the editor conditionally

$
0
0

This example demonstrates how to cancel editing or disable the editor conditionally for the grid when batch editing is in use. It is possible to execute your logic either on the client or server side for a complex business model.
Then, handle the grid's client-side BatchEditStartEditing event to either cancel the edit operation using the e.cancel property:

[JScript]
if(condition) e.cancel = true;

 or disable the editor by obtaining its client instance:

[JScript]
var editor = s.GetEditor(e.focusedColumn.fieldName); editor.SetEnabled(condition);

 The custom server-side logic can be executed in the CustomJSProperties event handler:

[C#]
settings.CustomJSProperties+=(s,e)=>{varclientData=newDictionary<int,object>();vargrid=sasMVCxGridView;for(inti= 0;i<grid.VisibleRowCount;i++){varrowValues=grid.GetRowValues(i,newstring[]{"ID","ServerSideExample"})asobject[];varkey=Convert.ToInt32(rowValues[0]);if(key% 2 != 0)clientData.Add(key,"ServerSideExample");}e.Properties["cp_cellsToDisable"]=clientData;};


See Also:

APSxGridView - Batch Editing - How to cancel editing or disable the editor conditionally

Viewing all 7205 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>