Skip to main content

Specify a Database Connection at Runtime

  • 2 minutes to read

Use Predefined Connections

When you use the Data Source Wizard to connect to a database, a connection string is added to the application’s configuration file:

<configuration>  
...  
    <connectionStrings>  
        <add name="dxSample.NWINDConnectionString"  
            connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient" />  
    </connectionStrings>  
...  
</configuration> 

You can use the name attribute to refer to this connection in code:

sqlDataSource1.ConnectionName = "dxSample.NWINDConnectionString";

Create a Connection

Use one of the following options to specify a connection:

  1. Specify connection credentials. Create a DataConnectionParametersBase descendant instance (for instance, MsSqlConnectionParameters) and use its new properties to specify credentials, such as the server name, database name, user name, and password.

    MsSqlConnectionParameters connectionParameters = new MsSqlConnectionParameters("localhost", "nwind.mdf", "username", "password", MsSqlAuthorizationType.SqlServer);  
    SqlDataSource dataSource = new SqlDataSource();  
    dataSource.ConnectionName = "nwindConnection";  
    dataSource.ConnectionParameters = connectionParameters; 
    
  2. Specify a connection string. Create a CustomStringConnectionParameters class instance and set its ConnectionString property to the connection string.

    string connectionString = @"XpoProvider=MSSqlServer;Data Source=(local);User ID=username;Password=password;Initial Catalog=database;Persist Security Info=true;";  
    CustomStringConnectionParameters connectionParameters = new CustomStringConnectionParameters(connectionString);  
    SqlDataSource ds = new SqlDataSource(connectionParameters);
    
  3. Handle the SqlDataSource.ConfigureDataConnection event and specify the event’s ConnectionParameters. Check the event’s ConnectionName property to identify the connection.

    private void sqlDataSource1_ConfigureDataConnection(object sender, DevExpress.DataAccess.Sql.ConfigureDataConnectionEventArgs e) {  
    if (e.ConnectionName == "connection1") {  
            e.ConnectionParameters = new Access97ConnectionParameters("../../nwind.mdb", "", "");  
       }  
    }  
    

Restore Connections Serialized in a Report

You can implement a service with the IConnectionProviderService interface and register the service in the application. The interface has the LoadConnection method that is invoked when the report is loaded for each connection serialized in the report definition file. Implement the LoadConnection method to get a connection by name and return the valid data connection to the report.