1. 程式人生 > >c# winform做的SqlServer資料庫伺服器連線配置登入介面

c# winform做的SqlServer資料庫伺服器連線配置登入介面

使用該介面完成資料庫伺服器的連線配置,給使用者提供一個方便、友好、易操作的介面。

首次配置成功後,下次登入就直接使用已配置連線登入。

如果需要更改另外的連線,可以直接將程式中的xxxx.exe.config檔案刪除。

用此登入介面結合開發的主程式執行。並設定好程式依賴關係。

以下為詳細說明:

1、配置介面


這個介面用到了DevComponents.DotNetBar外掛。

步驟:

1)下載DevComponents.DotNetBar2.dll(VS2010需要v10.0以上版本)

2)為工程新增引用,瀏覽找到DevComponents.DotNetBar2.dll

3)程式碼中新增using DevComponents.DotNetBar;

下載地址網上很容易找到,這裡提供一個:http://www.pc6.com/softview/SoftView_95579.html


2、用到的類

1)ConfigType.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ServerTest.AppConfig
{
    public enum ConfigType
    {
        /// <summary> 
        /// asp.net網站的config檔案 
        /// </summary> 
        WebConfig = 1,
        /// <summary> 
        /// Windows應用程式的config檔案 
        /// </summary> 
        ExeConfig = 2
    }
}

2)ConfigurationOperator.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Windows.Forms;

namespace ServerTest.AppConfig
{
    /// <summary> 
    /// 說明:本類主要負責對程式配置檔案(.config)進行修改的類, 
    /// 可以對網站和應用程式的配置檔案進行修改 
    /// 作者:toff95 
    /// 日期:2014-09-10 
    /// 首發地址:http://blog.csdn.net/toff95
    /// </summary> 
    public class ConfigurationOperator
    {
        private Configuration config;
        private string configPath;
        private ConfigType configType;
        /// <summary> 
        /// 對應的配置檔案 
        /// </summary> 
        public Configuration Configuration
        {
            get { return config; }
            set { config = value; }
        }
        /// <summary> 
        /// 建構函式 
        /// </summary> 
        /// <param name="configType">.config檔案的型別,只能是網站配置檔案或者應用程式配置檔案</param> 
        public ConfigurationOperator(ConfigType configType)
        {
            this.configType = configType;
            if (configType == ConfigType.ExeConfig)
            {
                configPath = Application.ExecutablePath;
                //AppDomain.CurrentDomain.BaseDirectory; 
            }
            else
            {
                //configPath = HttpContext.Current.Request.ApplicationPath; 
            }
            Initialize();
        }
        /// <summary> 
        /// 建構函式 
        /// </summary> 
        /// <param name="path">.config檔案的位置</param> 
        /// <param name="type">.config檔案的型別,只能是網站配置檔案或者應用程式配置檔案</param> 
        public ConfigurationOperator(string configPath, ConfigType configType)
        {
            this.configPath = configPath;
            this.configType = configType;
            Initialize();
        }
        //例項化configuration,根據配置檔案型別的不同,分別採取了不同的例項化方法 
        private void Initialize()
        {
            //如果是WinForm應用程式的配置檔案 
            if (configType == ConfigType.ExeConfig)
            {
                config = System.Configuration.ConfigurationManager.OpenExeConfiguration(configPath);
            }
            else//WebForm的配置檔案 
            {
                //config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(configPath); 
            }
        }
        /// <summary> 
        /// 新增應用程式配置節點,如果已經存在此節點,則會修改該節點的值 
        /// </summary> 
        /// <param name="key">節點名稱</param> 
        /// <param name="value">節點值</param> 
        public void AddAppSetting(string key, string value)
        {
            AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings");
            if (appSetting.Settings[key] == null)//如果不存在此節點,則新增 
            {
                appSetting.Settings.Add(key, value);
            }
            else//如果存在此節點,則修改 
            {
                ModifyAppSetting(key, value);
            }
        }
        /// <summary> 
        /// 新增資料庫連線字串節點,如果已經存在此節點,則會修改該節點的值 
        /// </summary> 
        /// <param name="key">節點名稱</param> 
        /// <param name="value">節點值</param> 
        public void AddConnectionString(string key, string connectionString)
        {
            ConnectionStringsSection connectionSetting = (ConnectionStringsSection)config.GetSection("connectionStrings");
            if (connectionSetting.ConnectionStrings[key] == null)//如果不存在此節點,則新增 
            {
                ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(key, connectionString);
                connectionSetting.ConnectionStrings.Add(connectionStringSettings);
            }
            else//如果存在此節點,則修改 
            {
                ModifyConnectionString(key, connectionString);
            }
        }
        /// <summary> 
        /// 修改應用程式配置節點,如果不存在此節點,則會新增此節點及對應的值 
        /// </summary> 
        /// <param name="key">節點名稱</param> 
        /// <param name="value">節點值</param> 
        public void ModifyAppSetting(string key, string newValue)
        {
            AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings");
            if (appSetting.Settings[key] != null)//如果存在此節點,則修改 
            {
                appSetting.Settings[key].Value = newValue;
            }
            else//如果不存在此節點,則新增 
            {
                AddAppSetting(key, newValue);
            }
        }
        /// <summary> 
        /// 修改資料庫連線字串節點,如果不存在此節點,則會新增此節點及對應的值 
        /// </summary> 
        /// <param name="key">節點名稱</param> 
        /// <param name="value">節點值</param> 
        public void ModifyConnectionString(string key, string connectionString)
        {
            ConnectionStringsSection connectionSetting = (ConnectionStringsSection)config.GetSection("connectionStrings");
            if (connectionSetting.ConnectionStrings[key] != null)//如果存在此節點,則修改 
            {
                connectionSetting.ConnectionStrings[key].ConnectionString = connectionString;
            }
            else//如果不存在此節點,則新增 
            {
                AddConnectionString(key, connectionString);
            }
        }
        /// <summary> 
        /// 儲存所作的修改 
        /// </summary> 
        public void Save()
        {
            config.Save();
        }
    }
}

3)ConntionConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using DevComponents.DotNetBar;
using System.Windows.Forms;
using ServerTest.Forms;
using System.Data.SqlClient;
using System.Data;
using System.Security.Cryptography;

namespace ServerTest.AppConfig
{
    /// <summary>
    /// SQL資料庫伺服器配置靜態類
    /// </summary>
    public class ConntionConfig
    {
        /// <summary>
        /// 檢查配置資訊
        /// </summary>
        /// <returns>完整有效返回true,無效則啟動配置介面</returns>
        public static bool CheckConntionConfig()
        {
            if (CheckedConnection())
            {
                return true;
            }
            else
            {
               return CheckedConfig();
            }
        }

        /// <summary>
        /// 驗證配置資訊
        /// </summary>
        private static bool CheckedConfig()
        {
            MessageBoxEx.Show("資料庫伺服器無法連線,請重新配置。",
                   "系統提示",
                   MessageBoxButtons.OK,
                   MessageBoxIcon.Warning);

            SvrConf svrConf = new SvrConf();
            svrConf.ShowDialog();

            if (MessageBoxEx.Show("是否現在進入系統?", "詢問",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question) == DialogResult.Yes)
            {
                return CheckConntionConfig();
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 驗證配置資訊的資料庫連線
        /// </summary>
        private static bool CheckedConnection()
        {
            string connectionString = ConString();
            return !string.IsNullOrEmpty(connectionString) &&
                   TestConntion(connectionString);
        }

        /// <summary>
        /// 測試與伺服器資料庫是否成功連線
        /// </summary>
        /// <param name="connectionString">資料庫連線字串</param>
        /// <returns></returns>
        public static bool TestConntion(string connectionString)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                try
                {
                    if (conn.State == ConnectionState.Open)
                        conn.Close();
                    conn.Open();
                    return true;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }

        /// <summary>
        /// 資料庫連線字串,自動判斷加密狀態並獲取對應連線字串。
        /// </summary>
        /// <returns></returns>
        public static string ConString()
        {
            if (IsEncrypt())
            {
                string cstr = ConfigurationManager.AppSettings["ConnectionString"];
                try
                {
                    //解密後的資料庫連線字串
                    cstr = DESEncrypt.Decrypt(cstr);
                    return cstr;
                }
                catch 
                {
                    //如果勾選加密,第一次登陸時取到的是未加密連線字串,所以直接返回。如果返回空字串會導致首次登陸失敗。
                    //ConfigurationManager.AppSettings["ConnectionString"] = string.Empty;
                    //return string.Empty;
                    return cstr;
                }
            }
            else
            {
                //無須解密的資料庫連線字串
                return ConfigurationManager.AppSettings["ConnectionString"];
            }
           
        }

        /// <summary>
        /// 驗證是否已加密
        /// </summary>
        /// <returns></returns>
        internal static bool IsEncrypt()
        {
            switch (ConfigurationManager.AppSettings["ConStringEncrypt"])
            {
                case "1":
                case "TRUE":
                case "true":
                    return true;
                default:
                    return false;
            }
        }
    }
}

4)DESEncrypt.cs加密解密類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Web.Security;

namespace ServerTest
{
    /// <summary>
    /// DES加密/解密類。
    /// </summary>
    public class DESEncrypt
    {
        public DESEncrypt()
        {
        }

        #region ========加密========

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, "toff95");
        }
        /// <summary> 
        /// 加密資料 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        #endregion

        #region ========解密========


        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Decrypt(string Text)
        {
            return Decrypt(Text, "toff95");
        }

        /// <summary> 
        /// 解密資料 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Decrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;
            len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }

        #endregion
    }
}

3、配置介面程式碼 SvrConf.Designer.cs
namespace ServerTest.Forms
{
    partial class SvrConf
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.chkEncrypt = new DevComponents.DotNetBar.Controls.CheckBoxX();
            this.labelX1 = new DevComponents.DotNetBar.LabelX();
            this.labelX5 = new DevComponents.DotNetBar.LabelX();
            this.lstServer = new System.Windows.Forms.ListBox();
            this.txtServer = new DevComponents.DotNetBar.Controls.TextBoxX();
            this.labelX4 = new DevComponents.DotNetBar.LabelX();
            this.labelX2 = new DevComponents.DotNetBar.LabelX();
            this.labelX3 = new DevComponents.DotNetBar.LabelX();
            this.txtPwd = new DevComponents.DotNetBar.Controls.TextBoxX();
            this.txtDataBase = new DevComponents.DotNetBar.Controls.TextBoxX();
            this.PanelDataBase = new DevComponents.DotNetBar.Controls.GroupPanel();
            this.txtUid = new DevComponents.DotNetBar.Controls.TextBoxX();
            this.btnTest = new DevComponents.DotNetBar.ButtonItem();
            this.commandTest = new DevComponents.DotNetBar.Command();
            this.PanelServersList = new DevComponents.DotNetBar.Controls.GroupPanel();
            this.proWait = new DevComponents.DotNetBar.ProgressBarItem();
            this.bar1 = new DevComponents.DotNetBar.Bar();
            this.btnSave = new DevComponents.DotNetBar.ButtonItem();
            this.commandSave = new DevComponents.DotNetBar.Command();
            this.btnCancel = new DevComponents.DotNetBar.ButtonItem();
            this.commandCancel = new DevComponents.DotNetBar.Command();
            this.PanelDataBase.SuspendLayout();
            this.PanelServersList.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.bar1)).BeginInit();
            this.SuspendLayout();
            // 
            // chkEncrypt
            // 
            this.chkEncrypt.AutoSize = true;
            this.chkEncrypt.BackColor = System.Drawing.Color.Transparent;
            this.chkEncrypt.Location = new System.Drawing.Point(113, 178);
            this.chkEncrypt.Name = "chkEncrypt";
            this.chkEncrypt.Size = new System.Drawing.Size(26, 16);
            this.chkEncrypt.TabIndex = 4;
            this.chkEncrypt.Text = " ";
            // 
            // labelX1
            // 
            this.labelX1.AutoSize = true;
            this.labelX1.BackColor = System.Drawing.Color.Transparent;
            this.labelX1.Location = new System.Drawing.Point(51, 21);
            this.labelX1.Name = "labelX1";
            this.labelX1.Size = new System.Drawing.Size(56, 18);
            this.labelX1.TabIndex = 5;
            this.labelX1.Text = "伺服器:";
            // 
            // labelX5
            // 
            this.labelX5.AutoSize = true;
            this.labelX5.BackColor = System.Drawing.Color.Transparent;
            this.labelX5.Location = new System.Drawing.Point(51, 178);
            this.labelX5.Name = "labelX5";
            this.labelX5.Size = new System.Drawing.Size(56, 18);
            this.labelX5.TabIndex = 9;
            this.labelX5.Text = "加  密:";
            // 
            // lstServer
            // 
            this.lstServer.Dock = System.Windows.Forms.DockStyle.Fill;
            this.lstServer.FormattingEnabled = true;
            this.lstServer.ItemHeight = 12;
            this.lstServer.Location = new System.Drawing.Point(0, 0);
            this.lstServer.Name = "lstServer";
            this.lstServer.Size = new System.Drawing.Size(168, 205);
            this.lstServer.TabIndex = 3;
            this.lstServer.SelectedIndexChanged += new System.EventHandler(this.lstServer_SelectedIndexChanged);
            // 
            // txtServer
            // 
            // 
            // 
            // 
            this.txtServer.Border.Class = "TextBoxBorder";
            this.txtServer.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
            this.txtServer.Location = new System.Drawing.Point(113, 18);
            this.txtServer.Name = "txtServer";
            this.txtServer.Size = new System.Drawing.Size(147, 21);
            this.txtServer.TabIndex = 0;
            // 
            // labelX4
            // 
            this.labelX4.AutoSize = true;
            this.labelX4.BackColor = System.Drawing.Color.Transparent;
            this.labelX4.Location = new System.Drawing.Point(51, 138);
            this.labelX4.Name = "labelX4";
            this.labelX4.Size = new System.Drawing.Size(56, 18);
            this.labelX4.TabIndex = 8;
            this.labelX4.Text = "密  碼:";
            // 
            // labelX2
            // 
            this.labelX2.AutoSize = true;
            this.labelX2.BackColor = System.Drawing.Color.Transparent;
            this.labelX2.Location = new System.Drawing.Point(51, 60);
            this.labelX2.Name = "labelX2";
            this.labelX2.Size = new System.Drawing.Size(56, 18);
            this.labelX2.TabIndex = 6;
            this.labelX2.Text = "資料庫:";
            // 
            // labelX3
            // 
            this.labelX3.AutoSize = true;
            this.labelX3.BackColor = System.Drawing.Color.Transparent;
            this.labelX3.Location = new System.Drawing.Point(51, 99);
            this.labelX3.Name = "labelX3";
            this.labelX3.Size = new System.Drawing.Size(56, 18);
            this.labelX3.TabIndex = 7;
            this.labelX3.Text = "使用者名稱:";
            // 
            // txtPwd
            // 
            // 
            // 
            // 
            this.txtPwd.Border.Class = "TextBoxBorder";
            this.txtPwd.Location = new System.Drawing.Point(113, 135);
            this.txtPwd.Name = "txtPwd";
            this.txtPwd.Size = new System.Drawing.Size(147, 21);
            this.txtPwd.TabIndex = 3;
            this.txtPwd.UseSystemPasswordChar = true;
            // 
            // txtDataBase
            // 
            // 
            // 
            // 
            this.txtDataBase.Border.Class = "TextBoxBorder";
            this.txtDataBase.Location = new System.Drawing.Point(113, 57);
            this.txtDataBase.Name = "txtDataBase";
            this.txtDataBase.Size = new System.Drawing.Size(147, 21);
            this.txtDataBase.TabIndex = 1;
            // 
            // PanelDataBase
            // 
            this.PanelDataBase.CanvasColor = System.Drawing.SystemColors.Control;
            this.PanelDataBase.ColorSchemeStyle = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;
            this.PanelDataBase.Controls.Add(this.chkEncrypt);
            this.PanelDataBase.Controls.Add(this.labelX1);
            this.PanelDataBase.Controls.Add(this.labelX5);
            this.PanelDataBase.Controls.Add(this.txtServer);
            this.PanelDataBase.Controls.Add(this.labelX4);
            this.PanelDataBase.Controls.Add(this.labelX2);
            this.PanelDataBase.Controls.Add(this.labelX3);
            this.PanelDataBase.Controls.Add(this.txtPwd);
            this.PanelDataBase.Controls.Add(this.txtDataBase);
            this.PanelDataBase.Controls.Add(this.txtUid);
            this.PanelDataBase.Dock = System.Windows.Forms.DockStyle.Fill;
            this.PanelDataBase.Location = new System.Drawing.Point(174, 0);
            this.PanelDataBase.Name = "PanelDataBase";
            this.PanelDataBase.Size = new System.Drawing.Size(316, 229);
            // 
            // 
            // 
            this.PanelDataBase.Style.BackColor2SchemePart = DevComponents.DotNetBar.eColorSchemePart.PanelBackground2;
            this.PanelDataBase.Style.BackColorGradientAngle = 90;
            this.PanelDataBase.Style.BackColorSchemePart = DevComponents.DotNetBar.eColorSchemePart.PanelBackground;
            this.PanelDataBase.Style.BorderBottom = DevComponents.DotNetBar.eStyleBorderType.Solid;
            this.PanelDataBase.Style.BorderBottomWidth = 1;
            this.PanelDataBase.Style.BorderColorSchemePart = DevComponents.DotNetBar.eColorSchemePart.PanelBorder;
            this.PanelDataBase.Style.BorderLeft = DevComponents.DotNetBar.eStyleBorderType.Solid;
            this.PanelDataBase.Style.BorderLeftWidth = 1;
            this.PanelDataBase.Style.BorderRight = DevComponents.DotNetBar.eStyleBorderType.Solid;
            this.PanelDataBase.Style.BorderRightWidth = 1;
            this.PanelDataBase.Style.BorderTop = DevComponents.DotNetBar.eStyleBorderType.Solid;
            this.PanelDataBase.Style.BorderTopWidth = 1;
            this.PanelDataBase.Style.CornerDiameter = 4;
            this.PanelDataBase.Style.CornerType = DevComponents.DotNetBar.eCornerType.Rounded;
            this.PanelDataBase.Style.TextAlignment = DevComponents.DotNetBar.eStyleTextAlignment.Center;
            this.PanelDataBase.Style.TextColorSchemePart = DevComponents.DotNetBar.eColorSchemePart.PanelText;
            this.PanelDataBase.TabIndex = 16;
            this.PanelDataBase.Text = "資料庫資訊";
            // 
            // txtUid
            // 
            // 
            // 
            // 
            this.txtUid.Border.Class = "TextBoxBorder";
            this.txtUid.Location = new System.Drawing.Point(113, 96);
            this.txtUid.Name = "txtUid";
            this.txtUid.Size = new System.Drawing.Size(147, 21);
            this.txtUid.TabIndex = 2;
            // 
            // btnTest
            // 
            this.btnTest.Command = this.commandTest;
            this.btnTest.ImagePaddingHorizontal = 8;
            this.btnTest.Name = "btnTest";
            this.btnTest.Text = "測試連線";
            // 
            // commandTest
            // 
            this.commandTest.Executed += new System.EventHandler(this.commandRefurbish_Executed);
            // 
            // PanelServersList
            // 
            this.PanelServersList.CanvasColor = System.Drawing.SystemColors.Control;
            this.PanelServersList.ColorSchemeStyle = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;
            this.PanelServersList.Controls.Add(this.lstServer);
            this.PanelServersList.Dock = System.Windows.Forms.DockStyle.Left;
            this.PanelServersList.Location = new System.Drawing.Point(0, 0);
            this.PanelServersList.Name = "PanelServersList";
            this.PanelServersList.Size = new System.Drawing.Size(174, 229);
            // 
            // 
            // 
            this.PanelServersList.Style.BackColor2SchemePart = DevComponents.DotNetBar.eColorSchemePart.PanelBackground2;
            this.PanelServersList.Style.BackColorGradientAngle = 90;
            this.PanelServersList.Style.BackColorSchemePart = DevComponents.DotNetBar.eColorSchemePart.PanelBackground;
            this.PanelServersList.Style.BorderBottom = DevComponents.DotNetBar.eStyleBorderType.Solid;
            this.PanelServersList.Style.BorderBottomWidth = 1;
            this.PanelServersList.Style.BorderColorSchemePart = DevComponents.DotNetBar.eColorSchemePart.PanelBorder;
            this.PanelServersList.Style.BorderLeft = DevComponents.DotNetBar.eStyleBorderType.Solid;
            this.PanelServersList.Style.BorderLeftWidth = 1;
            this.PanelServersList.Style.BorderRight = DevComponents.DotNetBar.eStyleBorderType.Solid;
            this.PanelServersList.Style.BorderRightWidth = 1;
            this.PanelServersList.Style.BorderTop = DevComponents.DotNetBar.eStyleBorderType.Solid;
            this.PanelServersList.Style.BorderTopWidth = 1;
            this.PanelServersList.Style.CornerDiameter = 4;
            this.PanelServersList.Style.CornerType = DevComponents.DotNetBar.eCornerType.Rounded;
            this.PanelServersList.Style.TextAlignment = DevComponents.DotNetBar.eStyleTextAlignment.Center;
            this.PanelServersList.Style.TextColorSchemePart = DevComponents.DotNetBar.eColorSchemePart.PanelText;
            this.PanelServersList.TabIndex = 15;
            this.PanelServersList.Text = "伺服器列表";
            // 
            // proWait
            // 
            // 
            // 
            // 
            this.proWait.BackStyle.TextAlignment = DevComponents.DotNetBar.eStyleTextAlignment.Center;
            this.proWait.BackStyle.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
            this.proWait.ChunkColor = System.Drawing.Color.Red;
            this.proWait.ChunkGradientAngle = 0F;
            this.proWait.MenuVisibility = DevComponents.DotNetBar.eMenuVisibility.VisibleAlways;
            this.proWait.Name = "proWait";
            this.proWait.ProgressType = DevComponents.DotNetBar.eProgressItemType.Marquee;
            this.proWait.RecentlyUsed = false;
            this.proWait.Stretch = true;
            this.proWait.Text = "正在載入伺服器列表!請稍等...";
            this.proWait.TextVisible = true;
            // 
            // bar1
            // 
            this.bar1.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.bar1.Items.AddRange(new DevComponents.DotNetBar.BaseItem[] {
            this.proWait,
            this.btnTest,
            this.btnSave,
            this.btnCancel});
            this.bar1.Location = new System.Drawing.Point(0, 229);
            this.bar1.Name = "bar1";
            this.bar1.Size = new System.Drawing.Size(490, 25);
            this.bar1.Stretch = true;
            this.bar1.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;
            this.bar1.TabIndex = 17;
            this.bar1.TabStop = false;
            // 
            // btnSave
            // 
            this.btnSave.Command = this.commandSave;
            this.btnSave.ImagePaddingHorizontal = 8;
            this.btnSave.Name = "btnSave";
            this.btnSave.Text = "儲存";
            // 
            // commandSave
            // 
            this.commandSave.Executed += new System.EventHandler(this.commandSave_Executed);
            // 
            // btnCancel
            // 
            this.btnCancel.Command = this.commandCancel;
            this.btnCancel.ImagePaddingHorizontal = 8;
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.Text = "關閉";
            // 
            // commandCancel
            // 
            this.commandCancel.Executed += new System.EventHandler(this.commandCancel_Executed);
            // 
            // SvrConf
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(490, 254);
            this.Controls.Add(this.PanelDataBase);
            this.Controls.Add(this.PanelServersList);
            this.Controls.Add(this.bar1);
            this.Name = "SvrConf";
            this.Text = "連線資料庫伺服器";
            this.Load += new System.EventHandler(this.SvrConf_Load);
            this.PanelDataBase.ResumeLayout(false);
            this.PanelDataBase.PerformLayout();
            this.PanelServersList.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.bar1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private DevComponents.DotNetBar.Controls.CheckBoxX chkEncrypt;
        private DevComponents.DotNetBar.LabelX labelX1;
        private DevComponents.DotNetBar.LabelX labelX5;
        private System.Windows.Forms.ListBox lstServer;
        private DevComponents.DotNetBar.Controls.TextBoxX txtServer;
        private DevComponents.DotNetBar.LabelX labelX4;
        private DevComponents.DotNetBar.LabelX labelX2;
        private DevComponents.DotNetBar.LabelX labelX3;
        private DevComponents.DotNetBar.Controls.TextBoxX txtPwd;
        private DevComponents.DotNetBar.Controls.TextBoxX txtDataBase;
        private DevComponents.DotNetBar.Controls.GroupPanel PanelDataBase;
        private DevComponents.DotNetBar.Controls.TextBoxX txtUid;
        private DevComponents.DotNetBar.ButtonItem btnTest;
        private DevComponents.DotNetBar.Command commandTest;
        private DevComponents.DotNetBar.Controls.GroupPanel PanelServersList;
        private DevComponents.DotNetBar.ProgressBarItem proWait;
        private DevComponents.DotNetBar.Bar bar1;
        private DevComponents.DotNetBar.ButtonItem btnSave;
        private DevComponents.DotNetBar.Command commandSave;
        private DevComponents.DotNetBar.ButtonItem btnCancel;
        private DevComponents.DotNetBar.Command commandCancel;
    }
}

4、視窗程式 SvrConf.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.Threading;
using System.Data.Sql;
using System.Configuration;
using ServerTest.AppConfig;

namespace ServerTest.Forms
{
    /// <summary>
    /// SQL資料庫伺服器配置介面
    /// </summary>
    internal partial class SvrConf : Office2007Form
    {
        #region 值域成員

        delegate void BindList(DataTable dt);
        delegate void Mydelegate(bool a);
        delegate void LoadValue(string value);
        delegate void AddValue(object value);
        delegate void Thisdelegate();
        Thread thread;
        #endregion

        #region 載入例項

        public SvrConf()
        {
            InitializeComponent();
        }

        private void SvrConf_Load(object sender, EventArgs e)
        {
            ReadConfig();
            StartTread();
        }

        /// <summary>
        /// 開啟執行緒
        /// </summary>
        private void StartTread()
        {
            BeginTask();
            ShowText("正在載入伺服器列表,請稍等...");
            //開啟執行緒
            thread = new Thread(new ThreadStart(LoadSqlServerList));
            thread.Start();
        }

        /// <summary>
        /// 載入伺服器列表
        /// </summary>
        private void LoadSqlServerList()
        {
            FillList();
            EndTask();
        }

        /// <summary>
        /// 填充伺服器列表
        /// </summary>
        private void FillList()
        {
            //獲取本地網路的所有伺服器
            SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
            DataTable dt = instance.GetDataSources();

            foreach (DataRow row in dt.Rows)
            {
                ShowText("正在載入伺服器:" + row["ServerName"].ToString());
                AddServer(row["ServerName"]);
            }
            ShowText("伺服器載入完畢");
        }

        /// <summary>
        /// 讀取資料庫配置資訊
        /// </summary>
        private void ReadConfig()
        {
            if (string.IsNullOrEmpty(
                ConfigurationManager.AppSettings["ConnectionString"]))
                return;
            string[] strConfig = ConfigurationManager.AppSettings["ConnectionString"].Split(';');
            txtServer.Text = strConfig[0].Replace("server=", "").Trim();
            txtDataBase.Text = strConfig[1].Replace("database=", "").Trim();
            txtUid.Text = strConfig[2].Replace("uid=", "").Trim();
            txtPwd.Text = strConfig[3].Replace("pwd=", "").Trim();

            chkEncrypt.Checked = ConntionConfig.IsEncrypt();
        }

        #endregion

        #region 選擇服務

        private void lstServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstServer.SelectedIndex < 0) return;

            txtServer.Text = lstServer.SelectedItem.ToString().Trim();

        }
        #endregion

        #region 測試連線

        private void commandRefurbish_Executed(object sender, EventArgs e)
        {
            TestConntion();
        }

        /// <summary>
        /// 測試資料庫連線,並且提示資訊
        /// </summary>
        /// <returns>是否連線成功</returns>
        private bool TestConntion()
        {
            if (ConntionConfig.TestConntion(CreateConnectionString()))
            {
                ShowText("測試連線成功");

                return true;
            }
            else
            {
                ShowText("測試連線失敗");

                return false;
            }
        }
        #endregion

        #region 關閉視窗

        private void commandCancel_Executed(object sender, EventArgs e)
        {
            CloseForm();
        }
        #endregion

        #region 儲存設定

        private void commandSave_Executed(object sender, EventArgs e)
        {
            if (!CheckInputEmpty()) return;
            //BeginTask();
            //寫入配置檔案
            WriteConfig();
            //EndTask();
        }

        /// <summary>
        /// 檢查是否輸入完整
        /// </summary>
        /// <returns></returns>
        private bool CheckInputEmpty()
        {
            if (txtServer.Text == "")
            {
                ShowText("伺服器名稱不能為空!請重新輸入!");
                return false;
            }
            if (txtDataBase.Text == "")
            {
                ShowText("資料庫名稱不能為空!請重新輸入!");
                return false;
            }
            if (txtUid.Text == "")
            {
                ShowText("使用者名稱不能為空!請重新輸入!");
                return false;
            }
            return true;
        }

        /// <summary>
        /// 寫入配置資訊
        /// </summary>
        private void WriteConfig()
        {
            ShowText("正在寫入配置檔案!請稍等....");
            ConfigurationOperator co =
                new ConfigurationOperator(Application.StartupPath +
                "\\" + Application.ProductName + ".exe",
                ConfigType.ExeConfig);
            string connectionString = CreateConnectionString();

            //檢查是否需要加密
            if (chkEncrypt.Checked)
            {
                string strConn = DESEncrypt.Encrypt(connectionString);
                co.AddAppSetting("ConStringEncrypt", "TRUE");
                co.AddAppSetting("ConnectionString", strConn);
                ConfigurationManager.AppSettings["ConStringEncrypt"] = "TRUE";
                ConfigurationManager.AppSettings["ConnectionString"] = connectionString;
            }
            else
            {
                co.AddAppSetting("ConStringEncrypt", "FALSE");
                co.AddAppSetting("ConnectionString", connectionString);
                ConfigurationManager.AppSettings["ConStringEncrypt"] = "FALSE";
                ConfigurationManager.AppSettings["ConnectionString"] = connectionString;
            }

            co.Save();//儲存寫入結果 

            ShowText("成功寫入配置檔案");
        }

        /// <summary>
        /// 建立資料庫連線字串
        /// </summary>
        private string CreateConnectionString()
        {
            string connectionString = "server=" + txtServer.Text.Trim() +
                ";database=" + txtDataBase.Text.Trim() +
                ";uid=" + txtUid.Text.Trim() +
                ";pwd=" + txtPwd.Text.Trim();

            return connectionString;
        }
        #endregion

        #region 委託方法

        /// <summary>
        /// 顯示進度條資訊
        /// </summary>
        /// <param name="text">顯示的資訊</param>
        private void ShowText(string text)
        {
            if (this.bar1.InvokeRequired)
            {
                LoadValue d = new LoadValue(ShowText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                proWait.Text = text;
            }
        }

        /// <summary>
        /// 開始任務
        /// </summary>
        private void BeginTask()
        {
            if (this.bar1.InvokeRequired)
            {
                Thisdelegate d = new Thisdelegate(BeginTask);
                this.Invoke(d, new object[] { });
            }
            else
            {
                this.Enabled = false;
                proWait.ProgressType = eProgressItemType.Marquee;
            }
        }

        /// <summary>
        /// 結束任務
        /// </summary>
        private void EndTask()
        {
            if (this.bar1.InvokeRequired)
            {
                Thisdelegate d = new Thisdelegate(EndTask);
                this.Invoke(d, new object[] { });
            }
            else
            {
                this.Enabled = true;
                proWait.ProgressType = eProgressItemType.Standard;
                thread.Abort();
            }
        }

        /// <summary>
        /// 新增伺服器
        /// </summary>
        /// <param name="item"></param>
        private void AddServer(object item)
        {
            if (this.lstServer.InvokeRequired)
            {
                AddValue d = new AddValue(AddServer);
                this.Invoke(d, new object[] { item });
            }
            else
            {
                lstServer.Items.Add(item);
            }
        }

        /// <summary>
        /// 關閉視窗
        /// </summary>
        private void CloseForm()
        {
            if (this.InvokeRequired)
            {
                Thisdelegate d = new Thisdelegate(CloseForm);
                this.Invoke(d, new object[] { });
            }
            else
            {
                this.Close();
                this.Dispose();
            }
        }
        #endregion
    }
}

這裡解決了勾選加密不能登入的問題。