如何在asp.net中的对象数据源中动态更改连接字符串?
答案 0 :(得分: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);
}
}
我希望它有所帮助。
答案 1 :(得分:1)
我没有得到上述工作但是这样做了:
if (e.ObjectInstance != null)
{
((ReportPrototype.ReleasedRatingsDataTableAdapters.RatingsViewTableAdapter)e.ObjectInstance).Connection.ConnectionString = ConfigurationManager.ConnectionStrings["RADSDataConnectionString"].ConnectionString;
}
ObjectInstance是表适配器,在我的例子中是绑定到ObjectDataSource的类型。
答案 2 :(得分:0)
这是一种适用于所有生成的表适配器的方法,使用反射:
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;
}
}
请注意,Microsoft生成的Connection属性是作为内部创建的(在我的VS 2013上),因此您需要将BindingFlags.NonPublic提供给GetProperty。
当然,以这种或那种方式连接ObjectCreated事件:
ObjectDataSource ObjectDataSource1 = new ObjectDataSource();
...
ObjectDataSource1.ObjectCreated += OnObjectDataSourceObjectCreated;