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.
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.