Changing C# Dataset (XSD) Connection Strings

One thing that I have often found I have needed to do when programming is to change the connection string properties of an dataset table adapter or queries table adapter. Allowing changes to the connection to be made programmatically can be very beneficial. For example time-outs can be controlled and the database or SQL server instance can be changed on the fly.

The usual way of accessing the connection is the make a partial class on the adapter that exposes the properties that you want to have access to. While this method does work it is not very generic and requires partial classes to be made and maintained. This is OK if you have a small set but can become an unnecessary overhead if you have a large collection of adapters. As such having a generic method of solving this issue was required.

The first thing we have to do is make connection and connection modifier properties on the adapter public because by default they are set to internal.

XSD Connection Moddifier

Next we need to make use of the .Net reflection library. This will allow us to make a generic method that will work over all of the XSDs strongly typed datasets. Due to the way the table adapters and query table adapters are generated I created two methods, however if required I’m sure they could be combined.

Hopefully this code will be helpful to some people as I could find very little online on how to do this.