在运行时vs2010更改数据集连接字符串

时间:2013-02-19 16:24:10

标签: c# sql dataset

我找到了一个解决方案,必须是旧版本然后vs2010。我想知道如何为vs2010做到这一点?有谁知道吗?

http://www.csharpbydesign.com/2008/01/overriding-dataset-settings-co.html

让我解释一下细节。

我有一个c#生成的数据集。如何更改连接字符串,以便将数据集与另一个(结构相同但填充程度不同的)数据库一起使用?这必须在运行时发生,因为我不知道编译时的服务器或数据库名称。我正在使用vs2010和SQL Server 2008 R2 Express

2 个答案:

答案 0 :(得分:5)

我认为没有简单的方法,您无法以编程方式更改整个DataSet的连接字符串,因为它是为每个TableAdapter设置的。

您需要使用/创建TableAdapter的部分类来更改连接字符串,因为Connection属性为internal(如果您的DAL位于不同的程序集中)。不要更改designer.cs文件,因为它将在设计器上的下一次更改后自动重新创建。要创建它,只需右键单击DataSet并选择“show code”。

例如(假设TableAdapter名为ProductTableAdapter):

namespace WindowsFormsApplication1.DataSet1TableAdapters
{
    public partial class ProductTableAdapter 
    {
        public string ConnectionString {
            get { return Connection.ConnectionString; }
            set { Connection.ConnectionString = value; }
        }
    }
}

现在您可以轻松更改它:

var productTableAdapter = new DataSet1TableAdapters.ProductTableAdapter();
productTableAdapter.ConnectionString = someOtherConnectionString;

这是我的示例DataSet和创建的文件DataSet1.cs的screesnhot:

enter image description here

答案 1 :(得分:0)

实际上更改连接字符串的方法更简单。 转到“设置”屏幕,其中连接字符串显示为连接字符串。 首先标记并复制显示的连接字符串。 然后将类型从连接字符串更改为字符串。字符串的文本将更改为包含xml。 然后将复制的连接字符串粘贴到xml文本上。 然后将范围从Application更改为User。

当我想更改连接字符串时,我使用以下代码。

// assign the path to use to the variable fullpath (or whatever)
string newConnection = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}", fullpath);            
Properties.Settings.Default.HootConnectionString = newConnection;
Properties.Settings.Default.Save();

就我而言,我有一个全局数据集处于活动状态,所以我必须让tableadapter重新读取数据。当然,您必须添加错误控制以确保数据库仍在那里。

您会注意到这不会改变“应用程序设置”中显示的内容。这些都是默认值。

这适用于Access数据库;所以你的里程和要求可能会有所不同。

编辑:警告。在安装时,连接字符串可以很好地打开和读取数据库内容,但是在尝试更新数据库时它抱怨没有连接字符串。

相关问题