How do you dynamically change the connection string in datasource object in asp.net?

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

0


source to share


3 answers


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

      



Hope this helps.

+4


source


I didn't get the above working, but it did:

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

      



ObjectInstance is a table adapter that in my case was bound to an ObjectDataSource object.

+1


source


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 created by Microsoft is instantiated internally (on my VS 2013), so you need to provide BindingFlags.NonPublic for the GetProperty.

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

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

      

0


source







All Articles