user1304232 user1304232 - 3 months ago 8
SQL Question

Changing dataset connectionstring at runtime vs2010

I found a solution that must be for a older version then vs2010. I would like to know how to do this for vs2010? Does anyone know?

Let me explain little more detail.

I have a c# generated dataset. How can I change the connection string so I can use the dataset with another (identically structured yet differently populated) database? This has to occur at runtime as I do not know the server or database name at compile time. i AM USING vs2010 and SQL Server 2008 R2 Express


I think there is no simple way and you cannot change the Connection-String programmatically for the entire DataSet since it's set for every TableAdapter.

You need to use/create the partial class of the TableAdapter to change the connection-string since the Connection property is internal (if your DAL is in a different assembly). Don't change the designer.cs file since it will be recreated automatically after the next change on the designer. To create it just right-click the DataSet and chose "show code".

For example (assuming the TableAdapter is named ProductTableAdapter):

namespace WindowsFormsApplication1.DataSet1TableAdapters
    public partial class ProductTableAdapter 
        public string ConnectionString {
            get { return Connection.ConnectionString; }
            set { Connection.ConnectionString = value; }

Now you can change it easily:

var productTableAdapter = new DataSet1TableAdapters.ProductTableAdapter();
productTableAdapter.ConnectionString = someOtherConnectionString;

Here's a screesnhot of my sample DataSet and the created file DataSet1.cs:

enter image description here