0

how to change connection string dynamically in object datasource in asp.net ?

3 Answers 3

4
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);
    }
}

I hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

2

I didn't get the above to work but this did:

  if (e.ObjectInstance != null)
  {
    ((ReportPrototype.ReleasedRatingsDataTableAdapters.RatingsViewTableAdapter)e.ObjectInstance).Connection.ConnectionString = ConfigurationManager.ConnectionStrings["RADSDataConnectionString"].ConnectionString;
  }

ObjectInstance is the table adapter which in my case was the type bound to the ObjectDataSource.

1 Comment

Late comment: I've been unable to make the accepted answer work, as I get a null reference for the results of GetProperty("Connection"), but this technique works consistently for me in ASP.NET 4.
0

Here's an approach that will work for all generated table adapters, using reflection:

void OnObjectDataSourceObjectCreated(object sender, ObjectDataSourceEventArgs e)
{
    if (e.ObjectInstance != null)
    {
        ((SqlConnection)e.ObjectInstance.GetType()
            .GetProperty("Connection", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance )
            .GetValue(e.ObjectInstance, null)
         ).ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    }
}

Note that the Connection property Microsoft generates is created as internal (on my VS 2013), so you need to give BindingFlags.NonPublic to GetProperty.

And of course, wire up the ObjectCreated event one way or another:

ObjectDataSource ObjectDataSource1 = new ObjectDataSource();
...
ObjectDataSource1.ObjectCreated += OnObjectDataSourceObjectCreated;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.