Best way to set strongly typed dataset connection string at runtime?

后端 未结 7 1799
孤街浪徒
孤街浪徒 2021-02-20 01:19

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 data

相关标签:
7条回答
  • 2021-02-20 02:21

    Re: wethercotes comment

    The wizard stores the connection string when you set up the dataset, but that doesn't mean you can't make it dynamic. How depends on which version you are using, but in general if you expand the files under your dataset you will find a file like Designer.cs, or DataTableNameAdapter.xsd. You can open those files and search for _connection. This is usually a private variable and is set in an init function in the class.

    You can make the setting dynamic by adding code like the following:

    public string ConnectionString
    {
        get { return this._connection.ConnectionString; }
        set
        {
            if (this._connection == null)
            {
                this._connection = new System.Data.SqlClient.SqlConnection();
            }
            this._connection.ConnectionString = value;
        }
    }
    

    Note that if you regenerate the dataset you will likely lose this section of code, and without refactoring the dataset you may have to add it to several objects.

    0 讨论(0)
提交回复
热议问题