打造自己的 C# WinForm 应用程序的 SQL Server 连接配置界面
在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
- {
- /// <summary>
- /// 数据库连接配置界面
- /// </summary>
- public partial class frmConnectionConfig : Form
- {
- #region Private Members
- /// <summary>
- /// SQL Server 连接字符串创建者对象
- /// </summary>
- SqlConnectionStringBuilder _connectionStringBuilder = null;
- /// <summary>
- /// 当前应用程序名称
- /// </summary>
- string _applicationName;
- #endregion
- #region Private Methods
- /// <summary>
- /// 获取 本地网络所有 SQL Server 实例(数据源)
- /// </summary>
- 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);
- // 创建 提供了一种枚举本地网络内的所有可用 SQL Server 实例的机制 的实例
- SqlDataSourceEnumerator sdsEnum = SqlDataSourceEnumerator.Instance;
- // 调用 检索包含有关所有可见 SQL Server 2000 或 SQL Server 2005 实例的信息的 DataTable 的方法
- DataTable serverDt = sdsEnum.GetDataSources();
- // 创建新列以拼接 ServerName 以及 InstanceName 列的内容(以此构建连接字符串的 Server / Data Source 项)
- DataColumn dcDataSource = new DataColumn("SqlDataSourceName", typeof(string));
- // 将新列添加到 DataTable
- serverDt.Columns.Add(dcDataSource);
- // 创建新列以用中文方式显示 IsClustered 列内容
- DataColumn dcIsClustered = new DataColumn("IsClusteredCHS", typeof(string));
- // 将新列添加到 DataTable
- serverDt.Columns.Add(dcIsClustered);
- // 遍历 DataTable 并给新列赋予拼接后的值
- 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)
- {
- // 创建窗体数据源封装类实例并封装 DataTable
- BindingSource source = new BindingSource();
- source.DataSource = serverDt;
- // 设置 ComboBox 数据源
- this.cboSqlDataSource.DataSource = source;
- this.cboSqlDataSource.DisplayMember = "SqlDataSourceName";
- this.cboSqlDataSource.ValueMember = "SqlDataSourceName";
- // 设置 DataGridView 数据源
- 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;
- }
- }
- /// <summary>
- /// 获取当前服务器上所有数据库名称
- /// </summary>
- 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);
- // 查询服务器上所有数据库的 SQL 查询命令
- string sqlTxt = "Select [Name] From [SysDatabases] Order By [Name]";
- // 保存结果的 DataTable
- DataTable dataBaseDt = new DataTable();
- // 创建连接对象
- using (SqlConnection con = new SqlConnection(GetConnectionString()))
- {
- // 执行查询
- try
- {
- // 创建适配器对象
- using (SqlDataAdapter adp = new SqlDataAdapter(sqlTxt, con))
- {
- // 将查询结果填充到 DataTable
- adp.Fill(dataBaseDt);
- }
- }
- catch { } // 不弹出异常消息
- }
- // 如果 DataTable 包含数据行
- 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;
- }
- }
- /// <summary>
- /// 获取连接字符串
- /// </summary>
- 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
- /// <summary>
- /// 无参构造
- /// </summary>
- public frmConnectionConfig(string applicationName)
- {
- // 构建设计器控件
- InitializeComponent();
- // 保存当前应用程序名称
- _applicationName = applicationName;
- // 创建连接字符串创建者
- _connectionStringBuilder = new SqlConnectionStringBuilder();
- _connectionStringBuilder.IntegratedSecurity = true;
- //_connectionStringBuilder.ApplicationName = _applicationName;
- //_connectionStringBuilder.AsynchronousProcessing = true;
- //_connectionStringBuilder.Encrypt = true;
- }
- #endregion
- #region Event Handlers
- /// <summary>
- /// 数据源 列表下拉事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void cboSqlDataSource_DropDown(object sender, EventArgs e)
- {
- // 如果 数据源 列表条目为空
- if (cboSqlDataSource.Items.Count == 0)
- {
- // 获取 本地网络所有 SQL Server 实例(数据源)
- GetSqlDataSource();
- }
- }
- /// <summary>
- /// 数据库 列表获得焦点事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void cboDataBaseName_Enter(object sender, EventArgs e)
- {
- // 获取当前服务器上所有数据库名称
- GetDataBaseName();
- }
- /// <summary>
- /// 选择选项卡页事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void tcServerInfo_Selecting(object sender, TabControlCancelEventArgs e)
- {
- // 如果 数据源 列表条目为空
- if (cboSqlDataSource.Items.Count == 0 && e.TabPage == tpServerInfo)
- {
- // 获取 本地网络所有 SQL Server 实例(数据源)
- GetSqlDataSource();
- }
- }
- /// <summary>
- /// [刷新]按钮点击事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void btnRefresh_Click(object sender, EventArgs e)
- {
- // 获取 本地网络所有 SQL Server 实例(数据源)
- GetSqlDataSource();
- }
- /// <summary>
- /// [使用 SQL Server 身份验证]单选按钮 Checked 属性更改事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- 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;
- }
- }
- /// <summary>
- /// [附加一个数据库文件]单选按钮 Checked 属性更改事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- 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;
- }
- }
- /// <summary>
- /// 数据源 列表 Text 值更改事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- 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;
- }
- }
- /// <summary>
- /// [用户名]文本框文本更改事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void txtUserName_TextChanged(object sender, EventArgs e)
- {
- if (!string.IsNullOrEmpty(txtUserName.Text.Trim()))
- gbConnectToADataBase.Enabled = true;
- else
- gbConnectToADataBase.Enabled = false;
- }
- /// <summary>
- /// [测试连接]按钮点击事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- 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);
- }
- }
- /// <summary>
- /// [确定]按钮点击事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- 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);
- // configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
- // 遍历检验 ConnectionType 项是否存在
- 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");
- // 遍历检验 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);
- }
- }
- /// <summary>
- /// [取消]按钮点击事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void btnCancel_Click(object sender, EventArgs e)
- {
- this.Close();
- }
- /// <summary>
- /// [浏览]按钮点击事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- 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;
- }
- /// <summary>
- /// [获取连接字符串]按钮点击事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void btnGetConnectionString_Click(object sender, EventArgs e)
- {
- this.txtConnectionString.Text = GetConnectionString();
- }
- #endregion
- }
- }
设计器源码:
- namespace CodingMouse.CMCSharpSDK.UI.Forms
- {
- partial class frmConnectionConfig
- {
- /// <summary>
- /// 必需的设计器变量。
- /// </summary>
- private System.ComponentModel.IContainer components = null;
- /// <summary>
- /// 清理所有正在使用的资源。
- /// </summary>
- /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
- #region Windows 窗体设计器生成的代码
- /// <summary>
- /// 设计器支持所需的方法 - 不要
- /// 使用代码编辑器修改此方法的内容。
- /// </summary>
- 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();
- //
- // cboSqlDataSource
- //
- 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);
- //
- // tcServerInfo
- //
- 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.tcServerInfo.Size = new System.Drawing.Size(350, 304);
- this.tcServerInfo.TabIndex = 3;
- this.tcServerInfo.Selecting += new System.Windows.Forms.TabControlCancelEventHandler(this.tcServerInfo_Selecting);
- //
- // tpConnectionInfo
- //
- this.tpConnectionInfo.Controls.Add(this.gbConnectToADataBase);
- this.tpConnectionInfo.Controls.Add(this.gbLogOnToTheServer);
- this.tpConnectionInfo.Location = new System.Drawing.Point(4, 21);
- this.tpConnectionInfo.Name = "tpConnectionInfo";
- this.tpConnectionInfo.Padding = new System.Windows.Forms.Padding(3);
- this.tpConnectionInfo.Size = new System.Drawing.Size(342, 279);
- this.tpConnectionInfo.TabIndex = 0;
- this.tpConnectionInfo.Text = "数据库连接信息";
- this.tpConnectionInfo.UseVisualStyleBackColor = true;
- //
- // gbConnectToADataBase
- //
- this.gbConnectToADataBase.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.gbConnectToADataBase.Controls.Add(this.txtLogicalName);
- this.gbConnectToADataBase.Controls.Add(this.lblLogicalName);
- this.gbConnectToADataBase.Controls.Add(this.btnBrowse);
- this.gbConnectToADataBase.Controls.Add(this.cboDataBaseName);
- this.gbConnectToADataBase.Controls.Add(this.txtDataBaseFilePath);
- this.gbConnectToADataBase.Controls.Add(this.rdoAttachADataBaseFile);
- this.gbConnectToADataBase.Controls.Add(this.rdoSelectOrEnterADataBaseName);
- this.gbConnectToADataBase.Enabled = false;
- this.gbConnectToADataBase.Location = new System.Drawing.Point(6, 129);
- this.gbConnectToADataBase.Name = "gbConnectToADataBase";
- this.gbConnectToADataBase.Size = new System.Drawing.Size(330, 144);
- this.gbConnectToADataBase.TabIndex = 1;
- this.gbConnectToADataBase.TabStop = false;
- this.gbConnectToADataBase.Text = "连接到一个数据库";
- //
- // txtLogicalName
- //
- this.txtLogicalName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.txtLogicalName.Enabled = false;
- this.txtLogicalName.Location = new System.Drawing.Point(6, 117);
- this.txtLogicalName.Name = "txtLogicalName";
- this.txtLogicalName.Size = new System.Drawing.Size(318, 21);
- this.txtLogicalName.TabIndex = 6;
- //
- // lblLogicalName
- //
- this.lblLogicalName.AutoSize = true;
- this.lblLogicalName.Enabled = false;
- this.lblLogicalName.Location = new System.Drawing.Point(4, 102);
- this.lblLogicalName.Name = "lblLogicalName";
- this.lblLogicalName.Size = new System.Drawing.Size(65, 12);
- this.lblLogicalName.TabIndex = 5;
- this.lblLogicalName.Text = "逻辑名(&L):";
- //
- // btnBrowse
- //
- this.btnBrowse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
- this.btnBrowse.Enabled = false;
- this.btnBrowse.Location = new System.Drawing.Point(244, 78);
- this.btnBrowse.Name = "btnBrowse";
- this.btnBrowse.Size = new System.Drawing.Size(80, 21);
- this.btnBrowse.TabIndex = 4;
- this.btnBrowse.Text = "浏览(&B)...";
- this.btnBrowse.UseVisualStyleBackColor = true;
- this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);
- //
- // cboDataBaseName
- //
- this.cboDataBaseName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.cboDataBaseName.FormattingEnabled = true;
- this.cboDataBaseName.Location = new System.Drawing.Point(6, 36);
- this.cboDataBaseName.Name = "cboDataBaseName";
- this.cboDataBaseName.Size = new System.Drawing.Size(318, 20);
- this.cboDataBaseName.TabIndex = 1;
- this.cboDataBaseName.Enter += new System.EventHandler(this.cboDataBaseName_Enter);
- //
- // txtDataBaseFilePath
- //
- this.txtDataBaseFilePath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.txtDataBaseFilePath.Enabled = false;
- this.txtDataBaseFilePath.Location = new System.Drawing.Point(6, 78);
- this.txtDataBaseFilePath.Name = "txtDataBaseFilePath";
- this.txtDataBaseFilePath.Size = new System.Drawing.Size(232, 21);
- this.txtDataBaseFilePath.TabIndex = 3;
- //
- // rdoAttachADataBaseFile
- //
- this.rdoAttachADataBaseFile.AutoSize = true;
- this.rdoAttachADataBaseFile.Location = new System.Drawing.Point(6, 62);
- this.rdoAttachADataBaseFile.Name = "rdoAttachADataBaseFile";
- this.rdoAttachADataBaseFile.Size = new System.Drawing.Size(155, 16);
- this.rdoAttachADataBaseFile.TabIndex = 2;
- this.rdoAttachADataBaseFile.Text = "附加一个数据库文件(&H):";
- this.rdoAttachADataBaseFile.UseVisualStyleBackColor = true;
- this.rdoAttachADataBaseFile.CheckedChanged += new System.EventHandler(this.rdoAttachADataBaseFile_CheckedChanged);
- //
- // rdoSelectOrEnterADataBaseName
- //
- this.rdoSelectOrEnterADataBaseName.AutoSize = true;
- this.rdoSelectOrEnterADataBaseName.Checked = true;
- this.rdoSelectOrEnterADataBaseName.Location = new System.Drawing.Point(6, 20);
- this.rdoSelectOrEnterADataBaseName.Name = "rdoSelectOrEnterADataBaseName";
- this.rdoSelectOrEnterADataBaseName.Size = new System.Drawing.Size(179, 16);
- this.rdoSelectOrEnterADataBaseName.TabIndex = 0;
- this.rdoSelectOrEnterADataBaseName.TabStop = true;
- this.rdoSelectOrEnterADataBaseName.Text = "选择或输入一个数据库名(&D):";
- this.rdoSelectOrEnterADataBaseName.UseVisualStyleBackColor = true;
- //
- // gbLogOnToTheServer
- //
- this.gbLogOnToTheServer.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.gbLogOnToTheServer.Controls.Add(this.txtPassword);
- this.gbLogOnToTheServer.Controls.Add(this.txtUserName);
- this.gbLogOnToTheServer.Controls.Add(this.lblPassword);
- this.gbLogOnToTheServer.Controls.Add(this.lblUserName);
- this.gbLogOnToTheServer.Controls.Add(this.rdoValidateBySQLServer);
- this.gbLogOnToTheServer.Controls.Add(this.rdoValidateByWindows);
- this.gbLogOnToTheServer.Location = new System.Drawing.Point(6, 6);
- this.gbLogOnToTheServer.Name = "gbLogOnToTheServer";
- this.gbLogOnToTheServer.Size = new System.Drawing.Size(330, 117);
- this.gbLogOnToTheServer.TabIndex = 0;
- this.gbLogOnToTheServer.TabStop = false;
- this.gbLogOnToTheServer.Text = "登录到服务器";
- //
- // txtPassword
- //
- this.txtPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.txtPassword.Enabled = false;
- this.txtPassword.Location = new System.Drawing.Point(93, 88);
- this.txtPassword.Name = "txtPassword";
- this.txtPassword.PasswordChar = '*';
- this.txtPassword.Size = new System.Drawing.Size(231, 21);
- this.txtPassword.TabIndex = 5;
- this.txtPassword.TextChanged += new System.EventHandler(this.txtPassword_TextChanged);
- //
- // txtUserName
- //
- this.txtUserName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.txtUserName.Enabled = false;
- this.txtUserName.Location = new System.Drawing.Point(93, 61);
- this.txtUserName.Name = "txtUserName";
- this.txtUserName.Size = new System.Drawing.Size(231, 21);
- this.txtUserName.TabIndex = 3;
- this.txtUserName.TextChanged += new System.EventHandler(this.txtUserName_TextChanged);
- //
- // lblPassword
- //
- this.lblPassword.AutoSize = true;
- this.lblPassword.Enabled = false;
- this.lblPassword.Location = new System.Drawing.Point(22, 91);
- this.lblPassword.Name = "lblPassword";
- this.lblPassword.Size = new System.Drawing.Size(65, 12);
- this.lblPassword.TabIndex = 4;
- this.lblPassword.Text = "密 码(&P):";
- //
- // lblUserName
- //
- this.lblUserName.AutoSize = true;
- this.lblUserName.Enabled = false;
- this.lblUserName.Location = new System.Drawing.Point(22, 64);
- this.lblUserName.Name = "lblUserName";
- this.lblUserName.Size = new System.Drawing.Size(65, 12);
- this.lblUserName.TabIndex = 2;
- this.lblUserName.Text = "用户名(&U):";
- //
- // rdoValidateBySQLServer
- //
- this.rdoValidateBySQLServer.AutoSize = true;
- this.rdoValidateBySQLServer.Location = new System.Drawing.Point(6, 42);
- this.rdoValidateBySQLServer.Name = "rdoValidateBySQLServer";
- this.rdoValidateBySQLServer.Size = new System.Drawing.Size(185, 16);
- this.rdoValidateBySQLServer.TabIndex = 1;
- this.rdoValidateBySQLServer.Text = "使用 SQL Server 身份验证(&Q)";
- this.rdoValidateBySQLServer.UseVisualStyleBackColor = true;
- this.rdoValidateBySQLServer.CheckedChanged += new System.EventHandler(this.rdoValidateBySQLServer_CheckedChanged);
- //
- // rdoValidateByWindows
- //
- this.rdoValidateByWindows.AutoSize = true;
- this.rdoValidateByWindows.Checked = true;
- this.rdoValidateByWindows.Location = new System.Drawing.Point(6, 20);
- this.rdoValidateByWindows.Name = "rdoValidateByWindows";
- this.rdoValidateByWindows.Size = new System.Drawing.Size(167, 16);
- this.rdoValidateByWindows.TabIndex = 0;
- this.rdoValidateByWindows.TabStop = true;
- this.rdoValidateByWindows.Text = "使用 Windows 身份验证(&W)";
- this.rdoValidateByWindows.UseVisualStyleBackColor = true;
- //
- // tpServerInfo
- //
- this.tpServerInfo.Controls.Add(this.dgvServerInfo);
- this.tpServerInfo.Location = new System.Drawing.Point(4, 21);
- this.tpServerInfo.Name = "tpServerInfo";
- this.tpServerInfo.Padding = new System.Windows.Forms.Padding(3);
- this.tpServerInfo.Size = new System.Drawing.Size(342, 279);
- this.tpServerInfo.TabIndex = 1;
- this.tpServerInfo.Text = "服务器详细信息";
- this.tpServerInfo.UseVisualStyleBackColor = true;
- //
- // dgvServerInfo
- //
- this.dgvServerInfo.AllowUserToAddRows = false;
- this.dgvServerInfo.AllowUserToDeleteRows = false;
- this.dgvServerInfo.AllowUserToResizeRows = false;
- this.dgvServerInfo.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
- this.dgvServerInfo.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
- this.dgvServerInfo.Dock = System.Windows.Forms.DockStyle.Fill;
- this.dgvServerInfo.Location = new System.Drawing.Point(3, 3);
- this.dgvServerInfo.MultiSelect = false;
- this.dgvServerInfo.Name = "dgvServerInfo";
- this.dgvServerInfo.ReadOnly = true;
- this.dgvServerInfo.RowHeadersVisible = false;
- this.dgvServerInfo.RowTemplate.Height = 23;
- this.dgvServerInfo.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
- this.dgvServerInfo.Size = new System.Drawing.Size(336, 273);
- this.dgvServerInfo.TabIndex = 0;
- //
- // toolTip
- //
- this.toolTip.ShowAlways = true;
- //
- // btnRefresh
- //
- this.btnRefresh.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
- this.btnRefresh.Location = new System.Drawing.Point(287, 23);
- this.btnRefresh.Name = "btnRefresh";
- this.btnRefresh.Size = new System.Drawing.Size(75, 21);
- this.btnRefresh.TabIndex = 2;
- this.btnRefresh.Text = "刷新(&R)";
- this.btnRefresh.UseVisualStyleBackColor = true;
- this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
- //
- // lblServer
- //
- this.lblServer.AutoSize = true;
- this.lblServer.Location = new System.Drawing.Point(10, 9);
- this.lblServer.Name = "lblServer";
- this.lblServer.Size = new System.Drawing.Size(77, 12);
- this.lblServer.TabIndex = 0;
- this.lblServer.Text = "服务器名(&E):";
- //
- // btnGetConnectionString
- //
- this.btnGetConnectionString.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
- this.btnGetConnectionString.Enabled = false;
- this.btnGetConnectionString.Location = new System.Drawing.Point(242, 360);
- this.btnGetConnectionString.Name = "btnGetConnectionString";
- this.btnGetConnectionString.Size = new System.Drawing.Size(120, 21);
- this.btnGetConnectionString.TabIndex = 5;
- this.btnGetConnectionString.Text = "获取连接字符串(&G)";
- this.btnGetConnectionString.UseVisualStyleBackColor = true;
- this.btnGetConnectionString.Click += new System.EventHandler(this.btnGetConnectionString_Click);
- //
- // btnCancel
- //
- this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
- this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
- this.btnCancel.Location = new System.Drawing.Point(287, 395);
- this.btnCancel.Name = "btnCancel";
- this.btnCancel.Size = new System.Drawing.Size(75, 21);
- this.btnCancel.TabIndex = 9;
- this.btnCancel.Text = "取消";
- this.btnCancel.UseVisualStyleBackColor = true;
- this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
- //
- // btnOK
- //
- this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
- this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
- this.btnOK.Enabled = false;
- this.btnOK.Location = new System.Drawing.Point(206, 395);
- this.btnOK.Name = "btnOK";
- this.btnOK.Size = new System.Drawing.Size(75, 21);
- this.btnOK.TabIndex = 8;
- this.btnOK.Text = "确定";
- this.btnOK.UseVisualStyleBackColor = true;
- this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
- //
- // btnTestConnection
- //
- this.btnTestConnection.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
- this.btnTestConnection.Location = new System.Drawing.Point(12, 395);
- this.btnTestConnection.Name = "btnTestConnection";
- this.btnTestConnection.Size = new System.Drawing.Size(100, 21);
- this.btnTestConnection.TabIndex = 7;
- this.btnTestConnection.Text = "测试连接(&T)";
- this.btnTestConnection.UseVisualStyleBackColor = true;
- this.btnTestConnection.Click += new System.EventHandler(this.btnTestConnection_Click);
- //
- // lblSplit
- //
- this.lblSplit.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.lblSplit.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
- this.lblSplit.Location = new System.Drawing.Point(12, 387);
- this.lblSplit.Name = "lblSplit";
- this.lblSplit.Size = new System.Drawing.Size(350, 2);
- this.lblSplit.TabIndex = 6;
- //
- // txtConnectionString
- //
- this.txtConnectionString.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.txtConnectionString.Location = new System.Drawing.Point(12, 360);
- this.txtConnectionString.Name = "txtConnectionString";
- this.txtConnectionString.ReadOnly = true;
- this.txtConnectionString.Size = new System.Drawing.Size(224, 21);
- this.txtConnectionString.TabIndex = 4;
- //
- // frmConnectionConfig
- //
- this.AcceptButton = this.btnOK;
- this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.CancelButton = this.btnCancel;
- this.ClientSize = new System.Drawing.Size(374, 428);
- this.Controls.Add(this.txtConnectionString);
- this.Controls.Add(this.lblSplit);
- this.Controls.Add(this.btnTestConnection);
- this.Controls.Add(this.btnOK);
- this.Controls.Add(this.btnCancel);
- this.Controls.Add(this.btnGetConnectionString);
- this.Controls.Add(this.btnRefresh);
- this.Controls.Add(this.lblServer);
- this.Controls.Add(this.tcServerInfo);
- this.Controls.Add(this.cboSqlDataSource);
- this.HelpButton = true;
- this.MaximizeBox = false;
- this.MinimizeBox = false;
- this.MinimumSize = new System.Drawing.Size(382, 455);
- this.Name = "frmConnectionConfig";
- this.ShowIcon = false;
- this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
- this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
- this.Text = "数据库连接配置";
- this.tcServerInfo.ResumeLayout(false);
- this.tpConnectionInfo.ResumeLayout(false);
- this.gbConnectToADataBase.ResumeLayout(false);
- this.gbConnectToADataBase.PerformLayout();
- this.gbLogOnToTheServer.ResumeLayout(false);
- this.gbLogOnToTheServer.PerformLayout();
- this.tpServerInfo.ResumeLayout(false);
- ((System.ComponentModel.ISupportInitialize)(this.dgvServerInfo)).EndInit();
- this.ResumeLayout(false);
- this.PerformLayout();
- }
- #endregion
- private System.Windows.Forms.ComboBox cboSqlDataSource;
- private System.Windows.Forms.TabControl tcServerInfo;
- private System.Windows.Forms.TabPage tpConnectionInfo;
- private System.Windows.Forms.TabPage tpServerInfo;
- private System.Windows.Forms.DataGridView dgvServerInfo;
- private System.Windows.Forms.ToolTip toolTip;
- private System.Windows.Forms.Label lblServer;
- private System.Windows.Forms.Button btnRefresh;
- private System.Windows.Forms.GroupBox gbLogOnToTheServer;
- private System.Windows.Forms.TextBox txtPassword;
- private System.Windows.Forms.TextBox txtUserName;
- private System.Windows.Forms.Label lblPassword;
- private System.Windows.Forms.Label lblUserName;
- private System.Windows.Forms.RadioButton rdoValidateBySQLServer;
- private System.Windows.Forms.RadioButton rdoValidateByWindows;
- private System.Windows.Forms.GroupBox gbConnectToADataBase;
- private System.Windows.Forms.RadioButton rdoAttachADataBaseFile;
- private System.Windows.Forms.RadioButton rdoSelectOrEnterADataBaseName;
- private System.Windows.Forms.Button btnGetConnectionString;
- private System.Windows.Forms.Button btnCancel;
- private System.Windows.Forms.Button btnOK;
- private System.Windows.Forms.Button btnTestConnection;
- private System.Windows.Forms.ComboBox cboDataBaseName;
- private System.Windows.Forms.TextBox txtDataBaseFilePath;
- private System.Windows.Forms.Button btnBrowse;
- private System.Windows.Forms.TextBox txtLogicalName;
- private System.Windows.Forms.Label lblLogicalName;
- private System.Windows.Forms.Label lblSplit;
- private System.Windows.Forms.TextBox txtConnectionString;
- }
- }
- 上面是自己写的界面,也可以自己去调用系统的界面
一、添加引用
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\Microsoft.Data.ConnectionUI.Dialog.dll
二、引入名称空间
- C# code
-
using Microsoft.Data.ConnectionUI;
三、代码
- C# code
-
DataConnectionDialog dlg =new DataConnectionDialog(); dlg.DataSources.Add(DataSource.SqlDataSource); dlg.SelectedDataProvider = DataProvider.SqlDataProvider; DataConnectionDialog.Show(dlg, this);
比如说放在一个按钮的Click事件里
- C# code
-
privatevoid button1_Click(object sender, EventArgs e) { DataConnectionDialog dlg =new DataConnectionDialog(); dlg.DataSources.Add(DataSource.SqlDataSource); dlg.SelectedDataProvider = DataProvider.SqlDataProvider; DataConnectionDialog.Show(dlg, this); }
四、运行
界面出来了,是不是相当的专业!
DataConnectionDialog 还有很多属性,配置这些属性可以改变窗口外观,满足不同需求。