界面层UI实现过程(桌面版)
来到UI层编写了,由于三层的架构体系,所以UI层只需要和BLL层沟通就好。(BLL层和DAL层交互,DAL层与底层数据库交互),关于DAL层的编码和BLL层编码实现过程,请参考前面的文章。
先来看看最终效果:(这里只能抛砖引玉,小虫我在界面美观上没有仔细用功,这一点大家千万不能也如此不重视,好的编程人员在UI上也要起码的让客户看上去舒服,这一点我做得很不够。所以后面的界面效果望大家能见谅!)
数据库已经切换了(目前只有Access数据库和SqlServer数据库)
实际上就是实现了用户的增删改和按部门查询的功能,加上了一个鸡肋(数据库切换)(对app.config的配置更新还是有了解的必要)。
<实际上是不存在此需求,具体的一个客户端只选择一种固定数据库的。这里仅仅为了测试方便,硬加上的。>
(其他的比如对部门的增删改功能和组合查询等就省略了。)
接下来,看看实现的过程:(首先界面需要的控件如图)
这里说明一下:控件的命名,后续代码看起来明白些。
切换后台数据库:
1 <?xml version="1.0" encoding="utf-8" ?>
2 <configuration>
3 <appSettings>
4 <add key="ProviderType" value="Sql"/>
5 </appSettings>
6 <connectionStrings>
7 <add name="DBConnString"
8 connectionString="Data Source=.\sqlexpress;Initial Catalog=testdb;Integrated Security=True"/>
9 </connectionStrings>
10 </configuration>
11 <!--
12 <?xml version="1.0" encoding="utf-8" ?>
13 <configuration>z
14 <appSettings>
15 <add key="ProviderType" value="Access"/>
16 </appSettings>
17 <connectionStrings>
18 <add name="DBConnString"
19 connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\netStudy\抽象工厂模式\testdb.mdb"/>
20 </connectionStrings>
21 </configuration>
22 -->
其实就只需要更改:<appSettings>节点的key[ProviderType]的Value值、<connectionStrings>节点的name[DBConnString]的connectionString。
操控XML文档可以用System.Xml命名空间的类。这里提供另外一种方法(读写文件替换)
首先建立一个模板AppTemplate.xml,内容如下:
程序运行的时候读取该文件,将%ProviderType%和%DBConnString%替换成合适的内容,然后将该内容保存到App.config中就可以了。
见上图:
1.读取模板 2.替换特别字符串 3.写入到app.config
4.ConfigurationManager.RefreshSection一定不要忘记,它会强制从磁盘重新读取。否则读取的是缓存内容<要重启程序才能生效>。
注意:程序如果处在调试状态,你要看到效果:对应的config文件是vshost.exe.config,但程序独立运行不调试的时候,代码要换为:.config。
总之要留心这个问题。(调试和独立运行对应的config文件不同。)
正式基于这点,又上网查询了下,有牛人给出了更好的解决方案<见下图方法:ChangeConfiguration()>,
一来会自动解决调试和独立运行的config文件,二来不要模板文件(读写都不需要)。 实现的直接替换。
在运行测试的过程中,发生了一些异常,主要是Access数据库sql语句访问的一些特殊地方。
对比一下:SqlUserProvider.cs中对应的代码:
参考代码:
Form1.cs代码:
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using 抽象工厂模式.BLL;
9 using System.Configuration;
10
11 namespace 抽象工厂模式
12 {
13 public partial class Form1 : Form
14 {
15 public Form1()
16 {
17 InitializeComponent();
18 }
19
20 private void Form1_Load(object sender, EventArgs e)
21 {
22 sourceUsers.DataSource = UserObj.GetUsers();//获得所有的用户
23 cboDepts.ValueMember = "Id"; //comboBox显示的内容实际关联的值(一般是主键值,通过它后台编码)
24 cboDepts.DisplayMember = "Name"; //comboBox显示的内容
25 var depts = DepartmentObj.GetDepartments();//获得所有的部门<用depts遍历来获取数据库获取的集合>
26 cboDepts.DataSource = depts;//depts集合中的每一个元素类型是 DepartmentObj---对应于ComboBox的每一项
27
28 cboDeptAdd.ValueMember = "Id";
29 cboDeptAdd.DisplayMember = "Name";
30 //不推荐这么写:cboDeptAdd.DataSource=DepartmentObj.GetDepartments();因为避免再次后台访问
31 var deptArrays = depts.ToArray(); //将集合depts复制到新数组deptArray中
32 cboDeptAdd.DataSource = deptArrays;
33
34
35 cboAllDepts.ValueMember = "Id";
36 cboAllDepts.DisplayMember = "Name";
37 depts.Insert(0,new DepartmentObj(0,"所有部门",""));//上1:为了下拉能显示<所有部门>,注意这里
38 cboAllDepts.DataSource = depts.ToArray(); //下2:提示<上1和下2这两行代码不能交换>,因为组合框一旦绑定后,不允许再手动更改Items的元素
39 }
40
41 private void btnEdit_Click(object sender, EventArgs e)
42 {
43 if (txtName.Text.Trim() == "")//验证<姓名不能为空>
44 {
45 errorMsg.SetError(txtName, txtName.Tag.ToString());//设置txtName控件显示错误图标(错误字符串)
46 return;
47 }
48 else
49 errorMsg.SetError(txtName, "");//隐藏错误图标
50 var obj = this.sourceUsers.Current as UserObj; //获得当前的用户域对象 UserObj
51 if (obj == null) return;
52 //更新用户的方法
53 UserObj.UpdateUserObj(obj.Id, obj.Name,
54 (cboDepts.SelectedItem as DepartmentObj).Id //找到选择的部门对象的主键
55 );
56 }
57
58 private void btnInsert_Click(object sender, EventArgs e)
59 {
60 if (txtNameAdd.Text.Trim() == "")//验证<姓名不能为空>
61 {
62 errorMsg.SetError(txtNameAdd, txtNameAdd.Tag.ToString());//设置txtNameAdd控件显示错误图标(错误字符串)
63 return;
64 }
65 else
66 errorMsg.SetError(txtNameAdd, "");//隐藏错误图标
67 UserObj.InsertUserObj((int)cboDeptAdd.SelectedValue, txtNameAdd.Text);//添加用户记录的方法
68 msgHelp.SetError(btnInsert, "添加成功");//显示成功图标
69 txtNameAdd.Text = ""; //清空txtNameAdd的文本
70
71 UsersRefresh();//刷新获得最新数据
72
73 }
74
75
76 private void txtNameAdd_TextChanged(object sender, EventArgs e)
77 {
78 if (msgHelp.GetError(btnInsert) != "") msgHelp.SetError(btnInsert, "");
79 }
80
81
82 private void cboAllDepts_SelectedIndexChanged(object sender, EventArgs e)
83 {
84 if (cboAllDepts.SelectedItem != null) UsersRefresh();
85 }
86
87 /// <summary>
88 /// 根据所选择部门获得对应的用户列表
89 /// </summary>
90 private void UsersRefresh()
91 {
92 int deptId = (int)cboAllDepts.SelectedValue;
93 if (deptId == 0)
94 sourceUsers.DataSource = UserObj.GetUsers(); //显示所有用户
95 else
96 sourceUsers.DataSource = UserObj.GetUsers(deptId);//显示对应部门的用户
97 }
98
99 private void tsbtnDelete_Click(object sender, EventArgs e)
100 {
101 if (MessageBox.Show("是否删除该记录?", "确认", MessageBoxButtons.OKCancel) ==
102 System.Windows.Forms.DialogResult.OK)
103 {
104 var obj = sourceUsers.Current as UserObj;
105 UserObj.DeleteUserObj(obj.Id); //删除该用户
106 UsersRefresh(); //刷新数据
107 }
108 }
109
110 private void tsbtnRefresh_Click(object sender, EventArgs e)
111 {
112 UsersRefresh();
113 }
114
115 private void tsbtnChangeDb_Click(object sender, EventArgs e)
116 {
117 try
118 {
119 Helper.ChangeDbServer();//切换数据库(Access与SqlServer切换)
120 UserObj.ChangeDB();
121 UsersRefresh();
122 }
123 catch (Exception ex)
124 {
125
126 MessageBox.Show(ex.Message);
127 }
128 }
129
130 private void toolStripButton1_Click(object sender, EventArgs e)
131 {
132 Helper.ChangeConfiguration(); //切换数据库(Access与SqlServer切换)
133 UserObj.ChangeDB();
134 UsersRefresh();
135 }
136
137
138 private void dgvUsers_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
139 {
140 string tipError = "";
141 var user= dgvUsers.Rows[e.RowIndex].DataBoundItem as UserObj;//获得当前选中的用户对象
142 if (user != null && string.IsNullOrEmpty(user.Name))
143 {
144 tipError = "姓名不能为空!";
145 dgvUsers.Rows[e.RowIndex].Cells["colName"].ErrorText = tipError;
146 }
147 errorMsg.SetError(txtName, tipError);
148 }
149
150
151 }
152 }
Form1.Designer.cs代码如下:
namespace 抽象工厂模式 { partial class Form1 { /// <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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.label1 = new System.Windows.Forms.Label(); this.txtName = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.cboDepts = new System.Windows.Forms.ComboBox(); this.btnEdit = new System.Windows.Forms.Button(); this.errorMsg = new System.Windows.Forms.ErrorProvider(this.components); this.cboDeptAdd = new System.Windows.Forms.ComboBox(); this.txtNameAdd = new System.Windows.Forms.TextBox(); this.btnInsert = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.msgHelp = new System.Windows.Forms.ErrorProvider(this.components); this.panel1 = new System.Windows.Forms.Panel(); this.panel3 = new System.Windows.Forms.Panel(); this.dgvUsers = new System.Windows.Forms.DataGridView(); this.bindingNavigator1 = new System.Windows.Forms.BindingNavigator(this.components); this.bindingNavigatorCountItem = new System.Windows.Forms.ToolStripLabel(); this.bindingNavigatorMoveFirstItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMovePreviousItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorSeparator = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorPositionItem = new System.Windows.Forms.ToolStripTextBox(); this.bindingNavigatorSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorMoveNextItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMoveLastItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.tsbtnDelete = new System.Windows.Forms.ToolStripButton(); this.tsbtnRefresh = new System.Windows.Forms.ToolStripButton(); this.tsbtnChangeDb = new System.Windows.Forms.ToolStripButton(); this.panel2 = new System.Windows.Forms.Panel(); this.cboAllDepts = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.colId = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.deptTitleDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.sourceUsers = new System.Windows.Forms.BindingSource(this.components); ((System.ComponentModel.ISupportInitialize)(this.errorMsg)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.msgHelp)).BeginInit(); this.panel1.SuspendLayout(); this.panel3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgvUsers)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingNavigator1)).BeginInit(); this.bindingNavigator1.SuspendLayout(); this.panel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.sourceUsers)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(75, 402); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(41, 12); this.label1.TabIndex = 2; this.label1.Text = "姓名:"; // // txtName // this.txtName.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.sourceUsers, "Name", true)); this.errorMsg.SetIconPadding(this.txtName, 5); this.txtName.Location = new System.Drawing.Point(113, 399); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(100, 21); this.txtName.TabIndex = 3; this.txtName.Tag = "姓名不能为空!"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(75, 429); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(41, 12); this.label2.TabIndex = 4; this.label2.Text = "部门:"; // // cboDepts // this.cboDepts.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.sourceUsers, "DeptTitle", true)); this.cboDepts.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboDepts.FormattingEnabled = true; this.errorMsg.SetIconPadding(this.cboDepts, 5); this.cboDepts.Location = new System.Drawing.Point(113, 426); this.cboDepts.Name = "cboDepts"; this.cboDepts.Size = new System.Drawing.Size(100, 20); this.cboDepts.TabIndex = 6; this.cboDepts.Tag = "部门不能为空!"; // // btnEdit // this.btnEdit.Location = new System.Drawing.Point(152, 461); this.btnEdit.Name = "btnEdit"; this.btnEdit.Size = new System.Drawing.Size(61, 23); this.btnEdit.TabIndex = 7; this.btnEdit.Text = "修改"; this.btnEdit.UseVisualStyleBackColor = true; this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click); // // errorMsg // this.errorMsg.ContainerControl = this; // // cboDeptAdd // this.cboDeptAdd.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboDeptAdd.FormattingEnabled = true; this.errorMsg.SetIconPadding(this.cboDeptAdd, 5); this.cboDeptAdd.Location = new System.Drawing.Point(304, 426); this.cboDeptAdd.Name = "cboDeptAdd"; this.cboDeptAdd.Size = new System.Drawing.Size(100, 20); this.cboDeptAdd.TabIndex = 11; this.cboDeptAdd.Tag = "部门不能为空!"; // // txtNameAdd // this.errorMsg.SetIconPadding(this.txtNameAdd, 5); this.txtNameAdd.Location = new System.Drawing.Point(304, 399); this.txtNameAdd.Name = "txtNameAdd"; this.txtNameAdd.Size = new System.Drawing.Size(100, 21); this.txtNameAdd.TabIndex = 9; this.txtNameAdd.Tag = "姓名不能为空!"; this.txtNameAdd.TextChanged += new System.EventHandler(this.txtNameAdd_TextChanged); // // btnInsert // this.errorMsg.SetIconPadding(this.btnInsert, 5); this.btnInsert.Location = new System.Drawing.Point(339, 461); this.btnInsert.Name = "btnInsert"; this.btnInsert.Size = new System.Drawing.Size(65, 26); this.btnInsert.TabIndex = 12; this.btnInsert.Text = "添加"; this.btnInsert.UseVisualStyleBackColor = true; this.btnInsert.Click += new System.EventHandler(this.btnInsert_Click); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(266, 429); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(41, 12); this.label3.TabIndex = 10; this.label3.Text = "部门:"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(266, 402); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(41, 12); this.label4.TabIndex = 8; this.label4.Text = "姓名:"; // // msgHelp // this.msgHelp.ContainerControl = this; this.msgHelp.Icon = ((System.Drawing.Icon)(resources.GetObject("msgHelp.Icon"))); // // panel1 // this.panel1.Controls.Add(this.panel3); this.panel1.Controls.Add(this.panel2); this.panel1.Dock = System.Windows.Forms.DockStyle.Top; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(613, 368); this.panel1.TabIndex = 13; // // panel3 // this.panel3.Controls.Add(this.dgvUsers); this.panel3.Controls.Add(this.bindingNavigator1); this.panel3.Dock = System.Windows.Forms.DockStyle.Fill; this.panel3.Location = new System.Drawing.Point(0, 34); this.panel3.Name = "panel3"; this.panel3.Size = new System.Drawing.Size(613, 334); this.panel3.TabIndex = 5; // // dgvUsers // this.dgvUsers.AutoGenerateColumns = false; this.dgvUsers.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvUsers.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colId, this.colName, this.deptTitleDataGridViewTextBoxColumn}); this.dgvUsers.DataSource = this.sourceUsers; this.dgvUsers.Dock = System.Windows.Forms.DockStyle.Fill; this.dgvUsers.Location = new System.Drawing.Point(0, 25); this.dgvUsers.Name = "dgvUsers"; this.dgvUsers.RowTemplate.Height = 23; this.dgvUsers.Size = new System.Drawing.Size(613, 309); this.dgvUsers.TabIndex = 4; this.dgvUsers.CellMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dgvUsers_CellMouseClick); // // bindingNavigator1 // this.bindingNavigator1.AddNewItem = null; this.bindingNavigator1.BindingSource = this.sourceUsers; this.bindingNavigator1.CountItem = this.bindingNavigatorCountItem; this.bindingNavigator1.DeleteItem = null; this.bindingNavigator1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.bindingNavigatorMoveFirstItem, this.bindingNavigatorMovePreviousItem, this.bindingNavigatorSeparator, this.bindingNavigatorPositionItem, this.bindingNavigatorCountItem, this.bindingNavigatorSeparator1, this.bindingNavigatorMoveNextItem, this.bindingNavigatorMoveLastItem, this.bindingNavigatorSeparator2, this.tsbtnDelete, this.tsbtnRefresh, this.tsbtnChangeDb, this.toolStripButton1}); this.bindingNavigator1.Location = new System.Drawing.Point(0, 0); this.bindingNavigator1.MoveFirstItem = this.bindingNavigatorMoveFirstItem; this.bindingNavigator1.MoveLastItem = this.bindingNavigatorMoveLastItem; this.bindingNavigator1.MoveNextItem = this.bindingNavigatorMoveNextItem; this.bindingNavigator1.MovePreviousItem = this.bindingNavigatorMovePreviousItem; this.bindingNavigator1.Name = "bindingNavigator1"; this.bindingNavigator1.PositionItem = this.bindingNavigatorPositionItem; this.bindingNavigator1.Size = new System.Drawing.Size(613, 25); this.bindingNavigator1.TabIndex = 3; this.bindingNavigator1.Text = "bindingNavigator1"; // // bindingNavigatorCountItem // this.bindingNavigatorCountItem.Name = "bindingNavigatorCountItem"; this.bindingNavigatorCountItem.Size = new System.Drawing.Size(35, 22); this.bindingNavigatorCountItem.Text = "/ {0}"; this.bindingNavigatorCountItem.ToolTipText = "总项数"; // // bindingNavigatorMoveFirstItem // this.bindingNavigatorMoveFirstItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveFirstItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveFirstItem.Image"))); this.bindingNavigatorMoveFirstItem.Name = "bindingNavigatorMoveFirstItem"; this.bindingNavigatorMoveFirstItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveFirstItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveFirstItem.Text = "移到第一条记录"; // // bindingNavigatorMovePreviousItem // this.bindingNavigatorMovePreviousItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMovePreviousItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMovePreviousItem.Image"))); this.bindingNavigatorMovePreviousItem.Name = "bindingNavigatorMovePreviousItem"; this.bindingNavigatorMovePreviousItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMovePreviousItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMovePreviousItem.Text = "移到上一条记录"; // // bindingNavigatorSeparator // this.bindingNavigatorSeparator.Name = "bindingNavigatorSeparator"; this.bindingNavigatorSeparator.Size = new System.Drawing.Size(6, 25); // // bindingNavigatorPositionItem // this.bindingNavigatorPositionItem.AccessibleName = "位置"; this.bindingNavigatorPositionItem.AutoSize = false; this.bindingNavigatorPositionItem.Name = "bindingNavigatorPositionItem"; this.bindingNavigatorPositionItem.Size = new System.Drawing.Size(50, 21); this.bindingNavigatorPositionItem.Text = "0"; this.bindingNavigatorPositionItem.ToolTipText = "当前位置"; // // bindingNavigatorSeparator1 // this.bindingNavigatorSeparator1.Name = "bindingNavigatorSeparator1"; this.bindingNavigatorSeparator1.Size = new System.Drawing.Size(6, 25); // // bindingNavigatorMoveNextItem // this.bindingNavigatorMoveNextItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveNextItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveNextItem.Image"))); this.bindingNavigatorMoveNextItem.Name = "bindingNavigatorMoveNextItem"; this.bindingNavigatorMoveNextItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveNextItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveNextItem.Text = "移到下一条记录"; // // bindingNavigatorMoveLastItem // this.bindingNavigatorMoveLastItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveLastItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveLastItem.Image"))); this.bindingNavigatorMoveLastItem.Name = "bindingNavigatorMoveLastItem"; this.bindingNavigatorMoveLastItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveLastItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveLastItem.Text = "移到最后一条记录"; // // bindingNavigatorSeparator2 // this.bindingNavigatorSeparator2.Name = "bindingNavigatorSeparator2"; this.bindingNavigatorSeparator2.Size = new System.Drawing.Size(6, 25); // // tsbtnDelete // this.tsbtnDelete.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tsbtnDelete.Image = ((System.Drawing.Image)(resources.GetObject("tsbtnDelete.Image"))); this.tsbtnDelete.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsbtnDelete.Name = "tsbtnDelete"; this.tsbtnDelete.Size = new System.Drawing.Size(23, 22); this.tsbtnDelete.Text = "toolStripButton1"; this.tsbtnDelete.ToolTipText = "删除用户"; this.tsbtnDelete.Click += new System.EventHandler(this.tsbtnDelete_Click); // // tsbtnRefresh // this.tsbtnRefresh.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tsbtnRefresh.Image = ((System.Drawing.Image)(resources.GetObject("tsbtnRefresh.Image"))); this.tsbtnRefresh.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsbtnRefresh.Name = "tsbtnRefresh"; this.tsbtnRefresh.Size = new System.Drawing.Size(23, 22); this.tsbtnRefresh.Text = "toolStripButton2"; this.tsbtnRefresh.ToolTipText = "刷新"; this.tsbtnRefresh.Click += new System.EventHandler(this.tsbtnRefresh_Click); // // tsbtnChangeDb // this.tsbtnChangeDb.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tsbtnChangeDb.Image = ((System.Drawing.Image)(resources.GetObject("tsbtnChangeDb.Image"))); this.tsbtnChangeDb.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsbtnChangeDb.Name = "tsbtnChangeDb"; this.tsbtnChangeDb.Size = new System.Drawing.Size(23, 22); this.tsbtnChangeDb.Text = "toolStripButton1"; this.tsbtnChangeDb.ToolTipText = "切换数据库"; this.tsbtnChangeDb.Click += new System.EventHandler(this.tsbtnChangeDb_Click); // // panel2 // this.panel2.Controls.Add(this.cboAllDepts); this.panel2.Controls.Add(this.label5); this.panel2.Dock = System.Windows.Forms.DockStyle.Top; this.panel2.Location = new System.Drawing.Point(0, 0); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(613, 34); this.panel2.TabIndex = 4; // // cboAllDepts // this.cboAllDepts.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboAllDepts.FormattingEnabled = true; this.cboAllDepts.Location = new System.Drawing.Point(77, 4); this.cboAllDepts.Name = "cboAllDepts"; this.cboAllDepts.Size = new System.Drawing.Size(181, 20); this.cboAllDepts.TabIndex = 1; this.cboAllDepts.SelectedIndexChanged += new System.EventHandler(this.cboAllDepts_SelectedIndexChanged); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(7, 9); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(77, 12); this.label5.TabIndex = 0; this.label5.Text = "请选择部门:"; // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image"))); this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(69, 22); this.toolStripButton1.Text = "切换数据库"; this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click); // // colId // this.colId.DataPropertyName = "Id"; this.colId.HeaderText = "主键"; this.colId.Name = "colId"; this.colId.ReadOnly = true; // // colName // this.colName.DataPropertyName = "Name"; this.colName.HeaderText = "姓名"; this.colName.Name = "colName"; // // deptTitleDataGridViewTextBoxColumn // this.deptTitleDataGridViewTextBoxColumn.DataPropertyName = "DeptTitle"; this.deptTitleDataGridViewTextBoxColumn.HeaderText = "部门"; this.deptTitleDataGridViewTextBoxColumn.Name = "deptTitleDataGridViewTextBoxColumn"; this.deptTitleDataGridViewTextBoxColumn.ReadOnly = true; // // sourceUsers // this.sourceUsers.AllowNew = false; this.sourceUsers.DataSource = typeof(抽象工厂模式.BLL.UserObj); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(613, 549); this.Controls.Add(this.panel1); this.Controls.Add(this.btnInsert); this.Controls.Add(this.cboDeptAdd); this.Controls.Add(this.label3); this.Controls.Add(this.txtNameAdd); this.Controls.Add(this.label4); this.Controls.Add(this.btnEdit); this.Controls.Add(this.cboDepts); this.Controls.Add(this.label2); this.Controls.Add(this.txtName); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "测试"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.errorMsg)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.msgHelp)).EndInit(); this.panel1.ResumeLayout(false); this.panel3.ResumeLayout(false); this.panel3.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgvUsers)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingNavigator1)).EndInit(); this.bindingNavigator1.ResumeLayout(false); this.bindingNavigator1.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.sourceUsers)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.BindingSource sourceUsers; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox cboDepts; private System.Windows.Forms.ErrorProvider errorMsg; private System.Windows.Forms.Button btnEdit; private System.Windows.Forms.ComboBox cboDeptAdd; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txtNameAdd; private System.Windows.Forms.Label label4; private System.Windows.Forms.ErrorProvider msgHelp; private System.Windows.Forms.Button btnInsert; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.BindingNavigator bindingNavigator1; private System.Windows.Forms.ToolStripLabel bindingNavigatorCountItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveFirstItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMovePreviousItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator; private System.Windows.Forms.ToolStripTextBox bindingNavigatorPositionItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator1; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveNextItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveLastItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator2; private System.Windows.Forms.ToolStripButton tsbtnDelete; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.ComboBox cboAllDepts; private System.Windows.Forms.Label label5; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.DataGridView dgvUsers; private System.Windows.Forms.ToolStripButton tsbtnRefresh; private System.Windows.Forms.ToolStripButton tsbtnChangeDb; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.DataGridViewTextBoxColumn colId; private System.Windows.Forms.DataGridViewTextBoxColumn colName; private System.Windows.Forms.DataGridViewTextBoxColumn deptTitleDataGridViewTextBoxColumn; } }
Help.cs代码:
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.IO;
5 using System.Configuration;
6 using System.Windows.Forms;
7 using System.Reflection;
8 namespace 抽象工厂模式
9 {
10 class Helper
11 {
12 private static string ProviderType = ConfigurationManager.AppSettings["ProviderType"];
13 private static string DBConnString =
14 ConfigurationManager.ConnectionStrings["DBConnString"].ConnectionString;
15 public static void ChangeDbServer()
16 {
17 SetConfig();
18 //可以采用System.Xml命名空间中的类
19
20 string content = File.ReadAllText(Application.StartupPath + "\\AppTemplate.xml");
21 content = content.Replace("%ProviderType%", ProviderType).Replace("%DBConnString%", DBConnString);
22
23 File.WriteAllText(Application.ExecutablePath + ".config", content);
24 // File.WriteAllText(Application.StartupPath + "\\抽象工厂模式.vshost.exe.config",content);
25
26 //强制刷新,避免重启程序
27 ConfigurationManager.RefreshSection("appSettings");
28 ConfigurationManager.RefreshSection("connectionStrings");
29 }
30
31 private static void SetConfig()
32 {
33 if (ProviderType.ToLower() == "sql")
34 {
35 ProviderType = "Access";
36 DBConnString =
37 @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\netStudy\抽象工厂模式\testdb.mdb";
38 }
39 else
40 {
41 ProviderType = "Sql";
42 DBConnString = @"Data Source=.\sqlexpress;Initial Catalog=testdb;Integrated Security=True";
43 }
44 }
45
46 public static void ChangeConfiguration()
47 {
48
49 SetConfig(); //读取程序集的配置文件
50
51 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
52
53 //获取appSettings节点
54 AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
55 appSettings.Settings["ProviderType"].Value = ProviderType;
56
57 var connectionSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
58 connectionSection.ConnectionStrings["DBConnString"].ConnectionString = DBConnString;
59 //保存配置文件
60 config.Save();
61
62 //强制刷新,避免重启程序
63 ConfigurationManager.RefreshSection("appSettings");//刷新命名节,在下次检索它时将会从磁盘重新读取
64 ConfigurationManager.RefreshSection("connectionStrings");
65 }
66 }
67 }
AccessUserProvider的代码:
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Data;
5 using System.Data.OleDb;
6 using 抽象工厂模式.DAL;
7 using 抽象工厂模式.DAL.Entity;
8
9 namespace 抽象工厂模式.DAL.Provider.Access
10 {
11 public class AccessUserProvider:UserProvider
12 {
13
14 public override List<User> GetUsers()
15 {
16 using (OleDbConnection conn = new OleDbConnection(ConnString))
17 {
18 var dbcmd = conn.CreateCommand();
19 dbcmd.CommandText = "GetUsers";
20 dbcmd.CommandType = CommandType.StoredProcedure;
21 conn.Open();
22 return GetUsersFromReader(dbcmd.ExecuteReader());
23 }
24 }
25
26 public override List<User> GetUsers(int deptId)
27 {
28 using (OleDbConnection conn = new OleDbConnection(ConnString))
29 {
30 var dbcmd = conn.CreateCommand();
31 dbcmd.CommandText = "GetUsersByDepartmentId";
32 dbcmd.CommandType = CommandType.StoredProcedure;
33 dbcmd.Parameters.Add("@DeptId", OleDbType.Integer).Value = deptId;
34 conn.Open();
35 return GetUsersFromReader(dbcmd.ExecuteReader());
36 }
37 }
38
39 public override User GetUserById(int id)
40 {
41 using (OleDbConnection conn = new OleDbConnection(ConnString))
42 {
43 var dbcmd = conn.CreateCommand();
44 dbcmd.CommandText = "GetUserById";
45 dbcmd.CommandType = CommandType.StoredProcedure;
46 dbcmd.Parameters.Add("@Id", OleDbType.Integer).Value =id ;
47 conn.Open();
48 var reader = dbcmd.ExecuteReader();
49 if (reader.Read()) return GetUserFromReader(reader); else return null;
50 }
51 }
52
53 public override bool DeleteUser(int id)
54 {
55 using (OleDbConnection conn = new OleDbConnection(ConnString))
56 {
57 OleDbCommand cmd = new OleDbCommand(
58 "delete from [user] where Id=" + id, conn);
59 conn.Open();
60 return cmd.ExecuteNonQuery() == 1;
61 }
62 }
63
64 public override int InsertUser(User user)
65 {
66 int result = 0;
67 using (OleDbConnection conn = new OleDbConnection(ConnString))
68 {
69 OleDbCommand cmd = new OleDbCommand(
70 @"insert into [user]([name],deptId) values(@name,@deptid);", conn);
71 cmd.Parameters.Add("@name", OleDbType.VarChar).Value = user.Name; //与下面的一行代码不能颠倒
72 cmd.Parameters.Add("@deptid", OleDbType.Integer).Value = user.DeptId;//access的sql语句参数必须按照顺序匹配
73 conn.Open();
74 var trans = conn.BeginTransaction();//执行数据库事务
75 cmd.Transaction = trans;
76 try
77 {
78
79 bool success = cmd.ExecuteNonQuery() == 1;
80 if (success)
81 {
82 cmd.CommandText = "select max(id) from [user] as newid;"; //由于access不支持多条语句一起执行,只好分多次<两次>执行
83 result = (int)cmd.ExecuteScalar();
84 trans.Commit(); //提交事务
85 }
86 }
87 catch (Exception)
88 {
89 trans.Rollback();//出现异常,回滚事务
90 }
91 }
92 return result;
93 }
94
95 public override bool UpdateUser(User user)
96 {
97 using (OleDbConnection conn = new OleDbConnection(ConnString))
98 {
99 OleDbCommand cmd = new OleDbCommand(
100 "update [user] set [name]=@name,deptId=@deptid where Id=@id" , conn);
101 cmd.Parameters.Add("@name", OleDbType.VarChar).Value = user.Name;
102 cmd.Parameters.Add("@deptid", OleDbType.Integer).Value = user.DeptId;
103 cmd.Parameters.Add("@id", OleDbType.Integer).Value = user.Id;
104 conn.Open();
105 return cmd.ExecuteNonQuery() == 1;
106 }
107 }
108
109 }
110 }
当来之世,经道灭尽,我以慈悲哀愍,特留此经止住百岁。其有众生,值斯经者,随意所愿,皆可得度。(南无阿弥陀佛)
道可道,非常道;名可名,非常名。
我常说,一个国家,一个民族,亡国都不怕,最可怕的是一个国 家和民族自己的根本文化亡掉了,这就会沦为万劫不复,永远不会翻身。---南怀瑾<国学大师>