界面層UI實現過程(桌面版)


來到UI層編寫了,由於三層的架構體系,所以UI層只需要和BLL層溝通就好。(BLL層和DAL層交互,DAL層與底層數據庫交互),關於DAL層的編碼BLL層編碼實現過程,請參考前面的文章。

先來看看最終效果:(這里只能拋磚引玉,小蟲我在界面美觀上沒有仔細用功,這一點大家千萬不能也如此不重視,好的編程人員在UI上也要起碼的讓客戶看上去舒服,這一點我做得很不夠。所以后面的界面效果望大家能見諒!)

image

數據庫已經切換了(目前只有Access數據庫和SqlServer數據庫)

image

image

image

image

實際上就是實現了用戶的增刪改和按部門查詢的功能,加上了一個雞肋(數據庫切換)(對app.config的配置更新還是有了解的必要)。

<實際上是不存在此需求,具體的一個客戶端只選擇一種固定數據庫的。這里僅僅為了測試方便,硬加上的。>

(其他的比如對部門的增刪改功能和組合查詢等就省略了。)

 

接下來,看看實現的過程:(首先界面需要的控件如圖)

image

這里說明一下:控件的命名,后續代碼看起來明白些。

序號 控件名[類型名] 位置 備注
1 cboAllDepts 最上面的ComboBox  
2 bndingNavigator1 image 其屬性DataSource=sourceUsers
3 dgvUsers[DataGridView控件] image

dgvUsers.DataSource=sourceUsers

請注意:姓名這一列的命名為:colName,因為后續要編碼。

4 sourceUsers[BindingSource] image

非可視化控件(運行時看不見的控件)

sourcUsers.Current獲取當前的項

5 image

txtName.Tag=”姓名不能為空!”

為了與errorMsg控件配合顯示錯誤用

ComboBox控件的DropDownStyle=DropDownList屬性,這樣不可能為空。(FormLoad事件)

6 image

txtNameAdd.Tag=”姓名不能為空!”

為了與errorMsg控件配合顯示錯誤用

7 errorMsg[ErrorProvider]  image

用來在指定控件右邊顯示錯誤圖標和指定的錯誤信息

SetError方法、GetError方法

8 msgHelp[ErrorProvider]  image

用來顯示添加成功的圖標!

image

 

 

image

切換后台數據庫:

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,內容如下:

image

程序運行的時候讀取該文件,將%ProviderType%和%DBConnString%替換成合適的內容,然后將該內容保存到App.config中就可以了。

image 見上圖:
1.讀取模板 2.替換特別字符串 3.寫入到app.config
4.ConfigurationManager.RefreshSection一定不要忘記,它會強制從磁盤重新讀取。否則讀取的是緩存內容<要重啟程序才能生效>。 image

 

注意:程序如果處在調試狀態,你要看到效果:對應的config文件是vshost.exe.config,但程序獨立運行不調試的時候,代碼要換為:.config。

總之要留心這個問題。(調試和獨立運行對應的config文件不同。)

 

正式基於這點,又上網查詢了下,有牛人給出了更好的解決方案<見下圖方法:ChangeConfiguration()>,

一來會自動解決調試和獨立運行的config文件,二來不要模板文件(讀寫都不需要)。 實現的直接替換。

image

在運行測試的過程中,發生了一些異常,主要是Access數據庫sql語句訪問的一些特殊地方。

image

 

對比一下:SqlUserProvider.cs中對應的代碼:

image

參考代碼:

Form1.cs代碼:

View Code
  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代碼:

View Code
 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的代碼:

View Code
  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 }



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM