C#編程筆記(一)

作者: 郝玉琨  來源: 博客園  發布時間: 2011-02-28 14:54  閱讀: 2264 次  推薦: 0   原文鏈接   [收藏]  

      前段時間,幫朋友用C#做了一個小玩意兒,在開發過程中,發現很多用的著的東西,在網上都沒有很好的解決方案,前前后后折騰了近一個月,總算是基本上完成了,在此整理下,權作以后再用到時復習之用。

      這個東西有點像星座性格測試那種的,只不過是要C/S的,安裝到客戶端上,所以做起來限制比較多。首先要有數據錄入的功能,提供界面,用戶要能向其中錄入數據,比如星座測試一條一條的題目;然后要對每個題目,提出相應的反饋、建議;最后,錄入完成了,用戶還要能夠有個界面對指定的數據庫進行增刪改查:前面是錄入的功能。在用戶性格測試的時候,要有窗口完成答題,并在提交后,查看測試的結果,有打分,有整體評價,并且對于那些答得不合適的,還有一些建議。

      接下來,我會按不同的模塊,說一說我是怎么做的。

      (1)數據的存儲

      由于沒有數據庫管理系統的支持,我選擇XML來保存數據。所以,這一模塊就是基本的XML的創建、添加、刪除。

      (1.1)XML文件的新建

      我做的這個玩意兒,用的XML的數據格式比較固定,所以,新建XML文件的時候,大的結構就寫死了,不希望,也不會發生改變:

EmptyXmlDocumentCreate
 1                 this._fileName = fileName;
 2                 this._xDoc = new XmlDocument();
 3                 this._xDoc.LoadXml(
 4                     "<?xml version=\"1.0\" encoding=\"gb2312\" ?>" +
 5                         "<root>"+
 6                             "<Principles>" +
 7                             "</Principles>"+
 8                             "<Results>"+
 9                             "</Results>"+
10                         "</root>"
11                     );
12                 try
13                 {
14                     this._xDoc.Save(fileName);
15                 }
16                 catch (Exception ex)
17                 {
18                     MessageBox.Show(ex.Message);
19                 }

      (1.2)向XML文件中的指定位置添加節點

      這里要說的是,我要添加的節點的數據結構是<ID,Content,Suggestion>。再者,添加節點的時候,用在樹上直接找的辦法,比較笨,用xPath會好很多,可惜時間緊沒學明白……

addToXMLDocument
 1         public void addToXMLDocument(string id, string content, string suggestion)
 2         {
 3             XmlNode Term = this._xDoc.CreateNode(XmlNodeType.Element, "Term""");
 4 
 5             XmlElement ID = this._xDoc.CreateElement("ID");
 6             ID.InnerText = id;
 7             Term.AppendChild(ID);
 8 
 9             XmlElement Content = this._xDoc.CreateElement("Content");
10             Content.InnerText = content;
11             Term.AppendChild(Content);
12 
13             XmlElement Suggestion = this._xDoc.CreateElement("Suggestion");
14             Suggestion.InnerText = suggestion;
15             Term.AppendChild(Suggestion);
16 
17             this._xDoc.ChildNodes.Item(1).ChildNodes.Item(0).AppendChild(Term);
18 
19             try
20             {
21                 this._xDoc.Save(this._fileName);
22             }
23             catch (Exception ex)
24             {
25                 MessageBox.Show(ex.Message);
26             }
27         }

      (1.3)從XML文件中刪除指定的節點

      在應用中,我是在ListView中把XML的數據打出來,通過勾選CheckBox選定刪除的對象。

DeleteNodeFromXmlDocument
 1         private void button4_Click(object sender, EventArgs e)
 2         {
 3             XmlDocument xDoc = new XmlDocument();
 4             xDoc.Load(this._fileName);
 5             foreach (ListViewItem lItem in Listview1.Items)
 6             {
 7                 if (lItem.Checked == true)
 8                 {
 9                     //int index = Convert.ToInt32(lItem.SubItems[1].Text, 10);
10                     foreach (XmlNode xNode in xDoc.ChildNodes.Item(1).ChildNodes.Item(0).ChildNodes)
11                     {
12                         if (String.Compare(xNode.ChildNodes[0].InnerText, lItem.SubItems[1].Text) == 0)
13                         {
14                             xDoc.ChildNodes.Item(1).ChildNodes.Item(0).RemoveChild(xNode);
15                         }
16                     }
17                     Listview1.Items.Remove(lItem);
18                 }
19             }
20             xDoc.Save(this._fileName);
21             Re_Load();
22         }

      (2)動態界面生成

       這個算是我在第一階段遇到的最大的一個問題。作為一個C#的菜鳥,習慣了拖拖拽拽弄出一個窗口界面,當被要求根據用戶輸入,動態生成界面的時候,直接歇菜了……

       在網上找了很多,可惜很多都不適用,忘記后來是在哪里找到的答案,向那位記不起名兒的童鞋致敬了。

       是這樣的,所謂的動態生成,就是把原來在Form.Designer.cs中代碼,搬到你自己的代碼中去。比如,你原來在Form.Designer.cs中有這樣的代碼

Example: Form.Designer.cs
1             // 
2             // button1
3             // 
4             this.button1.Location = new System.Drawing.Point(5797);
5             this.button1.Name = "button1";
6             this.button1.Size = new System.Drawing.Size(7523);
7             this.button1.TabIndex = 0;
8             this.button1.Text = "button1";
9             this.button1.UseVisualStyleBackColor = true;

       你可以寫到你自定義的Button2的Click事件中,這樣,在你點擊Button2后,就會在窗口上新加一個Button1出來

Example: ButtonClick
 1         private void button2_Click(object sender, EventArgs e)
 2         {
 3             // 
 4             // button1
 5             // 
 6             this.button1.Location = new System.Drawing.Point(5797);
 7             this.button1.Name = "button1";
 8             this.button1.Size = new System.Drawing.Size(7523);
 9             this.button1.TabIndex = 0;
10             this.button1.Text = "button1";
11             this.button1.UseVisualStyleBackColor = true;
12             this.Controls.Add(this.button1);
13             this.ResumeLayout(false);
14         }

       (2.1)說一說我自己做的那個東西,我設計如下:在Form中先放好一個大Panel,然后,根據用戶輸入,動態加入指定個數的組件Component。在每個Component里面,包含一個GroupBox,三個Label,三個TextBox,還有一些坐標的參數。

        要說一下,竊以為,動態加入組件,最麻煩的就是算坐標。那么多的東西,你需要事先把每個組件的坐標位置和大小都算好了,然后,你才可以保證你按下“添加”之后,你的組件能按照你想要的方式,呈現在窗口上。所以我對應每一條要添加的數據項,構造了上面的一個Component,然后給每個Component設置索引值,只要得到索引值,那么,這個Component的位置也就確定了。

        比較欣慰的是,這個組件的坐標是按相對位置計算的:你設置GroupBox的坐標時,你只要算好你在Panel中的位置就可以了,你不用管Panel在Form的哪里。同樣,你的Label,TextBox只要算好在一個200*50的GroupBox中的位置就可以了,剩下的你就不用管了。或許是以前沒有注意過這個問題,反正我覺得這一性質在我做的過程中,省了不少的事兒。

        這就完了么?No,還有一個我開始都沒注意到的問題:最大化。對,你算的坐標是死的,當用戶點擊“最大化”按鈕后,你的界面就會面目全非,所以,這里又要加入一個新的東西:TableLayoutPanel。Yes,需要把前面的那些寫死的坐標,都放到這個TableLayoutPanel里面來,設置好每個組件的位置,這樣,在“最大化”之后,依然能夠保持良好的布局。

Component
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace app01_Generate
{
    
class Component
    {
        
#region 成員變量定義

        public static int OFFSET = 3;
        
public static int HEIGHT = 98;
        
private int _weight;
        
private int _index;
        
private GroupBox _gb;
        
private Label _lb1, _lb2, _lb3;
        
private TextBox _tb1, _tb2, _tb3;
        
private TableLayoutPanel _tlp;

        
#endregion

        public Component(int index,int weight)
        {
            
this._index = index;
            
this._weight = weight;

            
this._gb = new GroupBox();
            
this._gb.Location = new Point(3, OFFSET + this._index * HEIGHT);
            
this._gb.Size = new System.Drawing.Size(this._weight, 92);
            
this._gb.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        
| System.Windows.Forms.AnchorStyles.Right)));
            
            
this._tlp = new TableLayoutPanel();
            
this._tlp.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        
| System.Windows.Forms.AnchorStyles.Left)
                        
| System.Windows.Forms.AnchorStyles.Right)));
            
this._tlp.ColumnCount = 25;
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4F));
            
this._tlp.Location = new System.Drawing.Point(620);
            
this._tlp.Name = "_tlp";
            
this._tlp.RowCount = 1;
            
this._tlp.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            
this._tlp.Size = new System.Drawing.Size(this._weight - 1266);

            
this._lb1 = new Label();
            
this._lb1.Anchor = ((System.Windows.Forms.AnchorStyles)(( System.Windows.Forms.AnchorStyles.Right)));
            
this._lb1.AutoSize = true;
            
this._tlp.SetColumnSpan(this._lb1, 2);
            
this._lb1.Font = new System.Drawing.Font("微軟雅黑"10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            
this._lb1.Location = new System.Drawing.Point((int)((this._weight - 12* 8 / 741), 0);
            
this._lb1.Name = "_lb1";
            
this._lb1.Size = new System.Drawing.Size(4719);
            
this._lb1.Text = "ID";


            
this._lb2 = new Label();
            
this._lb2.Anchor = ((System.Windows.Forms.AnchorStyles)(( System.Windows.Forms.AnchorStyles.Right)));
            
this._lb2.AutoSize = true;
            
this._tlp.SetColumnSpan(this._lb2, 2);
            
this._lb2.Font = new System.Drawing.Font("微軟雅黑"10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            
this._lb2.Location = new System.Drawing.Point((int)((this._weight - 12* 124 / 741), 0);
            
this._lb2.Name = "_lb2";
            
this._lb2.Size = new System.Drawing.Size(4738);
            
this._lb2.Text = "Content";

            
this._lb3 = new Label();
            
this._lb3.Anchor = ((System.Windows.Forms.AnchorStyles)(( System.Windows.Forms.AnchorStyles.Right)));
            
this._lb3.AutoSize = true;
            
this._tlp.SetColumnSpan(this._lb3, 2);
            
this._lb3.Font = new System.Drawing.Font("微軟雅黑"10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            
this._lb3.Location = new System.Drawing.Point((int)((this._weight - 12* 501 / 741), 0);
            
this._lb3.Name = "_lb3";
            
this._lb3.Size = new System.Drawing.Size(4738);
            
this._lb3.Text = "Suggestion";

            
this._tb1 = new TextBox();
            
this._tb1.Anchor = ((System.Windows.Forms.AnchorStyles)((( System.Windows.Forms.AnchorStyles.Left)
            
| System.Windows.Forms.AnchorStyles.Right)));
            
this._tlp.SetColumnSpan(this._tb1, 2);
            
this._tb1.Font = new System.Drawing.Font("仿宋"10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            
this._tb1.Location = new System.Drawing.Point((int)((this._weight - 12* 61 / 741), 3);
            
this._tb1.Name = "_tb1";
            
this._tb1.Size = new System.Drawing.Size(5229);

            
this._tb2 = new TextBox();
            
this._tb2.Anchor = ((System.Windows.Forms.AnchorStyles)((( System.Windows.Forms.AnchorStyles.Left)
                        
| System.Windows.Forms.AnchorStyles.Right)));
            
this._tlp.SetColumnSpan(this._tb2, 11);
            
this._tb2.Font = new System.Drawing.Font("仿宋"10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            
this._tb2.Location = new System.Drawing.Point((int)((this._weight - 12* 177 / 741), 3);
            
this._tb2.Multiline = true;
            
this._tb2.Name = "_tb2";
            
this._tb2.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            
this._tb2.Size = new System.Drawing.Size(31348);

            
this._tb3 = new TextBox();
            
this._tb3.Anchor = ((System.Windows.Forms.AnchorStyles)((( System.Windows.Forms.AnchorStyles.Left)
                        
| System.Windows.Forms.AnchorStyles.Right)));
            
this._tlp.SetColumnSpan(this._tb3, 6);
            
this._tb3.Font = new System.Drawing.Font("仿宋"10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            
this._tb3.Location = new System.Drawing.Point((int)((this._weight - 12* 554 / 741), 3);
            
this._tb3.Multiline = true;
            
this._tb3.Name = "_tb3";
            
this._tb3.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            
this._tb3.Size = new System.Drawing.Size(18448);

            
this._tlp.Controls.Add(this._lb1, 00);
            
this._tlp.Controls.Add(this._tb1, 20);
            
this._tlp.Controls.Add(this._lb2, 40);
            
this._tlp.Controls.Add(this._lb3, 170);
            
this._tlp.Controls.Add(this._tb3, 190);
            
this._tlp.Controls.Add(this._tb2, 60);
            
this._gb.Controls.Add(this._tlp);

        }

        
public void addToPanel(ref Panel pnl)
        {
            pnl.Controls.Add(
this._gb);
        }

        
public void Clear()
        {
            
this._tb1.Clear();
            
this._tb2.Clear();
            
this._tb3.Clear();
        }

        
public string getID()
        {
            
return this._tb1.Text.Trim();
        }

        
public string getContent()
        {
            
return this._tb2.Text.Trim();
        }

        
public string getSuggestion()
        {
            
return this._tb3.Text.Trim();
        }

        
public bool Check()
        {
            
if (string.IsNullOrEmpty(this._tb1.Text.Trim()) == false ||
                string.IsNullOrEmpty(this._tb2.Text.Trim()) == false ||
                string.IsNullOrEmpty(this._tb3.Text.Trim()) == false
                )
                
return false;
            
else
                return true;
        }

        
public void Refresh(string id, string content, string suggestion)
        {
            
this._tb1.Text = id;
            
this._tb2.Text = content;
            
this._tb3.Text = suggestion;
        }

    }
}

        (3)ListView的使用

        不得不說,ListView真是個不錯的東西,在顯示數據和處理的時候,非常的簡單實用。

        (3.1)ListView顯示XML數據

        原理很簡單,就是把XML中每個節點,填充到ListView的SubItem上。

ListViewShowXMLDocument
 1         private void Re_Load()
 2         {
 3             this.Listview1.Columns.Clear();
 4             this.Listview1.Items.Clear();
 5             this.Listview1.Columns.Add(" "20, HorizontalAlignment.Left);
 6             this.Listview1.Columns.Add("ID"80, HorizontalAlignment.Left);
 7             this.Listview1.Columns.Add("Content", (int)((this.Listview1.Width - 80* 0.5), HorizontalAlignment.Left);
 8             this.Listview1.Columns.Add("Suggestion", (int)((this.Listview1.Width - 80* 0.3), HorizontalAlignment.Left);
 9             this.Listview1.ListViewItemSorter = new ListViewItemComparer(1);
10 
11             ListViewItem myItem = null;
12             XmlDocument xDoc = new XmlDocument();
13             xDoc.Load(this._fileName);
14             XmlNode root = xDoc.ChildNodes.Item(1).ChildNodes.Item(0);
15 
16             foreach (XmlNode xNode in root.ChildNodes)
17             {
18                 myItem = new ListViewItem();
19                 //myItem.SubItems.Add("");
20                 myItem.SubItems.Add(xNode.ChildNodes[0].InnerText);
21                 myItem.SubItems.Add(xNode.ChildNodes[1].InnerText);
22                 myItem.SubItems.Add(xNode.ChildNodes[2].InnerText);
23                 Listview1.Items.Add(myItem);
24             }
25             
26         }

       (3.2)ListView的排序  

       注意到,上面設置了ListView的排序規則"this.Listview1.ListViewItemSorter = new ListViewItemComparer(1);",意思是:用ListViewItemComparer的一個對象,按ListView的第一列數據進行排序,就是按照ID進行排序。我是這兒考慮的,在XML文件里面,你對子節點按照ID進行排序,又麻煩,而且意義不是很大,干脆在呈現數據的時候,排一次序,這樣看起來就非常齊整,不會因為用戶的增加刪除而亂序。

ListViewItemComparer
 1         class ListViewItemComparer : IComparer
 2         {
 3             private int col;
 4             public ListViewItemComparer()
 5             {
 6                 col = 0;
 7             }
 8             public ListViewItemComparer(int column)
 9             {
10                 col = column;
11             }
12             public int Compare(object x, object y)
13             {
14                 return Convert.ToInt32(((ListViewItem)x).SubItems[col].Text,10- Convert.ToInt32(((ListViewItem)y).SubItems[col].Text,10);
15             }
16         }

       (3.3)ListView的刪除

       發現了ListView.CheckBoxes這個屬性,設置為true之后,在每條數據的前面加上了一個CheckBox,實用這個東西還完成數據項的刪除,同時映射后ListView綁定的XML文件數據刪除。

ListViewDeleteItem
 1             XmlDocument xDoc = new XmlDocument();
 2             xDoc.Load(this._fileName);
 3             foreach (ListViewItem lItem in Listview1.Items)
 4             {
 5                 if (lItem.Checked == true)
 6                 {
 7                     //int index = Convert.ToInt32(lItem.SubItems[1].Text, 10);
 8                     foreach (XmlNode xNode in xDoc.ChildNodes.Item(1).ChildNodes.Item(0).ChildNodes)
 9                     {
10                         if (String.Compare(xNode.ChildNodes[0].InnerText, lItem.SubItems[1].Text) == 0)
11                         {
12                             xDoc.ChildNodes.Item(1).ChildNodes.Item(0).RemoveChild(xNode);
13                         }
14                     }
15                     Listview1.Items.Remove(lItem);
16                 }
17             }
18             xDoc.Save(this._fileName);
19             Re_Load();

       可能,這些操作用DataGridView比較好,不過,時間有點急,DataGridView的東西有比較多,實在是沒能吃下,用了下,比較吃力,還是暫時放棄了。    

0
1
 
標簽:C#
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()