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:
Create a Connection
Use one of the following options to specify a connection:
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;
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);
Handle the SqlDataSource.ConfigureDataConnection event and specify the event’s ConnectionParameters. Check the event’s ConnectionName property to identify the connection.
Tip
Implement the IConnectionProviderService interface and handle its LoadConnection method to customize connections serialized in a report.