Declaring SqlConnection throughout one form

后端 未结 4 1649
感情败类
感情败类 2020-12-22 02:25

I\'m looking for some advise on C# - Please bare in mind that i\'m only a beginner with C# & Sql.

I am looking to design a small program that will Add/Edit/Dele

4条回答
  •  無奈伤痛
    2020-12-22 02:33

    Consider to declare your SqlConnection as field of your main form (if you don't want to use it on any other form).

    Note: Add reference to System.Configuration assembly in order to use ConfigurationManager class.

    Example:

    public partial class MainMenu : Form
    {
        SqlConnection _myConnection;
    
        public Form1()
        {
            InitializeComponent();
    
            this._myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
        }
    
        public void ExecuteAQueryExample()
        {
            if (this._myConnection.State != ConnectionState.Open) this._myConnection.Open();
    
            using (var command = this._myConnection.CreateCommand())
            {
                // ...
            }
    
            this._myConnection.Close();
        }
    }
    

提交回复
热议问题