Skip to main content
A newer version of this page is available. .

Update Database Connections

  • 2 minutes to read

You can create a report that obtains data from a sample database, for development purposes, and switches the database connection to the production database, for end-users. To retrieve production data, specify a database connection at runtime and implement a method to update database connections when users open a report.

  1. Implement the IConnectionProviderFactory service:

    using DevExpress.DataAccess.Web;
    using DevExpress.DataAccess.Wizard.Services;
    // ... 
        public class MyConnectionProviderFactory : IConnectionProviderFactory
        {
            public IConnectionProviderService Create()
            {
                return new MyConnectionProviderService();
            }
        }
    

    The service returns an instance of the IConnectionProviderService that supplies connections.

  2. Implement the IConnectionProviderService class:

    using DevExpress.DataAccess.ConnectionParameters;
    using DevExpress.DataAccess.Sql;
    using DevExpress.DataAccess.Wizard.Services;
    using System.Collections.Generic;
    // ...
        public class MyConnectionProviderService : IConnectionProviderService
        {        public SqlDataConnection LoadConnection(string connectionName)
            {
                switch (connectionName)
                {
                    case ("NWindConnectionString"):
                        return new SqlDataConnection("NWindConnectionString",
                                new MsSqlConnectionParameters()
                                {
                                    AuthorizationType = MsSqlAuthorizationType.Windows,
                                    DatabaseName = "Northwind",
                                    ServerName = "localhost"
                                });
                    default:
                        throw new KeyNotFoundException($"Connection string '{connectionName}' not found.");
                }
            }
        }
    

    When the Document Viewer or Report Designer Preview loads a report, it calls the IConnectionProviderService.LoadConnection method and allows you to return a connection with the specified name stored in a report.

    You can use various DataConnectionParametersBase descendants to establish a connection to different DBMS and data files in different formats, such as:

    To specify a custom connection string, use the CustomStringConnectionParameters instance.

  1. Register the MyConnectionProviderFactory service at application startup before the ASPxWebDocumentViewer.StaticInitialize method:

    protected void Application_Start() {
        // ...
        DevExpress.XtraReports.Web.WebDocumentViewer.DefaultWebDocumentViewerContainer.RegisterConnectionProviderFactory<MyConnectionProviderFactory>();
        //...
        DevExpress.XtraReports.Web.ASPxWebDocumentViewer.StaticInitialize();
        // ...
    }