本文介绍了设置强类型数据集的连接字符串在运行时的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Windows窗体应用程序使用的是通过设计师在Visual Studio中创建一个强类型数据集。在运行时,我希望能够选择现场或测试数据库。

什么是编程方式设置为在运行时数据集的连接字符串的最佳方式是什么?

解决方案

在TableAdapter的连接属性被定义为内部

 内部全局:: System.Data.SqlClient.SqlConnection连接
 

要解决这个问题,如下所述,你可以做。

为您的TableAdapter创建部分类,并添加另一个构造默认的公共参数构造函数旁边。假设TableAdapter的类型MyTableAdapter

 公共部分类MyTableAdapter
{
    公共MyTableAdapter(SqlConnection的连接)
    {
        thisSetConnection(连接);
        this.ClearBeforeFill =真;
    }

    公共无效SetConnection(SqlConnection的连接)
    {
        this._connection =连接;
    }
}
 

您需要做的多达TableAdapter的你在你的项目中。 TableAdapter的没有任何共同的基类,但由于它们被声明为部分类,所以我们能够做到这一点上面提到的方法。

现在在运行时,你可以创建你的TableAdapter这样的一个实例。

 的SqlConnection连接;
//在这里创建的连接在运行时..
MyTableAdapter适配器=新MyTableAdapter(连接);
 

或者甚至可以为它分配您创建默认的无参数的公共构造TableAdapter的实例后后..

 的SqlConnection连接;
//在这里创建的连接在运行时..
MyTableAdapter适配器=新MyTableAdapter();
适配器(连接)。
 

My Windows Forms application uses a strongly typed dataset created using the designer in Visual Studio. At runtime I would like to be able to select either the live or test database.

What is the best way to programmatically set the connection string for the dataset at runtime?

解决方案

Connection property in TableAdapters is defined as internal.

internal global::System.Data.SqlClient.SqlConnection Connection

To solve this problem, you can do as mentioned below.

create partial class for your TableAdapter and add another constructor beside the default public parameterless constructor. Assuming TableAdapter type as MyTableAdapter

public partial class MyTableAdapter
{
    public MyTableAdapter(SqlConnection connection)
    {
        thisSetConnection(connection);
        this.ClearBeforeFill = true;
    }

    public void SetConnection(SqlConnection connection)
    {
        this._connection = connection;
    }
}

You will need to do this for as many as TableAdapters you have in your project. TableAdapter does not have any common base class but thanks that they are declared as partial classes so we are able to do it the way mentioned above.

Now at runtime, you can create an instance of your TableAdapter like this..

SqlConnection connection;
//create the connection here at runtime..
MyTableAdapter adapter = new MyTableAdapter(connection);

or may be even assign it later after you create the TableAdapter instance with default parameterless public constructor..

SqlConnection connection;
//create the connection here at runtime..
MyTableAdapter adapter = new MyTableAdapter();
adapter.(connection);

这篇关于设置强类型数据集的连接字符串在运行时的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 14:25