在C# WinForm 应用程序非常需要一个 SQL Server 连接配置界面,许多时候,因 SQL Server 服务器地址变更或 数据库登录账户 变更引起的连接失败等情况,客户就可能打电话“找麻烦”。既然这样,还不如提供一个可视化的配置界面,并在用户手册中说明使用方法,尽可能避免这种小问题带来的烦恼。为此,我将自己无聊时写的连接配置源码贴出来给初学者参考,以备不时之需!
想必大家都很熟悉VS服务器资源管理器中的【添加连接】对话框吧!下面是它的截图:
再看看我模仿这个对话框打造的WinForm程序SQL Server 连接配置界面:
呵呵!有几分相似吧!需要的朋友可以参考下面的源码。这份源码是完整的,粘贴到VS中即可使用。
窗体源码:
-
using System;
-
using System.Collections.Generic;
-
using System.ComponentModel;
-
using System.Data;
-
using System.Drawing;
-
using System.Text;
-
using System.IO;
-
using System.Windows.Forms;
-
using System.Data.Sql;
-
using System.Data.SqlClient;
-
using System.Configuration;
-
-
-
namespace CodingMouse.CMCSharpSDK.UI.Forms
- {
-
-
-
- public partial class frmConnectionConfig : Form
- {
- #region Private Members
-
-
-
- SqlConnectionStringBuilder _connectionStringBuilder = null;
-
-
-
- string _applicationName;
-
- #endregion
-
- #region Private Methods
-
-
-
- private void GetSqlDataSource()
- {
-
- string msg = "正在获取本地网络所有 SQL Server 服务器信息 ...";
- this.toolTip.ToolTipIcon = ToolTipIcon.Info;
- this.toolTip.ToolTipTitle = "请稍候...";
- Point showLocation = new Point(
- this.lblServer.Left + 2,
- this.lblServer.Top + this.lblServer.Height);
- this.toolTip.Show(msg, this, showLocation, 1000);
-
-
- SqlDataSourceEnumerator sdsEnum = SqlDataSourceEnumerator.Instance;
-
- DataTable serverDt = sdsEnum.GetDataSources();
-
- DataColumn dcDataSource = new DataColumn("SqlDataSourceName", typeof(string));
-
- serverDt.Columns.Add(dcDataSource);
-
- DataColumn dcIsClustered = new DataColumn("IsClusteredCHS", typeof(string));
-
- serverDt.Columns.Add(dcIsClustered);
-
-
- foreach (DataRow dataRow in serverDt.Rows)
- {
- if (!string.IsNullOrEmpty(Convert.ToString(dataRow["InstanceName"])))
- dataRow["SqlDataSourceName"] = string.Format(@"{0}/{1}",
- Convert.ToString(dataRow["ServerName"]),
- Convert.ToString(dataRow["InstanceName"]));
- else
- dataRow["SqlDataSourceName"] = string.Format(@"{0}",
- Convert.ToString(dataRow["ServerName"]));
-
- dataRow["IsClusteredCHS"] =
- (Convert.ToString(dataRow["IsClustered"]).Trim().ToUpper() == "NO")
- ? "否" : ((Convert.ToString(dataRow["IsClustered"]).Trim().ToUpper() == "YES")
- ? "是" : dataRow["IsClustered"]);
- }
-
-
- if (serverDt.Rows.Count > 0)
- {
-
- BindingSource source = new BindingSource();
- source.DataSource = serverDt;
-
-
- this.cboSqlDataSource.DataSource = source;
- this.cboSqlDataSource.DisplayMember = "SqlDataSourceName";
- this.cboSqlDataSource.ValueMember = "SqlDataSourceName";
-
- this.dgvServerInfo.DataSource = source;
-
-
- this.dgvServerInfo.Columns["SqlDataSourceName"].HeaderText = "服务器名";
- this.dgvServerInfo.Columns["SqlDataSourceName"].DisplayIndex = 0;
- this.dgvServerInfo.Columns["ServerName"].HeaderText = "服务器物理名称";
- this.dgvServerInfo.Columns["ServerName"].DisplayIndex = 1;
- this.dgvServerInfo.Columns["ServerName"].Visible = false;
- this.dgvServerInfo.Columns["InstanceName"].HeaderText = "实例名";
- this.dgvServerInfo.Columns["InstanceName"].DisplayIndex = 2;
- this.dgvServerInfo.Columns["InstanceName"].Visible = false;
- this.dgvServerInfo.Columns["IsClustered"].HeaderText = "群集信息";
- this.dgvServerInfo.Columns["IsClustered"].DisplayIndex = 3;
- this.dgvServerInfo.Columns["IsClustered"].Visible = false;
- this.dgvServerInfo.Columns["IsClusteredCHS"].HeaderText = "属于群集";
- this.dgvServerInfo.Columns["IsClusteredCHS"].DisplayIndex = 4;
- this.dgvServerInfo.Columns["Version"].HeaderText = "版本";
- this.dgvServerInfo.Columns["Version"].DisplayIndex = 5;
- }
- }
-
-
-
-
- private void GetDataBaseName()
- {
-
- string msg = string.Format("正在获取服务器 [{0}] 上的数据库信息 ...", cboSqlDataSource.Text.Trim());
- this.toolTip.ToolTipIcon = ToolTipIcon.Info;
- this.toolTip.ToolTipTitle = "请稍候...";
- Point showLocation = new Point(
- this.lblServer.Left + 2,
- this.lblServer.Top + this.lblServer.Height);
- this.toolTip.Show(msg, this, showLocation, 1000);
-
-
- string sqlTxt = "Select [Name] From [SysDatabases] Order By [Name]";
-
-
- DataTable dataBaseDt = new DataTable();
-
-
- using (SqlConnection con = new SqlConnection(GetConnectionString()))
- {
-
- try
- {
-
- using (SqlDataAdapter adp = new SqlDataAdapter(sqlTxt, con))
- {
-
- adp.Fill(dataBaseDt);
- }
- }
- catch { }
- }
-
-
- if (dataBaseDt.Rows.Count > 0)
- {
-
- BindingSource source = new BindingSource();
- source.DataSource = dataBaseDt;
-
-
- cboDataBaseName.DataSource = source;
- cboDataBaseName.DisplayMember = "Name";
- cboDataBaseName.ValueMember = "Name";
- }
- else
- {
-
- cboDataBaseName.DataSource = null;
- }
- }
-
-
-
-
- private string GetConnectionString()
- {
-
- _connectionStringBuilder = new SqlConnectionStringBuilder();
-
-
- if (!string.IsNullOrEmpty(cboSqlDataSource.Text.Trim()))
- _connectionStringBuilder.DataSource = cboSqlDataSource.Text.Trim();
-
- if (rdoValidateBySQLServer.Checked)
- {
- if (!string.IsNullOrEmpty(txtUserName.Text.Trim()))
- _connectionStringBuilder.UserID = txtUserName.Text.Trim();
- if (!string.IsNullOrEmpty(txtPassword.Text.Trim()))
- _connectionStringBuilder.Password = txtPassword.Text.Trim();
- }
-
- if (!string.IsNullOrEmpty(cboDataBaseName.Text.Trim())
- || !string.IsNullOrEmpty(txtDataBaseFilePath.Text.Trim())
- || !string.IsNullOrEmpty(txtLogicalName.Text.Trim()))
- {
-
- if (rdoAttachADataBaseFile.Checked)
- {
- _connectionStringBuilder.AttachDBFilename = txtDataBaseFilePath.Text.Trim();
- _connectionStringBuilder.InitialCatalog = txtLogicalName.Text.Trim();
- }
- else
- _connectionStringBuilder.InitialCatalog = cboDataBaseName.Text.Trim();
- }
-
- if (rdoValidateByWindows.Checked)
- _connectionStringBuilder.IntegratedSecurity = true;
-
-
- return _connectionStringBuilder.ConnectionString;
- }
-
- #endregion
-
- #region Public Methods
-
-
-
- public frmConnectionConfig(string applicationName)
- {
-
- InitializeComponent();
-
-
- _applicationName = applicationName;
-
-
- _connectionStringBuilder = new SqlConnectionStringBuilder();
- _connectionStringBuilder.IntegratedSecurity = true;
-
-
-
- }
- #endregion
-
- #region Event Handlers
-
-
-
-
-
- private void cboSqlDataSource_DropDown(object sender, EventArgs e)
- {
-
- if (cboSqlDataSource.Items.Count == 0)
- {
-
- GetSqlDataSource();
- }
- }
-
-
-
-
-
-
- private void cboDataBaseName_Enter(object sender, EventArgs e)
- {
-
- GetDataBaseName();
- }
-
-
-
-
-
-
- private void tcServerInfo_Selecting(object sender, TabControlCancelEventArgs e)
- {
-
- if (cboSqlDataSource.Items.Count == 0 && e.TabPage == tpServerInfo)
- {
-
- GetSqlDataSource();
- }
- }
-
-
-
-
-
-
- private void btnRefresh_Click(object sender, EventArgs e)
- {
-
- GetSqlDataSource();
- }
-
-
-
-
-
-
- private void rdoValidateBySQLServer_CheckedChanged(object sender, EventArgs e)
- {
- if (rdoValidateBySQLServer.Checked)
- {
- _connectionStringBuilder.IntegratedSecurity = false;
- lblUserName.Enabled = true;
- txtUserName.Enabled = true;
- lblPassword.Enabled = true;
- txtPassword.Enabled = true;
-
- if (!string.IsNullOrEmpty(txtUserName.Text.Trim()))
- gbConnectToADataBase.Enabled = true;
- else
- gbConnectToADataBase.Enabled = false;
- }
- else
- {
- _connectionStringBuilder.IntegratedSecurity = true;
- lblUserName.Enabled = false;
- txtUserName.Enabled = false;
- lblPassword.Enabled = false;
- txtPassword.Enabled = false;
-
- if (!string.IsNullOrEmpty(cboSqlDataSource.Text.Trim()))
- gbConnectToADataBase.Enabled = true;
- else
- gbConnectToADataBase.Enabled = false;
- }
- }
-
-
-
-
-
-
- private void rdoAttachADataBaseFile_CheckedChanged(object sender, EventArgs e)
- {
- if (rdoAttachADataBaseFile.Checked)
- {
- cboDataBaseName.Enabled = false;
- txtDataBaseFilePath.Enabled = true;
- btnBrowse.Enabled = true;
- lblLogicalName.Enabled = true;
- txtLogicalName.Enabled = true;
- }
- else
- {
- cboDataBaseName.Enabled = true;
- txtDataBaseFilePath.Enabled = false;
- btnBrowse.Enabled = false;
- lblLogicalName.Enabled = false;
- txtLogicalName.Enabled = false;
- }
- }
-
-
-
-
-
-
- private void cboSqlDataSource_TextChanged(object sender, EventArgs e)
- {
- if (!string.IsNullOrEmpty(cboSqlDataSource.Text.Trim())
- && _connectionStringBuilder.IntegratedSecurity == true
- || !string.IsNullOrEmpty(txtUserName.Text.Trim())
- && _connectionStringBuilder.IntegratedSecurity == false)
- {
- gbConnectToADataBase.Enabled = true;
- btnOK.Enabled = true;
- }
- else
- {
- gbConnectToADataBase.Enabled = false;
- btnOK.Enabled = false;
- }
- }
-
-
-
-
-
-
- private void txtUserName_TextChanged(object sender, EventArgs e)
- {
- if (!string.IsNullOrEmpty(txtUserName.Text.Trim()))
- gbConnectToADataBase.Enabled = true;
- else
- gbConnectToADataBase.Enabled = false;
- }
-
-
-
-
-
-
- private void btnTestConnection_Click(object sender, EventArgs e)
- {
- if (!string.IsNullOrEmpty(cboSqlDataSource.Text.Trim()))
- {
-
- using (SqlConnection con = new SqlConnection(GetConnectionString()))
- {
- try
- {
-
- con.Open();
-
-
- MessageBox.Show(
- "测试连接成功。",
- this.Text,
- MessageBoxButtons.OK,
- MessageBoxIcon.Information);
- }
- catch (Exception ex)
- {
- MessageBox.Show(
- ex.Message,
- this.Text,
- MessageBoxButtons.OK,
- MessageBoxIcon.Error);
- }
- finally
- {
-
- con.Close();
- }
- }
- }
- else
- {
- MessageBox.Show(
- "无法测试此连接,因为没有指定服务器名称。",
- this.Text,
- MessageBoxButtons.OK,
- MessageBoxIcon.Error);
- }
- }
-
-
-
-
-
-
- private void btnOK_Click(object sender, EventArgs e)
- {
- try
- {
-
- string configFilePath = string.Format(@"{0}.config", Application.ExecutablePath);
- Configuration configuration = null;
- if (!File.Exists(configFilePath))
- {
- FileStream fs = null;
- try
- {
- fs = new FileStream(configFilePath, FileMode.CreateNew);
- fs.SetLength(0);
- }
- catch { }
- finally
- {
- fs.Close();
- }
- }
-
- configuration = ConfigurationManager.OpenExeConfiguration(configFilePath);
-
-
- bool appSettingsExist = false;
- foreach (KeyValueConfigurationElement element in configuration.AppSettings.Settings)
- {
-
- if (element.Key == "ConnectionType")
- {
-
- appSettingsExist = true;
- break;
- }
- }
-
- if (appSettingsExist)
-
- configuration.AppSettings.Settings["ConnectionType"].Value = "SQLSERVER";
- else
-
- configuration.AppSettings.Settings.Add("ConnectionType", "SQLSERVER");
-
-
- bool connectionStringExist = false;
- foreach (ConnectionStringSettings setting in configuration.ConnectionStrings.ConnectionStrings)
- {
-
- if (setting.Name == "SQLSERVER")
- {
-
- connectionStringExist = true;
- }
- }
-
- if (connectionStringExist)
- {
-
- configuration.ConnectionStrings.ConnectionStrings["SQLSERVER"].ConnectionString =
- GetConnectionString();
- configuration.ConnectionStrings.ConnectionStrings["SQLSERVER"].ProviderName =
- "System.Data.SqlClient";
- }
- else
- {
-
- configuration.ConnectionStrings.ConnectionStrings.Add(
- new ConnectionStringSettings(
- "SQLSERVER",
- GetConnectionString(),
- "System.Data.SqlClient"));
- }
-
-
- configuration.SaveAs(
- string.Format(@"{0}.config", Application.ExecutablePath.Replace(".EXE", ".exe")),
- ConfigurationSaveMode.Minimal);
-
-
- this.Close();
- }
- catch (Exception ex)
- {
- MessageBox.Show(
- string.Format("保存数据库连接配置时发生以下错误:/r/n/r/n{0}", ex.Message),
- this.Text,
- MessageBoxButtons.OK,
- MessageBoxIcon.Error);
- }
- }
-
-
-
-
-
-
- private void btnCancel_Click(object sender, EventArgs e)
- {
- this.Close();
- }
-
-
-
-
-
-
- private void btnBrowse_Click(object sender, EventArgs e)
- {
- OpenFileDialog ofDlg = new OpenFileDialog();
- ofDlg.Title = "选择 SQL Server 数据库文件";
- ofDlg.Filter = "Microsoft SQL Server 数据库(*.mdf)|*.mdf|所有文件(*.*)|*.*";
- ofDlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
- DialogResult result = ofDlg.ShowDialog(this);
- if (result == DialogResult.OK)
- txtDataBaseFilePath.Text = ofDlg.FileName;
- }
-
-
-
-
-
-
- private void btnGetConnectionString_Click(object sender, EventArgs e)
- {
- this.txtConnectionString.Text = GetConnectionString();
- }
-
- #endregion
- }
- }
设计器源码:
-
namespace CodingMouse.CMCSharpSDK.UI.Forms
- {
- partial class frmConnectionConfig
- {
-
-
-
- private System.ComponentModel.IContainer components = null;
-
-
-
-
-
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
-
- #region Windows 窗体设计器生成的代码
-
-
-
-
-
- private void InitializeComponent()
- {
- this.components = new System.ComponentModel.Container();
- this.cboSqlDataSource = new System.Windows.Forms.ComboBox();
- this.tcServerInfo = new System.Windows.Forms.TabControl();
- this.tpConnectionInfo = new System.Windows.Forms.TabPage();
- this.gbConnectToADataBase = new System.Windows.Forms.GroupBox();
- this.txtLogicalName = new System.Windows.Forms.TextBox();
- this.lblLogicalName = new System.Windows.Forms.Label();
- this.btnBrowse = new System.Windows.Forms.Button();
- this.cboDataBaseName = new System.Windows.Forms.ComboBox();
- this.txtDataBaseFilePath = new System.Windows.Forms.TextBox();
- this.rdoAttachADataBaseFile = new System.Windows.Forms.RadioButton();
- this.rdoSelectOrEnterADataBaseName = new System.Windows.Forms.RadioButton();
- this.gbLogOnToTheServer = new System.Windows.Forms.GroupBox();
- this.txtPassword = new System.Windows.Forms.TextBox();
- this.txtUserName = new System.Windows.Forms.TextBox();
- this.lblPassword = new System.Windows.Forms.Label();
- this.lblUserName = new System.Windows.Forms.Label();
- this.rdoValidateBySQLServer = new System.Windows.Forms.RadioButton();
- this.rdoValidateByWindows = new System.Windows.Forms.RadioButton();
- this.tpServerInfo = new System.Windows.Forms.TabPage();
- this.dgvServerInfo = new System.Windows.Forms.DataGridView();
- this.toolTip = new System.Windows.Forms.ToolTip(this.components);
- this.btnRefresh = new System.Windows.Forms.Button();
- this.lblServer = new System.Windows.Forms.Label();
- this.btnGetConnectionString = new System.Windows.Forms.Button();
- this.btnCancel = new System.Windows.Forms.Button();
- this.btnOK = new System.Windows.Forms.Button();
- this.btnTestConnection = new System.Windows.Forms.Button();
- this.lblSplit = new System.Windows.Forms.Label();
- this.txtConnectionString = new System.Windows.Forms.TextBox();
- this.tcServerInfo.SuspendLayout();
- this.tpConnectionInfo.SuspendLayout();
- this.gbConnectToADataBase.SuspendLayout();
- this.gbLogOnToTheServer.SuspendLayout();
- this.tpServerInfo.SuspendLayout();
- ((System.ComponentModel.ISupportInitialize)(this.dgvServerInfo)).BeginInit();
- this.SuspendLayout();
-
-
-
- this.cboSqlDataSource.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.cboSqlDataSource.FormattingEnabled = true;
- this.cboSqlDataSource.Location = new System.Drawing.Point(12, 24);
- this.cboSqlDataSource.Name = "cboSqlDataSource";
- this.cboSqlDataSource.Size = new System.Drawing.Size(269, 20);
- this.cboSqlDataSource.TabIndex = 1;
- this.cboSqlDataSource.Leave += new System.EventHandler(this.cboSqlDataSource_Leave);
- this.cboSqlDataSource.TextChanged += new System.EventHandler(this.cboSqlDataSource_TextChanged);
- this.cboSqlDataSource.DropDown += new System.EventHandler(this.cboSqlDataSource_DropDown);
-
-
-
- this.tcServerInfo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.tcServerInfo.Controls.Add(this.tpConnectionInfo);
- this.tcServerInfo.Controls.Add(this.tpServerInfo);
- this.tcServerInfo.HotTrack = true;
- this.tcServerInfo.Location = new System.Drawing.Point(12, 50);
- this.tcServerInfo.Name = "tcServerInfo";
- this.tcServerInfo.SelectedIndex = 0;
- this.tcServerInfo.ShowToolTips = true;
- this
|
请发表评论