我的 Windows 窗体应用程序使用强类型数据集,该数据集是使用 Visual Studio 中的设计器创建的。在运行时,我希望能够选择实时或测试数据库。
在运行时以编程方式设置数据集连接字符串的最佳方法是什么?
最佳答案
TableAdapter 中的连接属性定义为内部。
internal global::System.Data.SqlClient.SqlConnection Connection
So in case your TypedDataset is not in the same assembly as your main windows forms app, you will not be able to access Connection property. This problem might popup later when you refactor your dataset code and move it into a seperate project which will produce its own independant assembly.
要解决此问题,您可以按照以下说明进行操作。
为您的 TableAdapter 创建部分类,并在默认的公共(public)无参数构造函数旁边添加另一个构造函数。假设 TableAdapter 类型为 MyTableAdapter
public partial class MyTableAdapter
{
public MyTableAdapter(SqlConnection connection)
{
thisSetConnection(connection);
this.ClearBeforeFill = true;
}
public void SetConnection(SqlConnection connection)
{
this._connection = connection;
}
}
您需要为项目中的尽可能多的 TableAdapter 执行此操作。 TableAdapter 没有任何公共(public)基类,但感谢它们被声明为部分类,因此我们能够按照上述方式进行操作。
现在在运行时,您可以像这样创建 TableAdapter 的实例。
SqlConnection connection;
//create the connection here at runtime..
MyTableAdapter adapter = new MyTableAdapter(connection);
或者甚至可以在您使用默认无参数公共(public)构造函数创建 TableAdapter 实例之后分配它..
SqlConnection connection;
//create the connection here at runtime..
MyTableAdapter adapter = new MyTableAdapter();
adapter.SetConnection(connection);
关于c# - 在运行时设置强类型数据集连接字符串的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/695491/