Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource - Raj Kaimal

Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

The Visual Studio 2005 Dataset designer allows you to create a DAL using a typed dataset and easily bind this to a GridView with the help of an ObjectDataSource. By default, in the TableAdapter generated, the visibility of the encapsulated Connection object is set to private.

For the calling code to specify its own Connection object, the visibility of the Connection property has to be made public. This can be done by setting the ConnectionModifier property of the TableAdapter to public.

ConnectionModifier

Once that is done, changing the Connection at runtime can easily be done as shown below:

DataSet1TableAdapters.CustomersTableAdapter adapter = new DataSet1TableAdapters.CustomersTableAdapter();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = MyConnectionManager.ConnectionString;
adapter.Connection = conn;
DataTable table = adapter.GetData();

What if an ObjectDataSource were using this TableAdapter and we wanted to change the ConnectionString at runtime?

The ObjectDataSource, thankfully, exposes an ObjectCreated event. This event gets raised after the object specified by the TypeName property is created.  We can obtain a reference to this object by the ObjectInstance property exposed by the ObjectDataSourceEventArgs object. The Connection property can then be changed with a little sprinkle of reflection as shown below:

protected void ObjectDataSource1_ObjectCreated(object sender, ObjectDataSourceEventArgs e)
{
    if (e.ObjectInstance != null)
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = MyConnectionManager.ConnectionString;
        e.ObjectInstance.GetType().GetProperty("Connection").SetValue(e.ObjectInstance, conn, null);
    }
}

This is useful in places where you wanted to set the ConnectionString to use based on the role of the web user. As always, if you know of a better way to do this, please post a comment. Thanks.

Published Saturday, May 26, 2007 11:41 AM by rajbk
Filed under: , ,

Comments

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

Got a question on this:  I am using a class library, and I need to the database.xsd data Adapters to refer to the web.config files connection string info...  I am at a loss when it comes to directing the adapters to the correcct connection string info...

Thursday, July 05, 2007 3:00 PM by Warren LaFrance

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

Warren,

To see the connection string being used for a table adapter, click on the table adapter in the designer and look at the "Connection" property.

Thursday, July 05, 2007 4:20 PM by rajbk

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

Thanks for your help on this.

I have converted your code above to VB.NET.  Does this look correct to you...

If e.ObjectInstance IsNot Nothing Then

           Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection

           conn.ConnectionString = ConfigurationManager.ConnectionStrings("WebConfigConnString").ConnectionString

           e.ObjectInstance.GetType().GetProperty("Connection").SetValue(e.ObjectInstance, conn, Nothing)

       End If

Wednesday, July 11, 2007 9:00 PM by Warren LaFrance

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

THANKS FOR YOUR HELP, NOW I CAN CHANGE TABLEADAPTER CONNECTION

Thursday, July 26, 2007 2:10 PM by LUIS

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

Thank you for your posting. I tried to use your code, but I got an error at  e.ObjectInstance.GetType().GetProperty("Connection").SetValue(e.ObjectInstance, conn, null);

says: Cannot convert from string to System.Reflection.BindingFlages. If you can tell me why, I would be greatly appreciate it.

Tuesday, August 28, 2007 9:04 AM by Mark

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

I tried to post a message earlier, somehow it did not go throught. VS2005 does not recongnize "Connection"..

The error says"Can not convert string to System.Reflection.BindingFlags."

Please help if you know why.

Thanks very much in advance.

Tuesday, August 28, 2007 9:39 AM by Mark

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

Mark,

Did you do exactly as stated above? Check your code again.

Tuesday, August 28, 2007 9:53 AM by rajbk

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

Guys, I tried this walk-through and it worked perfectly.. asp.net/.../tutorial-72-vb.aspx

Friday, September 28, 2007 4:46 PM by Warren LaFrance

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

I searched high and low last week for such a post. Submitted my own question this week, and while waiting for a response search again and found this one. It does exactly what I was looking for. Thanks heaps.

Sunday, October 14, 2007 8:41 PM by Dale Curtis

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

I used this VB code and get the error "NullReferenceException was unhandled by user code".  It points to the last occurrence of e.ObjectInstance.  Any ideas?

Monday, December 10, 2007 3:37 PM by Mark D.

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

I also get the "NullReferenceException was unhandled by user code" error using the C# code.

It seems to be having problems with GetProperty("Connection") part.

Thursday, January 17, 2008 9:36 AM by Mike

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

Awesome!  Saved me a huge headache!

Friday, March 14, 2008 10:07 AM by Acer

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

hi:

if my database is microsoft access,

it got an error:

Keyword not supported: 'provider'.

how can i do, thx :)

Thursday, May 01, 2008 8:49 PM by williams

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

Wouldn't this have to be done for every table adaptor in the target database?

Saturday, May 24, 2008 3:50 AM by Bill Nell

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

Thanks! This makes the ObjectDataSource even more useful for me now.

Tuesday, July 15, 2008 3:56 PM by Steve

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

Thank You!!!!!

I spent hours trying to figure out where to set my extended table adapter class properties.

I only used the new typed dataset.xsd to try and save some time(What a mistake that was) for a sql report and in long run it cost me alot more. MS needs to fix this for now I consider the table adapter worthless.

I will go back to the old designer for typed datasets and fill them myself.

Anyways thanks a million man for sharing!

Wednesday, August 06, 2008 6:51 PM by OutOfTouch

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

Hi!

I have a workaround for those who work in environments with multiple database servers. I.e., Development, Testing and Production.

This solution will allow you to never have to change the web config to deploy apps for the different environment.

1. Create Add Key named Environment on the default website on each IIS server.  The value should be the type of server, i.e., Development, Testing, Production.

2. Add a connection string for each environment to your web.config.

<connectionStrings>

 <add name="Development" connectionString="ConnectionString"

  providerName="System.Data.SqlClient" />

 <add name="ModelOffice" connectionString="ConnectionString"

  providerName="System.Data.SqlClient" />

 <add name="Production" connectionString="ConnectionString"

  providerName="System.Data.SqlClient" />  

</connectionStrings>

3. Create 1 or 2 shared functions to return the current SQLConnection and ConnectionString.

           Public Shared ReadOnly Property ConnectionString() As String

               Get

                   Return ConfigurationManager.ConnectionStrings(AppSettings.DB.Environment).ConnectionString

               End Get

           End Property

           Public Shared ReadOnly Property Connection() As SqlClient.SqlConnection

               Get

                   Return New SqlClient.SqlConnection(DB.ConnectionString)

               End Get

           End Property

4. Create TypedDataSets as needed

5. For each TableAdapter create a class that inherits from the TableAdapter and changes the connection string using the Shared Function.

   Public Class TestTableAdapter

       Inherits _TestTableAdapters.MyTableTableAdapter

       Sub New()

           MyBase.New()

           MyBase.Connection = SharedFunction.Connection

       End Sub

   End Class

6. When using the ObjectDataSource, set the type equal to the newly created class.

Works like a charm.

NONA

Monday, November 17, 2008 7:50 PM by Nona

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

I also have the issue of NullReferenceException was unhandled by user code" error using the C# code.

If I look at e.ObjectInstance.GetType().GetProperties(), i get the following results:

{System.Reflection.PropertyInfo[3]}

   [0]: {Boolean ClearBeforeFill}

   [1]: {System.ComponentModel.ISite Site}

   [2]: {System.ComponentModel.IContainer Container}

As you can see, there is no connection property.  Does the above method work on a web project, or only a desktop app?

Monday, December 01, 2008 12:57 PM by soccerwiz13

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

It Works!!! Thanks a Lot... U hv it... Gr8

Monday, December 15, 2008 3:47 PM by NSK

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

I tried to provide the ObjectCreated event to the ObjectDataSource, but I got this error saying that this 'System.Web.UD.WebControls.ObjectDataSource' does not have a public property named 'ObjectCreated'.

Here is how I coded the tag for it:

<asp:ObjectDataSource ID="datasource1" runat="server" OldValuesParameterFormatString="original_{0}"

       SelectMethod="GetDistinctManagerofOffenders"

       TypeName="MEQNSTableAdapters.VW_DistinctManagerofOffendersTableAdapter"

       ObjectCreated="datasource1_ObjectCreated"

        ></asp:ObjectDataSource>

Please advise, what is wrong here.  Thank you.

Wednesday, January 28, 2009 6:15 PM by jonyeh

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

hi, the problem i'm having is similar: i want to simply "Add Connection" but use <configuration>

   <connectionStrings configSource="connections.config">

   </connectionStrings>

</configuration>

instead of a real database.  Then, later depending on environment, i can change settings in "connections.config" file to go to different databases. This should be this easy- why I cannot do it this way?

Wednesday, March 04, 2009 1:50 PM by Joe Meek

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

Excellent piece.Answers issues with clear simple

advice.

Thursday, May 14, 2009 8:56 AM by zvi yosef

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

my code is

       protected void ObjectDataSource1_ObjectCreating(object sender, ObjectDataSourceEventArgs e)

       {

           if (e.ObjectInstance != null)

           {

               SqlConnection conn = new SqlConnection();

               conn.ConnectionString = ConfigurationManager.ConnectionStrings["TestLib.Properties.Settings.MyConn"].ToString();

               e.ObjectInstance.GetType().GetProperty("Connection").SetValue(e.ObjectInstance, conn, null);

           }

       }

but it get the error message.

How can I do?

Saturday, July 11, 2009 10:02 PM by flying

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

Excellent. Just what I needed. I am developing an app with dynamic connection strings (connecting to one of hundreds of databases pending on who runs it)

Friday, July 17, 2009 10:14 AM by Peter B.L. Rasmussen

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

You are the best man!

For several months I have been searching for this issue, and your solution works great!

Thanks again

Thursday, July 23, 2009 3:41 PM by Horace

# Ordeal: Strongly Typed DataSet Connection String &laquo; Ideal Ordeal? Deal.

Pingback from  Ordeal: Strongly Typed DataSet Connection String &laquo; Ideal Ordeal? Deal.

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

thank u very very much

Thursday, May 13, 2010 12:55 PM by scevola

# re: Changing the connectionstring of a wizard generated TableAdapter at runtime from an ObjectDataSource

"NullReferenceException was unhandled by user code"

Solution: Change the connection modifier of the table adapter to "Public"

Tuesday, June 01, 2010 8:35 PM by edgardo cunanan

# Runtime tableadapter | Shaadui

Pingback from  Runtime tableadapter | Shaadui

Friday, September 23, 2011 5:29 AM by Runtime tableadapter | Shaadui

Leave a Comment

(required) 
(required) 
(optional)
(required)