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

后端 未结 7 1650
孤街浪徒
孤街浪徒 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.

提交回复
热议问题