【问题标题】:Changing dataset connection string in web config at runtime在运行时更改 Web 配置中的数据集连接字符串
【发布时间】:2013-09-27 23:27:41
【问题描述】:

我有一个 c# 生成的数据集。

如何更改连接字符串,以便将数据集与另一个(结构相同但填充不同)数据库一起使用?

这必须在运行时发生,因为我在编译时不知道服务器或数据库名称。我正在使用 c# 3.5

【问题讨论】:

  • 强类型数据集?

标签: asp.net


【解决方案1】:

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

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

例如(假设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 的屏幕截图:

【讨论】:

    【解决方案2】:

    ide mvs 2008 在您的 settings.designer.cs 验证程序中或编辑此

      public string NamOfappConnectionString{
            get {
                return ((string)(this["NamOfappConnectionString"]));
            }
          //add this line     
            set {
                this["NamOfappConnectionString"]=value;
            }
        }
    
     //atr untime use this
    
    
    string myconnexion = "Data Source=" + txt_data_source.Text + ";Initial Catalog=" + txt_initial_catalog.Text + ";Persist Security Info=True;";
    
        ConfigurationManager.AppSettings.Set("NamOfappConnectionString", myconnexion);
    

    //保存到设置中

    Properties.Settings.Default.NamOfappConnectionString= myconnexion;
    Application.Restart();
    

    【讨论】:

      猜你喜欢
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 2012-04-30
      相关资源
      最近更新 更多