2014年5月15日 星期四

視窗程式設計5/15

練習A
#pragma once


namespace graph3 {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;

	/// <summary>
	/// Form1 的摘要
	///
	/// 警告: 如果您變更這個類別的名稱,就必須變更與這個類別所依據之所有 .resx 檔案關聯的
	///          Managed 資源編譯器工具的 'Resource File Name' 屬性。
	///          否則,這些設計工具
	///          將無法與這個表單關聯的當地語系化資源
	///          正確互動。
	/// </summary>
	public ref class Form1 : public System::Windows::Forms::Form
	{
	public:
		Form1(void)
		{
			InitializeComponent();
			//
			//TODO: 在此加入建構函式程式碼
			//
		}

	protected:
		/// <summary>
		/// 清除任何使用中的資源。
		/// </summary>
		~Form1()
		{
			if (components)
			{
				delete components;
			}
		}

	private:
		/// <summary>
		/// 設計工具所需的變數。
		/// </summary>
		System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
		/// <summary>
		/// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改這個方法的內容。
		///
		/// </summary>
		void InitializeComponent(void)
		{
			this->SuspendLayout();
			// 
			// Form1
			// 
			this->AutoScaleDimensions = System::Drawing::SizeF(8, 15);
			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
			this->ClientSize = System::Drawing::Size(673, 613);
			this->Name = L"Form1";
			this->Text = L"Form1";
			this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
			this->ResumeLayout(false);

		}
#pragma endregion
	private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
			 }
	protected: virtual void OnPaint(PaintEventArgs^ e) override{
				   System::Drawing::Font ^myFont=gcnew System::Drawing::Font("Verdana",18);
				   System::Drawing::SolidBrush ^redBrush=gcnew System::Drawing::SolidBrush(Color::Red);
				   System::Drawing::SolidBrush ^blueBrush=gcnew System::Drawing::SolidBrush(Color::Blue);				
				   /*for(int i=0;i<20;i+=2){	
					   if(i%4)
							e->Graphics->DrawString("Hellow USC!", myFont, redBrush, 40+i*10, 40+i*10);
					   else	
							e->Graphics->DrawString("Hellow USC!", myFont, blueBrush, 400-i*10, 60+i*10);
				   }*/

				   Graphics^ g = e->Graphics;
		
 				Pen^ myPen = gcnew Pen(Color::Black, 3);
				/*for(int i=0;i<20;i++){
					for(int j=0;j<7000000;j++) ;
					g->DrawEllipse(myPen, 30+i*15, 20+i*10, 220, 90); 
				}*/

				/*				
				int x1 = 300,y1=200,x2=150,y2=150;				
				g->FillEllipse(redBrush2,x1,y1,x2,y2);
				*/

				Pen^ myPen2 = gcnew Pen(Color::White, 3);
				SolidBrush^ redBrush2 = gcnew SolidBrush(Color::HotPink);
				int r=200,x,y;
				double deg=Math::PI/72;
				for(int i=0;i<144;i++){
					for(int j=0;j<70000000;j++) ;
					g->DrawLine(myPen2, 200, 200, 200+x, 200+y);
					x=r*Math::Sin(deg*i);
					y=r*Math::Cos(deg*i);
					g->DrawLine(myPen, 200, 200, 200+x, 200+y);
				}
				
				
			   }
	};
}

老師範例
#pragma once


namespace graph3 {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;

	/// <summary>
	/// Form1 的摘要
	///
	/// 警告: 如果您變更這個類別的名稱,就必須變更與這個類別所依據之所有 .resx 檔案關聯的
	///          Managed 資源編譯器工具的 'Resource File Name' 屬性。
	///          否則,這些設計工具
	///          將無法與這個表單關聯的當地語系化資源
	///          正確互動。
	/// </summary>
	public ref class Form1 : public System::Windows::Forms::Form
	{
	public:
		Form1(void)
		{
			InitializeComponent();
			//
			//TODO: 在此加入建構函式程式碼
			//
		}

	protected:
		/// <summary>
		/// 清除任何使用中的資源。
		/// </summary>
		~Form1()
		{
			if (components)
			{
				delete components;
			}
		}

	private:
		/// <summary>
		/// 設計工具所需的變數。
		/// </summary>
		System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
		/// <summary>
		/// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改這個方法的內容。
		///
		/// </summary>
		void InitializeComponent(void)
		{
			this->SuspendLayout();
			// 
			// Form1
			// 
			this->AutoScaleDimensions = System::Drawing::SizeF(8, 15);
			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
			this->ClientSize = System::Drawing::Size(673, 613);
			this->Name = L"Form1";
			this->Text = L"Form1";
			this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
			this->ResumeLayout(false);

		}
#pragma endregion
	private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
			 }
	protected: virtual void OnPaint(PaintEventArgs^ e) override{
				   System::Drawing::Font ^myFont=gcnew System::Drawing::Font("Verdana",18);
				   System::Drawing::SolidBrush ^redBrush=gcnew System::Drawing::SolidBrush(Color::Red);
				   e->Graphics->DrawString("Hellow USC!", myFont, redBrush, 40, 40);
//=========================================================================
				Graphics^ g = e->Graphics;

 				Pen^ myPen = gcnew Pen(Color::Black, 3);

				g->DrawEllipse(myPen, 30, 20, 220, 90); 

				// Graphics^ g = e->Graphics;
//==========================================================================

				Pen^ goldPen = gcnew Pen(Color::Gold, 5);

				array<PointF>^ curvePoints =gcnew array<PointF>
				  {PointF(230,260), PointF(230,235), PointF(370,215), PointF(410,260), PointF(430,310)};

				g->DrawClosedCurve(goldPen, curvePoints);
//=====================================================================================

				Pen^ blackPen = gcnew Pen(Color::Black, 3);
				int x =35;	// 方框左上點橫座標(方框為?圓之外框)
				int y =15;	// 方框左上點縱座標
				int width = 200;	// 方框寬
				int height = 100;	// 方框高
				int startAngle =  40;	// 開始角度
				int sweepAngle = 230;	// 掃過角度

				g->DrawPie(blackPen, x, y, width, height, startAngle, sweepAngle);
//=======================================================================================

				SolidBrush^ redBrush2 = gcnew SolidBrush(Color::LightBlue);

				int x1 = 300;
				int y1 = 20;
				int x2 = 380;
				int y2 = 70;

				g->FillEllipse(redBrush2 , x1, y1, x2, y2); 
//=======================================================================================
		// 先產生fillRegion區域
		System::Drawing::Region^ fillRegion = 
			gcnew System::Drawing::Region(Rectangle(230, 230, 330, 330));   
		// 將fillRegion區域與Rectangle 聯集
		fillRegion->Complement(Rectangle(260, 260, 330, 330));    	

		SolidBrush^ br1=gcnew SolidBrush(Color::Red);
		// 畫實心區域圖
		g->FillRegion(br1,fillRegion);   

			   }
	};
}
練習B
#pragma once


namespace graph3 {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;

	/// <summary>
	/// Form1 的摘要
	///
	/// 警告: 如果您變更這個類別的名稱,就必須變更與這個類別所依據之所有 .resx 檔案關聯的
	///          Managed 資源編譯器工具的 'Resource File Name' 屬性。
	///          否則,這些設計工具
	///          將無法與這個表單關聯的當地語系化資源
	///          正確互動。
	/// </summary>
	public ref class Form1 : public System::Windows::Forms::Form
	{
	public:
		Form1(void)
		{
			InitializeComponent();
			//
			//TODO: 在此加入建構函式程式碼
			//
		}
		Graphics^ g1;
		Pen ^p1, ^p2;
	private: System::Windows::Forms::Button^  button1;
	private: System::Windows::Forms::Button^  button3;
	public: 
	private: System::Windows::Forms::Button^  button2;
	protected:
		/// <summary>
		/// 清除任何使用中的資源。
		/// </summary>
		~Form1()
		{
			if (components)
			{
				delete components;
			}
		}

	private:
		/// <summary>
		/// 設計工具所需的變數。
		/// </summary>
		System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
		/// <summary>
		/// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改這個方法的內容。
		///
		/// </summary>
		void InitializeComponent(void)
		{
			this->button1 = (gcnew System::Windows::Forms::Button());
			this->button2 = (gcnew System::Windows::Forms::Button());
			this->button3 = (gcnew System::Windows::Forms::Button());
			this->SuspendLayout();
			// 
			// button1
			// 
			this->button1->Location = System::Drawing::Point(93, 440);
			this->button1->Margin = System::Windows::Forms::Padding(5);
			this->button1->Name = L"button1";
			this->button1->Size = System::Drawing::Size(122, 35);
			this->button1->TabIndex = 0;
			this->button1->Text = L"Circle";
			this->button1->UseVisualStyleBackColor = true;
			this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
			// 
			// button2
			// 
			this->button2->Location = System::Drawing::Point(272, 440);
			this->button2->Margin = System::Windows::Forms::Padding(5);
			this->button2->Name = L"button2";
			this->button2->Size = System::Drawing::Size(122, 35);
			this->button2->TabIndex = 1;
			this->button2->Text = L"Retcangle";
			this->button2->UseVisualStyleBackColor = true;
			this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
			// 
			// button3
			// 
			this->button3->Location = System::Drawing::Point(450, 440);
			this->button3->Margin = System::Windows::Forms::Padding(5);
			this->button3->Name = L"button3";
			this->button3->Size = System::Drawing::Size(122, 35);
			this->button3->TabIndex = 2;
			this->button3->Text = L"Clear";
			this->button3->UseVisualStyleBackColor = true;
			this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click);
			// 
			// Form1
			// 
			this->AutoScaleDimensions = System::Drawing::SizeF(13, 23);
			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
			this->ClientSize = System::Drawing::Size(668, 522);
			this->Controls->Add(this->button3);
			this->Controls->Add(this->button2);
			this->Controls->Add(this->button1);
			this->Font = (gcnew System::Drawing::Font(L"新細明體", 13.8F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(136)));
			this->Margin = System::Windows::Forms::Padding(5);
			this->Name = L"Form1";
			this->Text = L"Form1";
			this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
			this->ResumeLayout(false);

		}
#pragma endregion
	private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
				 g1=this->CreateGraphics();
				 p1=gcnew Pen(Color::Red, 2);
				 p2=gcnew Pen(Color::Blue, 4);
			 }

	private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

				g1->DrawEllipse(p2,200,200,200,200);

			 }
	private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {

				g1->DrawRectangle(p1,150,70,250,80);
			 }
	private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {
				Refresh();
			 }
};
}
練習作業
#pragma once


namespace graph3 {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;

	/// <summary>
	/// Form1 的摘要
	///
	/// 警告: 如果您變更這個類別的名稱,就必須變更與這個類別所依據之所有 .resx 檔案關聯的
	///          Managed 資源編譯器工具的 'Resource File Name' 屬性。
	///          否則,這些設計工具
	///          將無法與這個表單關聯的當地語系化資源
	///          正確互動。
	/// </summary>
	public ref class Form1 : public System::Windows::Forms::Form
	{
	public:
		Form1(void)
		{
			InitializeComponent();
			//
			//TODO: 在此加入建構函式程式碼
			//
		}
		Graphics^ g1;
		Pen ^p1, ^p2;
	private: System::Windows::Forms::Button^  button1;
	private: System::Windows::Forms::Button^  button3;
	public: 
	private: System::Windows::Forms::Button^  button2;
	protected:
		/// <summary>
		/// 清除任何使用中的資源。
		/// </summary>
		~Form1()
		{
			if (components)
			{
				delete components;
			}
		}

	private:
		/// <summary>
		/// 設計工具所需的變數。
		/// </summary>
		System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
		/// <summary>
		/// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改這個方法的內容。
		///
		/// </summary>
		void InitializeComponent(void)
		{
			this->button1 = (gcnew System::Windows::Forms::Button());
			this->button2 = (gcnew System::Windows::Forms::Button());
			this->button3 = (gcnew System::Windows::Forms::Button());
			this->SuspendLayout();
			// 
			// button1
			// 
			this->button1->Location = System::Drawing::Point(93, 440);
			this->button1->Margin = System::Windows::Forms::Padding(5);
			this->button1->Name = L"button1";
			this->button1->Size = System::Drawing::Size(122, 35);
			this->button1->TabIndex = 0;
			this->button1->Text = L"Circle";
			this->button1->UseVisualStyleBackColor = true;
			this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
			// 
			// button2
			// 
			this->button2->Location = System::Drawing::Point(272, 440);
			this->button2->Margin = System::Windows::Forms::Padding(5);
			this->button2->Name = L"button2";
			this->button2->Size = System::Drawing::Size(122, 35);
			this->button2->TabIndex = 1;
			this->button2->Text = L"Retcangle";
			this->button2->UseVisualStyleBackColor = true;
			this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
			// 
			// button3
			// 
			this->button3->Location = System::Drawing::Point(450, 440);
			this->button3->Margin = System::Windows::Forms::Padding(5);
			this->button3->Name = L"button3";
			this->button3->Size = System::Drawing::Size(122, 35);
			this->button3->TabIndex = 2;
			this->button3->Text = L"Clear";
			this->button3->UseVisualStyleBackColor = true;
			this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click);
			// 
			// Form1
			// 
			this->AutoScaleDimensions = System::Drawing::SizeF(13, 23);
			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
			this->ClientSize = System::Drawing::Size(668, 522);
			this->Controls->Add(this->button3);
			this->Controls->Add(this->button2);
			this->Controls->Add(this->button1);
			this->Font = (gcnew System::Drawing::Font(L"新細明體", 13.8F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(136)));
			this->Margin = System::Windows::Forms::Padding(5);
			this->Name = L"Form1";
			this->Text = L"Form1";
			this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
			this->ResumeLayout(false);

		}
#pragma endregion
	private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
				 g1=this->CreateGraphics();
				 p1=gcnew Pen(Color::Red, 2);
				 p2=gcnew Pen(Color::Blue, 4);
			 }

	private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

				
				Pen^ myPen2 = gcnew Pen(Color::White, 3);
                SolidBrush^ redBrush2 = gcnew SolidBrush(Color::HotPink);
                int r=200,x,y;
                double deg=Math::PI/72;
                for(int i=0;i<144;i++){
                    for(int j=0;j<70000000;j++) ;                    
                    x=r*Math::Sin(deg*i);
                    y=r*Math::Cos(deg*i);
					g1->DrawEllipse(p2,240+x,150+y,150,150);
					
                  
                }

			 }
	private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {

				
				Pen^ myPen2 = gcnew Pen(Color::White, 3);
                SolidBrush^ redBrush2 = gcnew SolidBrush(Color::HotPink);
                int r=200,x,y;
                double deg=Math::PI/72;
                for(int i=0;i<144;i++){
                    for(int j=0;j<70000000;j++) ;                    
                    x=r*Math::Sin(deg*i);
                    y=r*Math::Cos(deg*i);
					g1->DrawRectangle(p1,240+x,150+y,150,70);
                  
                }
			 }
	private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {
				Refresh();
			 }
};
}

2014年5月8日 星期四

視窗程式設計5/8

資料庫 PhoneBook.mdb
Visual Studio 2008 CLR主控台應用程式
// DB1.cpp: 主要專案檔。

#include "stdafx.h"

#using <System.Dll>
#using <System.Data.Dll>

using namespace System;
using namespace System::Data;
using namespace System::Data::OleDb;

int main(array<System::String ^> ^args)
{
        // 與指定的Access 資料庫建立連接
        String^ connectionString = "provider=Microsoft.Jet.OLEDB.4.0;data source=D:\\PhoneBook.mdb;";      
        OleDbConnection^ myConn = gcnew OleDbConnection(connectionString);
        //OdbcCommand^ cmd;
         try
         {
   myConn->Open();
               //  設定取樣標準
              OleDbCommand^ myCommand = myConn->CreateCommand();
              myCommand->CommandText ="SELECT 姓名, 電話, 地址, 郵區 FROM Phone ";
              //  讀取資料
             OleDbDataReader^ myReader = myCommand->ExecuteReader();
            while (myReader->Read())
             {
                 Console::WriteLine("姓名 = " + myReader["姓名"]);
                 Console::WriteLine("電話 = " + myReader["電話"]);
                 Console::WriteLine("地址 = " + myReader["地址"]);
                 Console::WriteLine("郵區 = " + myReader["郵區"]);
   Console::WriteLine();
             }
             myConn->Close();
    myConn->Open();
              myCommand->CommandText ="INSERT INTO Phone VALUES  ('李九九', '02-11112222', '台北市星光大道100號' , '00011') " ;
                 // 新增資料
                 myCommand->ExecuteNonQuery();
                 Console::WriteLine("新增完成!");
              myCommand->CommandText ="SELECT 姓名, 電話, 地址, 郵區 FROM Phone ";
              //  讀取資料
              OleDbDataReader^ myReader2 = myCommand->ExecuteReader();
             while (myReader2->Read())
             {
                 Console::WriteLine("姓名 = " + myReader2["姓名"]);
                 Console::WriteLine("電話 = " + myReader2["電話"]);
                 Console::WriteLine("地址 = " + myReader2["地址"]);
                 Console::WriteLine("郵區 = " + myReader2["郵區"]);
   Console::WriteLine();
             }

        }
        catch (Exception^ e)
        {
            Console::WriteLine("Error: " + e);
        }

        catch (OleDbException^ ex)
        {
             Console::WriteLine(ex->ToString());
        } 
        finally
        {
             myConn->Close();
        }
}
資料庫為stdRec.mdb
A9803001 林品潔         33 96 66 75 Average=67
A9803004 王曉華         60 75 75 77 Average=71
A9803005 王智明         44 59 83 74 Average=65
A9803007 李斌           34 56 58 89 Average=59*
A9803009 陳大川         43 31 80 94 Average=62
A9803010 楊智源         38 65 49 62 Average=53*
A9803012 黃美鳳         39 99 82 51 Average=67
A9803015 鍾智勝         92 44 67 46 Average=62
A9803021 陳大川         75 88 65 64 Average=73
A9803022 朱彰文         54 79 96 80 Average=77
A9803025 黃莉茉         64 61 83 99 Average=76
A9803029 曾山國         47 78 31 37 Average=48*
A9803030 李雄山         43 58 67 99 Average=66
A9803033 林莉貞         41 38 50 34 Average=40*
A9803039 陳均安         82 55 87 62 Average=71
A9803042 李素惠         31 90 72 49 Average=60
A9803043 王小寶         62 49 94 74 Average=69
A9803048 李明白         50 30 35 32 Average=36*
A9803050 曾美蓮         99 92 78 91 Average=90
A9803052 魏一林         77 52 99 39 Average=66
請按任意鍵繼續 . . .
-------------------------------------------------------------

// DB1.cpp: 主要專案檔。

#include "stdafx.h"

#using <System.Dll>
#using <System.Data.Dll>

using namespace System;
using namespace System::Data;
using namespace System::Data::OleDb;

int main(array<System::String ^> ^args)
{
        // 與指定的Access 資料庫建立連接
  int sc;
  String^ tmp;

        String^ connectionString = "provider=Microsoft.Jet.OLEDB.4.0;data source=d:\\stdRec.mdb;";      
        OleDbConnection^ myConn = gcnew OleDbConnection(connectionString);
        //OdbcCommand^ cmd;
         try
         {
   myConn->Open();
               //  設定取樣標準
              OleDbCommand^ myCommand = myConn->CreateCommand();
              //myCommand->CommandText ="SELECT 課程A.學號,課程A.分數, 課程B.分數 FROM 課程A, 課程B WHERE 課程A.學號=課程B.學號";
     myCommand->CommandText ="SELECT 學生資料表.學號, 姓名, 課程A.分數, 課程B.分數, 課程C.分數, 課程D.分數 from 學生資料表, 課程A, 課程B, 課程C, 課程D WHERE 學生資料表.學號=課程A.學號 and 學生資料表.學號=課程B.學號 and 學生資料表.學號=課程C.學號 and 學生資料表.學號=課程D.學號";
              
     //  讀取資料
             OleDbDataReader^ myReader = myCommand->ExecuteReader();
            while (myReader->Read())
             { 
     String^ tmp;
     int sc=0;
                  Console::Write(myReader["學號"]);
      Console::Write(" " + myReader["姓名"]);
                  Console::Write("    \t" + myReader["課程A.分數"]);
                  Console::Write(" " + myReader["課程B.分數"]);
      Console::Write(" " + myReader["課程C.分數"]);
      Console::Write(" " + myReader["課程D.分數"]);
                  //Console::WriteLine("電話號碼 = " + myReader["電話號碼"]);
                  //Console::WriteLine("聯絡地址 = " + myReader["聯絡地址"]);
      tmp=myReader["課程A.分數"]->ToString();
      sc+=System::Int32::Parse(tmp);
      tmp=myReader["課程B.分數"]->ToString();
      sc+=System::Int32::Parse(tmp);
      tmp=myReader["課程C.分數"]->ToString();
      sc+=System::Int32::Parse(tmp);
      tmp=myReader["課程D.分數"]->ToString();
      sc+=System::Int32::Parse(tmp);
      sc/=4.0;

      Console::Write(" Average=" + sc);
      if(sc >= 60) 
       Console::WriteLine( " ");
      else 
       Console::WriteLine( "*");
                  // Console::WriteLine("郵區 = " + myReader["郵區"]);
      //Console::WriteLine();
             }
        }
        catch (Exception^ e)
        {
            Console::WriteLine("Error: " + e);
        }

        catch (OleDbException^ ex)
        {
             Console::WriteLine(ex->ToString());
        } 
        finally
        {
             myConn->Close();
        }
}
Visual Studio 2008 Windows form 圖片移動  計畫名稱要一致
#pragma once


namespace KeyBoard {

 using namespace System;
 using namespace System::ComponentModel;
 using namespace System::Collections;
 using namespace System::Windows::Forms;
 using namespace System::Data;
 using namespace System::Drawing;

 /// <summary>
 /// Form1 的摘要
 ///
 /// 警告: 如果您變更這個類別的名稱,就必須變更與這個類別所依據之所有 .resx 檔案關聯的
 ///          Managed 資源編譯器工具的 'Resource File Name' 屬性。
 ///          否則,這些設計工具
 ///          將無法與這個表單關聯的當地語系化資源
 ///          正確互動。
 /// </summary>
 public ref class Form1 : public System::Windows::Forms::Form
 {
 public:
  Form1(void)
  {
   InitializeComponent();
   //
   //TODO: 在此加入建構函式程式碼
   //
  }

 protected:
  /// <summary>
  /// 清除任何使用中的資源。
  /// </summary>
  ~Form1()
  {
   if (components)
   {
    delete components;
   }
  }
 private: System::Windows::Forms::PictureBox^  pictureBox1;
 protected: 

 private:
  /// <summary>
  /// 設計工具所需的變數。
  String^ state;
  /// </summary>
  System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
  /// <summary>
  /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改這個方法的內容。
     // String^ state;
  /// </summary>
 //System::ComponentModel::Container ^components;
  /// </summary>
  void InitializeComponent(void)
  {
   System::ComponentModel::ComponentResourceManager^  resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid));
   this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());
   (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox1))->BeginInit();
   this->SuspendLayout();
   // 
   // pictureBox1
   // 
   this->pictureBox1->Image = (cli::safe_cast<System::Drawing::Image^  >(resources->GetObject(L"pictureBox1.Image")));
   this->pictureBox1->Location = System::Drawing::Point(110, 53);
   this->pictureBox1->Name = L"pictureBox1";
   this->pictureBox1->Size = System::Drawing::Size(61, 56);
   this->pictureBox1->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;
   this->pictureBox1->TabIndex = 0;
   this->pictureBox1->TabStop = false;
   // 
   // Form1
   // 
   this->AutoScaleDimensions = System::Drawing::SizeF(6, 12);
   this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
   this->BackColor = System::Drawing::Color::White;
   this->ClientSize = System::Drawing::Size(290, 189);
   this->Controls->Add(this->pictureBox1);
   this->Name = L"Form1";
   this->Text = L"鍵盤按鍵";
   this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
   (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox1))->EndInit();
   this->ResumeLayout(false);

  }
#pragma endregion

 private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
     this->KeyUp += gcnew KeyEventHandler(this, &KeyBoard::Form1::OnKeyPress);
      state="Up";
    }

 public: void OnKeyPress(Object^ sender, KeyEventArgs^ e)
    {
  String^ skey = e->KeyCode.ToString();   //  取得按鍵名稱
  if (skey=="Up") {
    // 同向未碰到頂邊則向上移動
    if ((pictureBox1->Top>=10) && state=="Up") {
                        pictureBox1->Top -= 10;
    }
                else
                {
                        state = "Up";
                        pictureBox1->ImageLocation = "D:\\\ArrowU.gif";
                }
  }
  if (skey=="Down") {
    // 同向未碰到底邊則向下移動
                if ((pictureBox1->Top <=this->Height-40-10) && state == "Down")
                        pictureBox1->Top += 10;
                else
                {
                        state = "Down";
      pictureBox1->ImageLocation = "D:\\ArrowD.gif";
                }
  }
  if (skey=="Left") {
    // 同向未碰到左邊則向左移動
    if ((pictureBox1->Left >= 10) && state == "Left")
                        pictureBox1->Left -= 10;
                else
                {
                        state = "Left";
                        pictureBox1->ImageLocation = "D:\\ArrowL.gif";
                }
  }
  if (skey=="Right") {
    // 同向未碰到右邊則向右移動
                if ((pictureBox1->Left <= this->Width - 40 - 10) && state == "Right")
                        pictureBox1->Left += 10;
                else
                {
                        state = "Right";
                        pictureBox1->ImageLocation = "D:\\ArrowR.gif";
                }
  }
      }


 };
}


Visual Studio 2008 Windows form 畫矩形 計畫名稱要一致
#pragma once


namespace mouse {

 using namespace System;
 using namespace System::ComponentModel;
 using namespace System::Collections;
 using namespace System::Windows::Forms;
 using namespace System::Data;
 using namespace System::Drawing;

 /// <summary>
 /// Form1 的摘要
 ///
 /// 警告: 如果您變更這個類別的名稱,就必須變更與這個類別所依據之所有 .resx 檔案關聯的
 ///          Managed 資源編譯器工具的 'Resource File Name' 屬性。
 ///          否則,這些設計工具
 ///          將無法與這個表單關聯的當地語系化資源
 ///          正確互動。
 /// </summary>
 public ref class Form1 : public System::Windows::Forms::Form
 {
 public:
  Form1(void)
  {
   InitializeComponent();
   //
   //TODO: 在此加入建構函式程式碼
   //
  }

 protected:
  /// <summary>
  /// 清除任何使用中的資源。
  /// </summary>
  ~Form1()
  {
   if (components)
   {
    delete components;
   }
  }
 bool mouseOn;
 int x0,y0,x1,y1,w,h;
 private:
  /// <summary>
  /// 設計工具所需的變數。
  /// </summary>
  System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
  /// <summary>
  /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改這個方法的內容。
  ///
  /// </summary>
  void InitializeComponent(void)
  {
   this->SuspendLayout();
   // 
   // Form1
   // 
   this->AutoScaleDimensions = System::Drawing::SizeF(8, 15);
   this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
   this->ClientSize = System::Drawing::Size(421, 374);
   this->Name = L"Form1";
   this->Text = L"Form1";
   this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
   this->ResumeLayout(false);

  }
#pragma endregion
 private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
     this->MouseDown +=gcnew MouseEventHandler(this, &mouse::Form1::OnMouseDown);
     this->MouseUp +=gcnew MouseEventHandler(this, &mouse::Form1::OnMouseUp);
     this->MouseMove +=gcnew MouseEventHandler(this, &mouse::Form1::OnMouseMove);
     mouseOn=false;
    }
 private:  System::Void OnMouseDown(System::Object^  sender, System::Windows::Forms::MouseEventArgs^ e) {
     x0=e->X;
     y0=e->Y;
     x1=e->X;
     y1=e->Y;
     mouseOn=true;
    }
 private:  System::Void OnMouseUp(System::Object^  sender, System::Windows::Forms::MouseEventArgs^ e) {
     w=e->X-x1;
     h=e->Y-y1;
     if(w<0){
      w=w*-1;
      x0=e->X;
     }

     if(h<0){
      h=h*-1;
      y0=e->Y;
     }     
     Refresh();
     mouseOn=false;
    }
 private:  System::Void OnMouseMove(System::Object^  sender, System::Windows::Forms::MouseEventArgs^ e) {
     if( mouseOn){
      w=e->X-x1;
      h=e->Y-y1 ;
     if(w<0){
      w=w*-1;
      x0=e->X;
     }

     if(h<0){
       h=h*-1;
      y0=e->Y;
     }     
     Refresh();
     }
    }
 protected: virtual void OnPaint(PaintEventArgs^  e) override{
     Pen^ blackPen = gcnew Pen(Color::Black, 3);
     e->Graphics->DrawRectangle(blackPen,x0,y0,w,h);
    }
 };
}


2014年5月1日 星期四

視窗程式設計5/1

egles老鷹圖片在網路學園
#pragma once


namespace eagle {

 using namespace System;
 using namespace System::ComponentModel;
 using namespace System::Collections;
 using namespace System::Windows::Forms;
 using namespace System::Data;
 using namespace System::Drawing;

 /// <summary>
 /// Form1 的摘要
 ///
 /// 警告: 如果您變更這個類別的名稱,就必須變更與這個類別所依據之所有 .resx 檔案關聯的
 ///          Managed 資源編譯器工具的 'Resource File Name' 屬性。
 ///          否則,這些設計工具
 ///          將無法與這個表單關聯的當地語系化資源
 ///          正確互動。
 /// </summary>
 public ref class Form1 : public System::Windows::Forms::Form
 {
 public:
  Form1(void)
  {
   InitializeComponent();
   //
   //TODO: 在此加入建構函式程式碼
   //
  }

 protected:
  /// <summary>
  /// 清除任何使用中的資源。
  /// </summary>
  ~Form1()
  {
   if (components)
   {
    delete components;
   }
  }
  int times;
 private: System::Windows::Forms::Button^  button1;
 protected: 
 private: System::Windows::Forms::PictureBox^  pictureBox1;
 private: System::Windows::Forms::Button^  button2;
 private: System::Windows::Forms::Timer^  timer1;
 private: System::Windows::Forms::Button^  button3;
 private: System::ComponentModel::IContainer^  components;

 private:
  /// <summary>
  /// 設計工具所需的變數。
  /// </summary>


#pragma region Windows Form Designer generated code
  /// <summary>
  /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改這個方法的內容。
  ///
  /// </summary>
  void InitializeComponent(void)
  {
   this->components = (gcnew System::ComponentModel::Container());
   this->button1 = (gcnew System::Windows::Forms::Button());
   this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());
   this->button2 = (gcnew System::Windows::Forms::Button());
   this->timer1 = (gcnew System::Windows::Forms::Timer(this->components));
   this->button3 = (gcnew System::Windows::Forms::Button());
   (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox1))->BeginInit();
   this->SuspendLayout();
   // 
   // button1
   // 
   this->button1->Location = System::Drawing::Point(12, 22);
   this->button1->Name = L"button1";
   this->button1->Size = System::Drawing::Size(75, 23);
   this->button1->TabIndex = 0;
   this->button1->Text = L"Stop";
   this->button1->UseVisualStyleBackColor = true;
   this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
   // 
   // pictureBox1
   // 
   this->pictureBox1->Location = System::Drawing::Point(22, 65);
   this->pictureBox1->Name = L"pictureBox1";
   this->pictureBox1->Size = System::Drawing::Size(173, 150);
   this->pictureBox1->TabIndex = 1;
   this->pictureBox1->TabStop = false;
   this->pictureBox1->Click += gcnew System::EventHandler(this, &Form1::pictureBox1_Click);
   // 
   // button2
   // 
   this->button2->Location = System::Drawing::Point(174, 22);
   this->button2->Name = L"button2";
   this->button2->Size = System::Drawing::Size(75, 23);
   this->button2->TabIndex = 2;
   this->button2->Text = L"Exit";
   this->button2->UseVisualStyleBackColor = true;
   this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
   // 
   // timer1
   // 
   this->timer1->Tick += gcnew System::EventHandler(this, &Form1::timer1_Tick);
   // 
   // button3
   // 
   this->button3->Location = System::Drawing::Point(93, 22);
   this->button3->Name = L"button3";
   this->button3->Size = System::Drawing::Size(75, 23);
   this->button3->TabIndex = 3;
   this->button3->Text = L"restart";
   this->button3->UseVisualStyleBackColor = true;
   this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click);
   // 
   // Form1
   // 
   this->AutoScaleDimensions = System::Drawing::SizeF(6, 12);
   this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
   this->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(192)), static_cast<System::Int32>(static_cast<System::Byte>(255)), 
    static_cast<System::Int32>(static_cast<System::Byte>(255)));
   this->ClientSize = System::Drawing::Size(284, 262);
   this->Controls->Add(this->button3);
   this->Controls->Add(this->button2);
   this->Controls->Add(this->pictureBox1);
   this->Controls->Add(this->button1);
   this->Name = L"Form1";
   this->Text = L"Form1";
   this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
   (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox1))->EndInit();
   this->ResumeLayout(false);

  }
#pragma endregion
 private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e) {
     switch(times){
      case 0:
       pictureBox1->Image=Image::FromFile("D:\\Eagle2.gif");
       times=1;
       break;
      case 1:
       pictureBox1->Image=Image::FromFile("D:\\Eagle3.gif");
       times=2;
       break;
      case 2:
       pictureBox1->Image=Image::FromFile("D:\\Eagle1.gif");
       times=0;
       break;
    }
       pictureBox1->Left +=14;
       pictureBox1->Top +=4;
       pictureBox1->Height +=5;
       pictureBox1->Width +=6;
    }
 private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
     timer1->Enabled=true;
     timer1->Interval=100;
     times=0;
     Form1::Height=1024;
     Form1::Width=1024;
    }
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
    timer1->Enabled=!timer1->Enabled;
    if(timer1->Enabled==true)
     button1->Text="Start";
    else
     button1->Text="Retart";
   }
private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
    Application::Exit();
   }
private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {
    timer1->Enabled=true;
    System::Media::SoundPlayer^ so = gcnew System::Media::SoundPlayer("D:\\");
    so->Play();
   }
};
}


視窗程式設計期中考

midTest1
#include <iostream>

using namespace std;

void sort(int *dd,int num){   // Descending
 int tmp;

 for(int i=0;i<num-1;i++){
  for(int j=i+1;j<num;j++){
   if(dd[i]<dd[j]){
                    tmp=dd[i];
                    dd[i]=dd[j];
                    dd[j]=tmp;
   }
  }
 }
}
int bsearch(int* dd, int low, int high, int tk){
    int idx;

    if(low > high) return -1;
    idx=(low+high)/2;
    if(tk==dd[idx]) return idx;
    else if(tk>dd[idx]) bsearch(dd,low,idx-1,tk);
    else bsearch(dd,idx+1,high,tk);
}
int main(){
    int num, rk, tk;
    int data[]={59,83,66,54,79,63,44,99,50,88,73,47,80,75,60,39,92,95,87,69,57};

 num=sizeof(data)/4;       // number of array element
 sort(data,num);
    rk=bsearch(data,0,20,63);
    if(rk < 0) cout << "score 63 not found!!!" << endl;
    else cout << "rank of 63 is " << bsearch(data,0,20,63)+1 << endl;
    rk=bsearch(data,0,20,53);
    if(rk < 0) cout << "score 53 not found!!!" << endl;
    else cout << "rank of 53 is " << bsearch(data,0,20,53)+1 << endl;
    rk=bsearch(data,0,20,92);
    if(rk < 0) cout << "score 92 not found!!!" << endl;
    else cout << "rank of 92 is " << bsearch(data,0,20,92)+1 << endl;
    }

midTest2
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <math.h>
using namespace std;
int main(void)
{
   char txt[80],ch;
   string record;

   ifstream ifile("D:\\stdrec5.txt",ios::in);        // for input
   ofstream ofileA("D:\\reportA.txt",ios::out);       // for output1
   ofstream ofileB("D:\\reportB.txt",ios::out);       // for output2
   char porf=' ';
   string cls, id, name,sc[5],fnum;

   int isc[5],sum;
   while(!ifile.eof())
   {
       sum=0;
       fnum="";
       ifile.getline(txt,80,'\n');
       cout << txt << endl;
       record=txt;
       cls=record.substr(0,6);          // class
       id=record.substr(6,8);           // student identifier
       name=record.substr(14,10);         // student name
       for(int i=0;i<5;i++){              // get 5 course score & transfer to integer
            sc[i]=record.substr(24+i*3,3);
            isc[i]=atoi(sc[i].c_str());
            sum+=isc[i];
            if(isc[i]<60) fnum+="*";
      }
      if(cls.compare("DITM3A")==0){
            ofileA<<cls<<" "<<id<<" "<<name<<" "<<sc[0]<<" "<<sc[1]<<" "<<sc[2]<<" "<<sc[3]<<" "<<sc[4]<<"  Total="<<sum<<" Average="<<round(sum*10/5.0)/10.0<<"("<<fnum<<")"<<endl;
      }
      else{
            ofileB<<cls<<" "<<id<<" "<<name<<" "<<sc[0]<<" "<<sc[1]<<" "<<sc[2]<<" "<<sc[3]<<" "<<sc[4]<<"  Total="<<sum<<" Average="<<round(sum*10/5.0)/10.0<<"("<<fnum<<")"<<endl;
      }
   }
   ifile.close();
   ofileA.close();
   ofileB.close();

   return 0;
}

midTest3
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;

class person{
private:
    double pound,inch,kg,m;
public:
    person(double pd, double in){
        pound=pd;
        inch=in;
        toKg();
        toM();
    }
private:
    void toKg(){
        kg=pound*0.454;
    }
    void toM(){
        m=inch*0.0254;
    }
public:
    double getKg(){
        return kg;
    }
    double getM(){
        return m;
    }
};

class BMI:person{

    public:
    BMI(double pd, double in):person(pd, in){};
    public:
        short ckBMI(){
            double bmi=getBMI();
            if(bmi<18.5) return -1;
            else if(bmi<24.0) return 0;
            else if(bmi<27.0) return 1;
            else if(bmi<30.0) return 2;
            else if(bmi<35.0) return 3;
            else return 4;
        }
        double getBMI(){
            double kg,m, bmi;
            kg=person::getKg();
            m=person::getM();
            return bmi=kg/(m*m);
        }
        char* toMessage(short f){
            switch(f){
                case -1:
                    return "體重過輕";
                    break;
                case 0:
                    return "正常";
                    break;
                case 1:
                    return "過重";
                    break;
                case 2:
                    return "輕度肥胖";
                    break;
                case 3:
                    return "中度肥胖";
                    break;
                case 4:
                    return "重度肥胖";
            }
        }
};


int main(void) {
        BMI John(200, 71);
        BMI Mary(170, 69);
        BMI Ronny(192, 65);

        cout << "John BMI is " << John.getBMI()<< " Status:" << John.toMessage(John.ckBMI())<< endl;
        cout << "Mary BMI is " << Mary.getBMI()<< " Status:" << Mary.toMessage(Mary.ckBMI())<< endl;
        cout << "Ronny BMI is " << Ronny.getBMI()<< " Status:" << Ronny.toMessage(Ronny.ckBMI())<< endl;
    }

2014年4月11日 星期五

視窗程式設計期中考重點

2/20 練習
#include<iostream>
using namespace std;
int main(){
    double degreeC,degreeF;
    cout<<"Please enter the degree C!"<<endl;
    cin>>degreeC;
    degreeF=degreeC*9/5+32;
    cout<<"The degree C transform to degree F is "<<degreeF<<endl;

    cout<<"Please enter the degree F!"<<endl;
    cin>>degreeF;
    degreeC=(degreeF-32)*5/9;
    cout<<"The degree F transform to degree C is "<<degreeC<<endl;
    return 0;
}


0227練習
#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
    int n[101][200]={0};
    n[0][0]=1;
    int i,j;
    for(i=1;i<=100;i++){

        for(j=0;j<200;j++)
            n[i][j]=n[i-1][j]*i;
        for(j=0;j<200;j++)
            if(n[i][j]>=10){
                n[i][j+1]+=n[i][j]/10;
                n[i][j]%=10;
            }
        int t=199;
        while(n[i][t]==0) t--;
        cout<<i<<"!=";
        for(;t>=0;t--) cout<<n[i][t];
        cout<<endl;

    }


}

0306練習
# include <iostream>
#include <cstdlib>
#include<cmath>
using namespace std;

class CTime
{
private:
// members data
      int m_hours;
      int m_mins;
      int m_secs;
public:
// constructors
CTime(void);
CTime(int hours, int mins, int secs);

// other members function
bool setTime(int hours, int mins, int secs);
int getHours();
int getMins();
int getSecs();
void diff(CTime *time);
void print();
};
// Auxiliary Function
    bool isValidTime(int hours,int mins,int secs);
// constructors
    CTime::CTime(){
  m_hours=0;
  m_mins=0;
  m_secs=0;
      }

 CTime::CTime(int hours, int mins, int secs) {
     m_hours=hours;
        m_mins=mins;
        m_secs=secs;
      }


// member methods
    bool CTime::setTime(int hours, int mins, int secs){
  if (!isValidTime(hours, mins, secs))
   return false;
  else {
   m_hours=hours;
   m_mins=mins;
   m_secs=secs;
   return true;
  }
      }

      void CTime::diff(CTime *time){
        int sum1=m_hours*3600+m_mins*60+m_secs;
        int sum2=time->m_hours*3600+time->m_mins*60+time->m_secs;
        int sum=abs(sum2-sum1);

        int h=sum/3600;
        int m=sum%3600/60;
        int s=sum%60;
        if(h<10) cout<<0;
        cout << h << ":";
        if(m<10) cout<<0;
        cout << m << ":";
        if(s<10) cout<<0;
        cout << s << endl;
      }

      int CTime::getHours(){
  return m_hours;
      }

      int CTime::getMins(){
  return m_mins;
      }

      int CTime::getSecs(){
  return m_secs;
      }



      void CTime::print() {
        if(m_hours<10) cout<<0;
        cout << m_hours << ":";
        if(m_mins<10) cout<<0;
        cout << m_mins << ":";
        if(m_secs<10) cout<<0;
        cout << m_secs << endl;  //  ???  00:00:00
      }
      bool isValidTime(int hours,int mins,int secs)
      {
     return ( hours >=0 && hours < 24 && mins >= 0
            && mins < 60&& secs >= 0 && secs < 60 );
      }
int main(){

    CTime *time1=new CTime(12, 59, 59);
    cout << " time1>> ";
    time1->print();
    CTime *time2=new CTime(13, 0, 0);  // generate an CTime object time2 and time is 13:00:00
    cout << " time2>> ";
    time2->print();
    // add a member function into the CTime class for processing time difference
    //
    cout << " diftime>> ";
    time1->diff(time2);


}

ex0320 MS visual studio C++
// php.cpp: 主要專案檔。

#include "stdafx.h"
#include "stdlib.h"

using namespace System;
using namespace System::Text::RegularExpressions;
using namespace System::Collections;

int main(array<System::String ^> ^args)
{
 String^ input="Information and Management Department";
 String^ infix="67 + 55 * 5 - 32 / 4";

 String^ postfix="";
 Regex^ rx=gcnew Regex(" ");
 array<String^> ^a=rx->Split(infix);
 for each(String^ ss in a) Console::WriteLine(";"+ss);
 Stack^ stk1=gcnew Stack();


 for each(String^ ss in a){
  if(ss=="+" || ss=="-" ||ss=="*" ||ss=="/" ){
   if(stk1->Count ==0){
    stk1->Push(ss);
   }else{
    String^ peek=stk1->Peek()->ToString();
    if(ss=="*" ||ss=="/" ){
     if(peek=="-"||peek=="+"){
      stk1->Push(ss);
     }else{
      while(stk1->Count!=0)
       postfix=postfix+" "+stk1->Pop();
      stk1->Push(ss);
     }           
    }else{
     while(stk1->Count!=0)
       postfix=postfix+" "+stk1->Pop();
     stk1->Push(ss);
    } 
   }
  }else{
   postfix=postfix+" "+ss;
  }
 }
 while(stk1->Count!=0)
   postfix=postfix+" "+stk1->Pop();

 Console::WriteLine("postfix >>" + postfix);

 int op1,op2,op3;
 array<String^> ^b=rx->Split(postfix);
 for each(String^ ss in b){
  if(ss=="")
   ;
  else{
   if(ss=="+"){
    op1=Convert::ToInt32(stk1->Pop()->ToString());
    op2=Convert::ToInt32(stk1->Pop()->ToString());
    op3=op2+op1;
    stk1->Push(Convert::ToString(op3));
   }else if(ss=="-" ){
    op1=Convert::ToInt32(stk1->Pop()->ToString());
    op2=Convert::ToInt32(stk1->Pop()->ToString());
    op3=op2-op1;
    stk1->Push(Convert::ToString(op3));
   }else if(ss=="*"){
    op1=Convert::ToInt32(stk1->Pop()->ToString());
    op2=Convert::ToInt32(stk1->Pop()->ToString());
    op3=op2*op1;
    stk1->Push(Convert::ToString(op3));
   }else if(ss=="/"){
    op1=Convert::ToInt32(stk1->Pop()->ToString());
    op2=Convert::ToInt32(stk1->Pop()->ToString());
    op3=op2/op1;
    stk1->Push(Convert::ToString(op3));
   }else{
    stk1->Push(ss);
   }
  }
 }

 Console::WriteLine("sum >>" + stk1->Pop());

 system("pause");
    return 0;
}

0327練習A
// 0327A.cpp: 主要專案檔。

#include "stdafx.h"
#include "stdlib.h"

using namespace System;

int main(array<System::String ^> ^args)
{
  array<int> ^day=gcnew array<int>{10,9,3,7};
    try    // 監視程式碼的區塊 
    {
  int b = Convert::ToInt32("ABC") ;
         Console::WriteLine("b is {0}", b);
     }
     catch (ArithmeticException ^e)    // 取得”除以零”的錯誤
     {
          Console::WriteLine("ArithmeticException: {0}",e->Message);
      }catch (ArgumentException ^e)   
     {
          Console::WriteLine("ArgumentException: {0}",e->Message);
      }catch (FormatException ^e)    
     {
          Console::WriteLine("FormatException: {0}",e->Message);
      }catch (IndexOutOfRangeException ^e)    
     {
          Console::WriteLine("IndexOutOfRangeException: {0}",e->Message);
      }catch (Exception ^e)    // 例外狀況
     {
          Console::WriteLine("Exception: {0}",e->Message);
      }
     __finally
     {
           Console::WriteLine("End of Job");
  }
  system("pause");
    return 0;

}

0327練習B
#include <iostream>
#include <cstdlib>
#include <math.h>

using namespace std;

class interest{
private:
    char type;                  // 'S': Single rate;  'C':Compound interest
    double prin, rate=0.05;     // prin: principal; rate: bank rate
    int year;

public:
    interest(char tp);
    interest(char tp, double rt);
    int getResult(double year);
    void setPrin(double pp);
    void setRate(double rr);
};

    interest::interest(char tp){
        type = tp;
    }
    interest::interest(char tp, double rt){
        type = tp;
        rate = rt;
    }
    int interest::getResult(double yy){  // Formula of Single= p(1+nr)
                                        // Formula of Compound= P(1+r)^n
        year = yy;
        if(type=='S'){
            return round(prin*(1+year*rate));
        }else{
            return round(prin*pow((1+rate),year));
        }
    }

    void interest::setPrin(double pp){
        prin = pp;
    }
    void interest::setRate(double rr){
        rate = rr;
    }

int main(){
        double prin=2000, rate=0.05;

 interest *A = new interest('S');
 interest *B = new interest('C',rate);
        A->setPrin(prin);
        B->setPrin(prin);
    interest *D = new interest('S');
 interest *C = new interest('C',rate);
        C->setPrin(5000);
        C->setRate(0.0315);
        D->setPrin(5000);
        D->setRate(0.0315);
        cout<< "    *** Principal = " << prin << " \t **** Rate = "<< rate<<endl;   // 2000, 0.05
        cout<< "\nYears\t Bank A(Single) \tBank B(Compound) " << endl;
        cout<< "----------------------------------------------------- " << endl;
        for(int i=1;i<=10;i++) {
                //...............

                cout << "   "<<i<<"\t\t"<<A->getResult(i);
                cout << "\t\t\t"<< B->getResult(i)<< endl;
        }
 cout << "===================================================== "<<endl;
        cout<< "    *** Principal = 5000 \t **** Rate = 0.0315"<<endl;
        cout<< "\nYears\t Bank D(Single) \tBank C(Compound) " << endl;
        cout<< "----------------------------------------------------- " << endl;
        for(int i=1;i<=10;i++) {
                //...............

                cout << "   "<<i<<"\t\t"<<D->getResult(i);
                cout << "\t\t\t"<< C->getResult(i)<< endl;
        }
}

0410練習
A9803002 Alexis     73 81 54 66 avg:66
A9803006 Matthew    98 87 74 83 avg:84
A9803008 Aiden      83 77 82 72 avg:78
A9803011 Chrimetor  53 53 46 55 avg:51 *
A9803017 Addisory   83 88 74 57 avg:73
A9803019 Chritopher 77 83 71 88 avg:79
A9803020 Mason      63 69 88 90 avg:79
A9803023 Addison    95 97 94 82 avg:91
A9803028 Joshua     43 52 60 55 avg:53 *
A9803029 Andrew     71 79 64 72 avg:70
A9803030 Elizabeth  63 61 58 51 avg:57 *
// test.cpp: 主要專案檔。

#include "stdafx.h"
#include "string.h"
#include "stdio.h"

using namespace System;
using namespace System::IO;

int main(array<System::String ^> ^args)
{
 try {
  String^ fid2="d:\\stdrec1.txt";
  if(!File::Exists(fid2)){
   Console::WriteLine(L" File does not exists!!");
   return 0;
  }
  String^ fid="d:\\report.txt";
  if(File::Exists(fid)){
   Console::WriteLine(L" File already exists!!");
   File::Delete(fid);
   return 0;
  }
  StreamWriter^ sw=File::CreateText(fid);
  StreamReader^ sr=gcnew StreamReader(fid2);
  
  String ^line, ^sid, ^sname, ^sc1, ^sc2, ^sc3, ^sc4;

  while((line = sr->ReadLine()) != nullptr){
   sid=line->Substring(0,8);
   sname=line->Substring(8,10);
   sc1=line->Substring(19,2);
   sc2=line->Substring(22,2);
   sc3=line->Substring(25,2);
   sc4=line->Substring(28);
   int avg=Convert::ToDouble(sc1)*0.2+Convert::ToDouble(sc2)*0.2+Convert::ToDouble(sc3)*0.3+Convert::ToDouble(sc4)*0.3;
   String ^fail=" ";
   if(avg < 60) fail="*";
   Console::WriteLine("{0} {1} {2} {3} {4} {5} avg:{6} {7}",sid,sname,sc1,sc2,sc3,sc4,avg,fail);
      
   sw->WriteLine("{0} {1} {2} {3} {4} {5} avg:{6} {7}",sid,sname,sc1,sc2,sc3,sc4,avg,fail); 
  }
  sr->Close();
  sw->Close();
 }
 catch(Exception^ e){
  Console::WriteLine("The file can't be read: {0}",e->Message);
 }
    return 0;
}
0417檔案輸出輸入
 ifstream (檔案輸入)、ofstream (檔案輸出) 以及 fstream (檔案輸出入)
※檔案的開啟與關閉
開啟檔案
檔案物件.open(“檔案名稱”,ios::開啟模式);
可供選擇的開啟模式

  • ios::app 開啟可供附加資料的檔案
  • ios::in 開啟可供讀取資料的檔案
  • ios::out 開啟可供寫入資料的檔案
  • ios::trunc 若檔案已存在,先刪除它,再開啟
  • ios::binary 開啟二進位的輸入/輸出檔案

關閉檔案
檔案物件.close();
※文字檔的處理
將資料寫入文字檔
將資料附加到已存在的文字檔
從文字檔案讀取資料
get()、getline()、put()
利用 put() 將字串寫入檔案
文字檔的拷貝與讀取
//從檔案內讀取一個字元,並把它寫入 ch 字元變數
檔案物件.get(ch);
//從檔案內最多讀取 N-1 個字元,或是讀取到 \n
//並把它存放到字串 str 中
檔案物件.getline(str, N, ’\n’);
//將ch字元變數的值寫入檔案內
檔案物件.put(ch);
prog18_1
//prog18_1, 將資料寫入文字檔  
#include <fstream>   // 載入fstream標頭檔
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void)
{
   ofstream ofile("c:\\donkey.txt",ios::out);  // 建立ofile物件
   
   if(ofile.is_open())                         // 測試檔案是否被開啟
   {
      ofile << "我有一隻小毛驢" << endl;       // 將字串寫入檔案
      ofile << "我從來也不騎" << endl;         // 將字串寫入檔案       
      cout << "已將字串寫入檔案..." << endl; 
   }
   else 
      cout << "檔案開啟失敗..."  << endl; 
   
   ofile.close();                              // 關閉檔案
  
   system("pause");
   return 0;
}

prog18_2
//prog18_2, 將資料附加到已存在的文字檔  
#include <fstream>                              // 載入fstream標頭檔
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void)
{
   ofstream afile("c:\\donkey.txt",ios::app);   // 建立afile物件 從檔案結尾寫入(輸出)資料
   
   if(afile.is_open())                          // 測試檔案是否被開啟
   {
      afile << "有一天我心血來潮騎著去趕集";    // 將字串寫入檔案

      cout << "已將字串附加到檔案了..." <<endl; 
   }
   else 
      cout << "檔案開啟失敗..."  << endl; 
   
   afile.close();                               // 關閉檔案
  
   system("pause");
   return 0;
}

prog18_3
//prog18_3, 從檔案讀入資料 
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void)
{
   char txt[40];       // 建立字元陣列,用來接收字串
   ifstream ifile("c:\\donkey.txt",ios::in);
   
   while(!ifile.eof())      // 判別是否讀到檔案的尾端
   {
      ifile >> txt;         // 將檔案內容寫入字元陣列
      cout << txt << endl; 
   }
   
   ifile.close();       // 關閉檔案
   system("pause");
   return 0;
}

prog18_4
//prog18_4, 利用put()將字串寫入檔案
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void)
{
   char txt[]="Welcome to the C++ world" ;     // 建立字元陣列
   int i=0;

   ofstream ofile("F:\\welcome.txt",ios::out);

   while(txt[i] != '\0')                      // 判別txt[i]字元是否為字串尾端
   {
      ofile.put(txt[i]);                   // 將字元txt[i]寫入檔案
      i++;
   }
   cout << "字串寫入完成..." << endl;
   ofile.close();

   system("pause");
   return 0;
}

prog18_5
//prog18_5, 文字檔的拷貝與讀取
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void)
{
   char txt[80],ch;

   ifstream ifile1("c:\\welcome.txt",ios::in);
   ofstream ofile("c:\\welcome2.txt",ios::out);

   while(ifile1.get(ch))                       // 判別是否讀到檔案的尾端
      ofile.put(ch);
   cout << "拷貝完成..." << endl;
   ifile1.close();
   ofile.close();
   
   ifstream ifile2("c:\\welcome2.txt",ios::in);
   while(!ifile2.eof())                        // 判別是否讀到檔案的尾端
   {
      ifile2.getline(txt,80,'\n');
      cout << txt << endl;
   }
   ifile2.close();

   system("pause");
   return 0;
}

prog18_6
//prog18_6, 二進位檔寫入的練習 
#include <fstream>   // 載入fstream標頭檔
#include <iostream>
#include <cstdlib>
#include <cmath>   // 載入數學函數庫cmath
using namespace std;
int main(void)
{
   double num;  
   ofstream ofile("c:\\binary.dat",ios::binary);    // 開啟可供寫入的二進位檔
   
   for(int i=1;i<=5;i++)
   {
      num=sqrt((double)i);  // 將i轉成double,再計算sqrt(i)
      ofile.write((char*)&num,sizeof(num));         // 將num寫入二進位檔
   }
   cout << "已將資料寫入二進位檔了..." << endl;
   
   ofile.close();        // 關閉檔案
   
   system("pause");
   return 0;
}

prog18_7
//prog18_7, 讀取二進位檔
#include <fstream>                        // 載入fstream標頭檔
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void)
{
   ifstream ifile("c:\\binary.dat",ios::binary);  // 開啟二進位檔
   double num;
   
   for(int i=1;i<=5;i++)
   {
      ifile.read((char*) &num,sizeof(num));       // 從二進位檔中讀取資料
      cout << num << endl;                      // 印出讀取的內容
   }   
   cout << "二進位檔已被讀取了..." << endl; 
   
   ifile.close();                           // 關閉檔案  
   system("pause");
   return 0;
}

prog18_8
//prog18_8, 將物件的內容寫入二進位檔  
#include <fstream>               // 載入fstream標頭檔
#include <iostream>
#include <cstdlib>
using namespace std;
class CStudent
{
   protected:
      char name[40];
      int age;
   public:
      void get_data(void)          // 成員函數,用來輸入物件的資料成員
      {
         cout << "Enter name: "; cin >> name;
         cout << "Enter age: "; cin >> age;  
      }
      void show_data(void)         // 成員函數,用來顯示物件的資料成員
      {
         cout << "Name: " << name << endl;
         cout << "Age: "  << age << endl;  
      }            
};

int main(void)
{
   CStudent st;    
   st.get_data();
      
   ofstream ofile("c:\\student.dat",ios::binary);
   
   ofile.write((char*) &st,sizeof(st));          // 將物件寫入二進位檔中
   cout << "資料已寫入檔案中..." << endl;
   
   ofile.close();              // 關閉檔案
   system("pause");
   return 0;
}

prog18_9
//prog18_9, 從二進位檔裡讀取物件的資料
#include <fstream>      // 載入fstream標頭檔
#include <iostream>
#include <cstdlib>
using namespace std;
class CStudent
{
   protected:
      char name[40];
      int age;
   public:
      void get_data(void)     // 成員函數,用來輸入物件的資料成員
      {
         cout << "Enter name: "; cin >> name;
         cout << "Enter age: ";  cin >> age;  
      }
      void show_data(void)  // 成員函數,用來顯示物件的資料成員
      {
         cout << "Name: " << name << endl;
         cout << "Age: "  << age << endl;  
      }            
};

int main(void)
{
   CStudent st;
      
   ifstream ifile("c:\\student.dat",ios::binary);
   
   ifile.read((char*) &st,sizeof(st));
   st.show_data();
   
   ifile.close();         // 關閉檔案

   system("pause");
   return 0;
}

0417作業
       Report for Ansi C++
A9803002 Alexis     73 81 54 66 avg: 66
A9803006 Matthew    98 87 74 83 avg: 84
A9803008 Aiden      83 77 82 72 avg: 78
A9803011 Chrimetor  53 53 46 55 avg: 51*
A9803017 Addisory   83 88 74 57 avg: 73
A9803019 Chritopher 77 83 71 88 avg: 79
A9803020 Mason      63 69 88 90 avg: 79
A9803023 Addison    95 97 94 82 avg: 91
A9803028 Joshua     43 52 60 55 avg: 53*
A9803029 Andrew     71 79 64 72 avg: 70
A9803030 Elizabeth  63 61 58 51 avg: 57*

使用C的atoi()與atof()。
先利用c_str()轉成C string,再用atoi()與atof()。
double n = atof(s.c_str());
int n = atoi(s.c_str());

//prog18_5, 文字檔的拷貝與讀取
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;

int main(void)
{
    char txt[80],ch;
    string rec;

    ifstream ifile("D:\\stdRec1.txt",ios::in);
    ofstream ofile("D:\\report2.txt",ios::out);

    if(ofile.is_open()){
         ofile<< "       Report for Ansi C++ "<< endl;
        while(ifile.getline(txt,sizeof(txt),'\n')){
            rec = txt;
            string id = rec.substr(0,8);
            string name = rec.substr(8,10);
            double sc1 = atof(rec.substr(18,3).c_str());
            double sc2 = atof(rec.substr(21,3).c_str());
            double sc3 = atof(rec.substr(24,3).c_str());
            double sc4 = atof(rec.substr(27,3).c_str());
            //cout<<id<<" "<<name<<" "<<sc1<<" "<<sc2<<" "<<sc3<<" "<<sc4<<" "<<endl;
            int avg = sc1*0.2+sc2*0.2+sc3*0.3+sc4*0.3;
            string fail=" ";
            if(avg < 60) fail="*";
            ofile<<id<<" "<<name<<" "<<sc1<<" "<<sc2<<" "<<sc3<<" "<<sc4<<" avg: "<<avg<<fail<<endl;
        }
        ifile.close();
        ofile.close();
    }
    system("pause");
    return 0;
}


2013年12月27日 星期五

網際網路程式設計期末考-參考答案

DeltaLeft-cheat

.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DeltaAlpha.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style type="text/css">
        td
        {
            text-align: center;
        }
        .style1
        {
            height: 20px;
        }
    </style>
</head>
<body>
    <h1>
        繪製三角形
    </h1>
    <form id="form1" runat="server">
    <div>
        請輸入三角形高度:
        <asp:TextBox ID="txtHeight" runat="server" Width="30px"></asp:TextBox>
        <asp:DropDownList ID="ddlType" runat="server">
            <asp:ListItem Value="L">正左</asp:ListItem>
            <asp:ListItem Value="R">正右</asp:ListItem>
            <asp:ListItem Value="C">等腰</asp:ListItem>
            <asp:ListItem Value="RL">倒左</asp:ListItem>
            <asp:ListItem Value="RR">倒右</asp:ListItem>
            <asp:ListItem Value="RC">倒等腰</asp:ListItem>
            <asp:ListItem Value="2C">背對背等腰</asp:ListItem>
            <asp:ListItem Value="4C">蝴蝶</asp:ListItem>
        </asp:DropDownList>
        <asp:Button ID="btnSubmit" runat="server" Text="確定" OnClick="btnSubmit_Click" />
    </div>
    <table>
        <tr>
            <td>
                <asp:Literal ID="ltDelta" runat="server"></asp:Literal>
            </td>
            <td>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td>
                <asp:Literal ID="ltDelta2" runat="server"></asp:Literal>
            </td>
        </tr>
        <tr>
            <td class="style1">
                <asp:Literal ID="ltDelta3" runat="server"></asp:Literal>
            </td>
            <td class="style1">
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td class="style1">
                <asp:Literal ID="ltDelta4" runat="server"></asp:Literal>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

namespace DeltaAlpha
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        private char[] symbols = new char[26 + 26 + 10];
        private static int symbolIndex = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            txtHeight.Focus();
            initSymbols();
        }

        private void initSymbols()
        {
            char c = '1';
            int i = 0;
            while (c != '9')
            {
                symbols[i++] = c;
                c = (char)(c + 1);
            }
            symbols[i++] = '0';
            c = 'A';
            while (c != 'Z')
            {
                symbols[i++] = c;
                c = (char)(c + 1);
            }
            c = 'a';
            while (c != 'z')
            {
                symbols[i++] = c;
                c = (char)(c + 1);
            }
        }

        private void resetSymbolIndex()
        {
            symbolIndex = 0;
        }

        private string currentSymbol()
        {
            //return symbols[symbolIndex];
            return "<img src='images/skull.png' alt='' />";
        }

        private char nextSymbol()
        {
            char c = symbols[symbolIndex];
            symbolIndex = (symbolIndex + 1) % symbols.Length;
            return c;
        }

        /// <summary>
        /// 偏左的直角三角形,第 i 層印 i 個骷髏頭
        /// </summary>
        /// <param name="h">三角形高度</param>
        /// <returns>HTML</returns>
        private string deltaLeft(int h)
        {
            resetSymbolIndex();
            StringBuilder sb = new StringBuilder();
            sb.Append("<table border='0'>");
            for (int i = 1; i <= h; i++)
            {
                sb.Append("<tr>");
                for (int j = 1; j <= i; j++)
                {
                    sb.Append("<td>" + currentSymbol() + "</td>");
                }
                sb.Append("</tr>"); nextSymbol();
            }
            sb.Append("</table>");
            return sb.ToString();
        }

        /// <summary>
        /// 偏右的直角三角形,第 i 層印 (h-i) 個空格和 i 個骷髏頭
        /// </summary>
        /// <param name="h">三角形高度</param>
        /// <returns>HTML</returns>
        private string deltaRight(int h)
        {
            resetSymbolIndex();
            StringBuilder sb = new StringBuilder();
            sb.Append("<table border='0'>");
            for (int i = 1; i <= h; i++)
            {
                sb.Append("<tr>");
                for (int j = 1; j <= (h - i); j++)
                {
                    sb.Append("<td>&nbsp;</td>");
                }
                for (int j = 1; j <= i; j++)
                {
                    sb.Append("<td>" + currentSymbol() + "</td>");
                }
                sb.Append("</tr>"); nextSymbol();
            }
            sb.Append("</table>");
            return sb.ToString();
        }

        /// <summary>
        /// 正的等腰三角形,第 i 層印 (h-i) 個空格和 (2i-1) 個骷髏頭
        /// </summary>
        /// <param name="h">三角形高度</param>
        /// <returns>HTML</returns>
        private string deltaIsosceles(int h)
        {
            resetSymbolIndex();
            StringBuilder sb = new StringBuilder();
            sb.Append("<table border='0'>");
            for (int i = 1; i <= h; i++)
            {
                sb.Append("<tr>");
                for (int j = 1; j <= (h - i); j++)
                {
                    sb.Append("<td>&nbsp;</td>");
                }
                for (int j = 1; j <= (2 * i - 1); j++)
                {
                    sb.Append("<td>" + currentSymbol() + "</td>");
                }
                sb.Append("</tr>"); nextSymbol();
            }
            sb.Append("</table>");
            return sb.ToString();
        }


        /// <summary>
        /// 倒的偏左的直角三角形,第 i 層印 (h-i+1) 個骷髏頭
        /// </summary>
        /// <param name="h">三角形高度</param>
        /// <returns>HTML</returns>
        private string deltaDownLeft(int h)
        {
            resetSymbolIndex();
            StringBuilder sb = new StringBuilder();
            sb.Append("<table border='0'>");
            for (int i = 1; i <= h; i++)
            {
                sb.Append("<tr>");
                for (int j = 1; j <= (h - i + 1); j++)
                {
                    sb.Append("<td>" + currentSymbol() + "</td>");
                }
                sb.Append("</tr>"); nextSymbol();
            }
            sb.Append("</table>");
            return sb.ToString();
        }

        /// <summary>
        /// 倒的偏右的直角三角形,第 i 層印 (i-1) 個空格和 (h-i+1) 個骷髏頭
        /// </summary>
        /// <param name="h">三角形高度</param>
        /// <returns>HTML</returns>
        private string deltaDownRight(int h)
        {
            resetSymbolIndex();
            StringBuilder sb = new StringBuilder();
            sb.Append("<table border='0'>");
            for (int i = 1; i <= h; i++)
            {
                sb.Append("<tr>");
                for (int j = 1; j <= (i - 1); j++)
                {
                    sb.Append("<td>&nbsp;</td>");
                }
                for (int j = 1; j <= (h - i + 1); j++)
                {
                    sb.Append("<td>" + currentSymbol() + "</td>");
                }
                sb.Append("</tr>"); nextSymbol();
            }
            sb.Append("</table>");
            return sb.ToString();
        }

        /// <summary>
        /// 倒的等腰三角形,第 i 層印 (i-1) 個空格和 2(h-i)+1 個骷髏頭
        /// </summary>
        /// <param name="h">三角形高度</param>
        /// <returns>HTML</returns>
        private string deltaDownIsosceles(int h)
        {
            resetSymbolIndex();
            StringBuilder sb = new StringBuilder();
            sb.Append("<table border='0'>");
            for (int i = 1; i <= h; i++)
            {
                sb.Append("<tr>");
                for (int j = 1; j <= (i - 1); j++)
                {
                    sb.Append("<td>&nbsp;</td>");
                }
                for (int j = 1; j <= (2 * (h - i) + 1); j++)
                {
                    sb.Append("<td>" + currentSymbol() + "</td>");
                }
                sb.Append("</tr>"); nextSymbol();
            }
            sb.Append("</table>");
            return sb.ToString();
        }

        /// <summary>
        /// 背對背等腰三角形,第 i 層印 (h-i) 個空格和 2i 個骷髏頭
        /// </summary>
        /// <param name="h">三角形高度</param>
        /// <returns>HTML</returns>
        private string delta2Isosceles(int h)
        {
            resetSymbolIndex();
            StringBuilder sb = new StringBuilder();
            sb.Append("<table border='0'>");
            for (int i = 1; i <= h; i++)
            {
                sb.Append("<tr>");
                for (int j = 1; j <= (h - i); j++)
                {
                    sb.Append("<td>&nbsp;</td>");
                }
                for (int j = 1; j <= 2 * i; j++)
                {
                    sb.Append("<td>" + currentSymbol() + "</td>");
                }
                sb.Append("</tr>"); nextSymbol();
            }
            sb.Append("</table>");
            return sb.ToString();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            int h = int.Parse(txtHeight.Text);
            string type = ddlType.SelectedValue;
            ltDelta.Text = ltDelta2.Text = ltDelta3.Text = ltDelta4.Text = "";
            if (type.Equals("L"))
                ltDelta.Text = deltaLeft(h);
            else if (type.Equals("R"))
                ltDelta.Text = deltaRight(h);
            else if (type.Equals("C"))
                ltDelta.Text = deltaIsosceles(h);
            else if (type.Equals("RL"))
                ltDelta.Text = deltaDownLeft(h);
            else if (type.Equals("RR"))
                ltDelta.Text = deltaDownRight(h);
            else if (type.Equals("RC"))
                ltDelta.Text = deltaDownIsosceles(h);
            else if (type.Equals("2C"))
            {
                ltDelta.Text = deltaDownRight(h);
                ltDelta2.Text = deltaDownLeft(h);
            }
            else if (type.Equals("4C"))
            {
                ltDelta.Text = deltaDownRight(h);
                ltDelta2.Text = deltaDownLeft(h);
                ltDelta3.Text = deltaRight(h);
                ltDelta4.Text = deltaLeft(h);
            }
            txtHeight.Focus();
        }
    }
}
GCD-OK

.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="GCD.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>兩正整數的最大公因數與最小公倍數</title>
    <style type="text/css">
        div
        {
            text-align:center;          
            }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>兩正整數的最大公因數與最小公倍數</h1>  
    <hr />  

        <br />
        <asp:Label ID="Label1" runat="server" Text="第一正整數N: "></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="TextBox1" ErrorMessage="請輸入N">*</asp:RequiredFieldValidator>
&nbsp;<asp:RangeValidator ID="RangeValidator1" runat="server" 
            ControlToValidate="TextBox1" ErrorMessage="N值需大於0" MaximumValue="99999999" 
            MinimumValue="0" Type="Integer">*</asp:RangeValidator>
&nbsp;&nbsp;
        <asp:Label ID="Label2" runat="server" Text="第二正整數M: "></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
            ControlToValidate="TextBox2" ErrorMessage="請輸入M">*</asp:RequiredFieldValidator>
        <asp:RangeValidator ID="RangeValidator2" runat="server" 
            ControlToValidate="TextBox2" ErrorMessage="M值需大於0" MaximumValue="99999999" 
            MinimumValue="0" Type="Integer">*</asp:RangeValidator>
        <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
            HeaderText="以下資料有誤" ShowMessageBox="True" />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="送出" />
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="清除" />
        <br />
        <br />
        <asp:Literal ID="Literal1" runat="server"></asp:Literal>

    </div>
    </form>
</body>
</html>

.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GCD
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            TextBox1.Text = "";
            TextBox2.Text = "";
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            int n = int.Parse(TextBox1.Text);
            int m = int.Parse(TextBox2.Text);
            int c = 1;
            string str = n + " 與 " + m;
            int nn=n,mm=m;
            while (c>0) {
                c = nn % mm;
                nn = mm;
                mm = c;
            }
            if (nn == 1)
            {
                str += "兩數互質!<br>";
            }
            else {
                str += "最大公因數是 " + nn + "<br>";
            }
            str += "最小公倍數是 " + m * n / nn;
            Literal1.Text = str;

        }
    }
}
ListPrime-OK

.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ListPrime.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>印出小於N的質數</title>
    <style type="text/css">
        h1
        {
            text-align:center;
            }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>印出小於N的質數</h1>
        <p>&nbsp;</p>
        <hr />
        <p>
            <asp:Label ID="Label1" runat="server" Text="請輸入N值: "></asp:Label>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="送出" />
            <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="清除" />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                ControlToValidate="TextBox1" ErrorMessage="請輸入"> *</asp:RequiredFieldValidator>
            <asp:RangeValidator ID="RangeValidator1" runat="server" 
                ControlToValidate="TextBox1" ErrorMessage="須輸入大於等於2的正整數" MaximumValue="9999999" 
                MinimumValue="2" Type="Integer">*</asp:RangeValidator>
        </p>
        <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
        <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </div>
    </form>
</body>
</html>

.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ListPrime
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            TextBox1.Text = "";
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            int n = int.Parse(TextBox1.Text);
            int i, j;
            int count = 0;
            bool flag;
            string str = "比" + n + "小的質數是: ";
            if (n == 2)
            {
                Literal1.Text = "沒有比2小的質數。";
            }
            else {
                for (i = 2; i < n;i++ )
                {
                    for (j = 2, flag = true; j * j <= i &&flag; j++)
                        {
                            if (i % j == 0) flag = false;
                        }
                        if (flag==true)
                        {
                            if (count != 0)
                                str += ", ";
                            str += "" + i;
                            count++;
                        }
                }
                str += "<br>以上共計 "+ count + " 個質數。";
                Literal1.Text = str;
            }


        }
    }
}
Login-OK

.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Login.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>模擬登入畫面</title>
    <style type="text/css">
        div
        {
            text-align:center;
            margin: 1em 10%;
            background-color:Aqua;
            }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>模擬登入畫面</h1>
    <hr />
        <asp:Label ID="Label1" runat="server" Text="帳號: "></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="TextBox1" ErrorMessage="請輸入帳號"></asp:RequiredFieldValidator>
        <br />
        <asp:Label ID="Label2" runat="server" Text="密碼: "></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
            ControlToValidate="TextBox2" ErrorMessage="請輸入密碼"></asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="Button1" runat="server" Text="登入" onclick="Button1_Click" />
        &nbsp;&nbsp;&nbsp;
        <asp:Button ID="Button2" runat="server" Text="重設" onclick="Button2_Click" />
        <br />
        <asp:CompareValidator ID="CompareValidator1" runat="server" 
            ControlToCompare="TextBox2" ControlToValidate="TextBox1"></asp:CompareValidator>
    </div>
    </form>
</body>
</html>

.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Login
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            TextBox1.Text = "";
            TextBox2.Text = "";
            TextBox1.Focus();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (CompareValidator1.IsValid)
            {
                Response.Write("<script type='text/javascript'>alert('歡迎光臨');</script>");
                Response.Write("<script type='text/javascript'>self.moveTo(0,0);self.resizeTo(screen.availWidth,screen.availHeight);</script>");
                Response.Write("<script type='text/javascript'>window.location.replace('http://www.ywdeng.idv.tw')</script>");
            }
            else {
                Response.Write("<script type='text/javascript'>alert('帳號或密碼錯誤');</script>");
            }
        }
    }
}
MagicMatrix-cheat
演算法筆記 參考:http://openhome.cc/Gossip/AlgorithmGossip/OddArray.htm

.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="MagicMatrix.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>九宮格(加強版)</title>
    <style type="text/css">
.numberTextBox { text-align:center; }
</style>
</head>
<body>
    <form id="form1" runat="server">
    <div align="center">
        <h1>
            九宮格(加強版)</h1>
        <asp:Panel ID="Panel1" runat="server" HorizontalAlign="Center">
            請輸入一個大於等於 3 的奇數:
            <asp:TextBox ID="TextBox1" runat="server" CssClass="numberTextBox" Width="73px" AutoPostBack="True"
                OnTextChanged="Button1_Click"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="顯示" /><br />
            <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
            <asp:Label ID="lblSum" runat="server"></asp:Label>
        </asp:Panel>
        <asp:Panel ID="panelError" Visible="false" HorizontalAlign="center" runat="server">
            <asp:Label ID="lblMsg" runat="server"></asp:Label>
            <br />
            <asp:Button ID="btnReset" runat="server" Text="確定" OnClick="btnReset_Click" />
        </asp:Panel>
    </div>
    </form>
</body>
</html>

.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MagicMatrix
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                setFocus();
            }
        }

        private void setFocus()
        {
            this.TextBox1.Focus();
            ClientScript.RegisterStartupScript(this.GetType(),
                "selectDefault",
                "document.getElementById('" + TextBox1.ClientID + "').select();",
                true);
        }
        private int[,] makeMatrix(int n)
        {
            int[,] m = new int[n, n];
            int total = n * n;
            int digit = 1;
            int x, y;
            for (y = 0; y < n; y++)
                for (x = 0; x < n; x++)
                    m[y, x] = 0;
            x = n / 2;
            y = n - 1;
            while (digit <= total)
            {
                m[y, x] = digit;
                int nextX = (x + 1) % n;
                int nextY = (y + 1) % n;
                if (m[nextY, nextX] != 0)
                {
                    y = y - 1;
                }
                else
                {
                    x = nextX;
                    y = nextY;
                }
                digit++;
            }
            return m;
        }
        private void showMatrix(int[,] m)
        {
            Table t = new Table();
            t.HorizontalAlign = HorizontalAlign.Center;
            t.BorderStyle = BorderStyle.Solid;
            int sum = 0;
            for (int i = 0; i < m.GetLength(0); i++)
            {
                sum += m[i, 0];
                TableRow row = new TableRow();
                for (int j = 0; j < m.GetLength(1); j++)
                {
                    TableCell cell = new TableCell();
                    cell.Text = m[i, j].ToString();
                    cell.BorderStyle = BorderStyle.Solid;
                    cell.HorizontalAlign = HorizontalAlign.Center;
                    cell.VerticalAlign = VerticalAlign.Middle;
                    cell.Width = 40;
                    cell.Height = 40;
                    row.Cells.Add(cell);
                }
                t.Rows.Add(row);
            }
            lblSum.Text = "總和 = " + sum;
            this.PlaceHolder1.Controls.Clear();
            this.PlaceHolder1.Controls.Add(t);
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            lblSum.Text = "";
            try
            {
                int n = Convert.ToInt32(this.TextBox1.Text.Trim());
                if (((n & 0x1) == 1) && (n >= 3))
                {
                    int[,] matrix = makeMatrix(n);
                    showMatrix(matrix);
                    setFocus();
                }
                else
                {
                    showError("請輸入一個大於等於 3 的奇數");
                }
            }
            catch (Exception)
            {
                showError("數字格式錯誤!");
            }
        }
        private void showError(string msg)
        {
            lblMsg.Text = msg;
            this.Panel1.Visible = false;
            this.panelError.Visible = true;
        }
        protected void btnReset_Click(object sender, EventArgs e)
        {
            this.panelError.Visible = false;
            this.Panel1.Visible = true;
            setFocus();
        }
    }
}
Notes-cheat

.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Ex7_2_Notes.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>留言板範例</title>
    <style>
        #wrapper
        {
            margin: 1em 10%;
            padding: 1em;
            background-color: #FFC;
            text-align: center;
        }
        table
        {
            margin: 1em auto;
            text-align: left;
        }
        tr
        {
            vertical-align: middle;
            text-align: left;
        }
        tr.top
        {
            vertical-align: top;
        }
        th
        {
            text-align: right;
        }
        td
        {
            text-align: left;
        }
        a
        {
            text-decoration: none;
        }
        a:link
        {
            color: #FFC;
        }
        a:visited
        {
            color: #FFC;
        }
        span.redStar
        {
            font-weight: bold;
            color: Red;
        }
    </style>
    <script type="text/javascript">
        function ValidateCaptcha(sender, arg) {
            var captcha1 = document.getElementById("<%= hfCaptcha.ClientID %>");
            if (arg.Value == captcha1.value) {
                arg.IsValid = true;
            } else {
                arg.IsValid = false;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="wrapper">
        <h1>
            留言板</h1>
        <hr />
        <asp:Panel ID="panelList" runat="server" HorizontalAlign="Center">
            <asp:Button ID="btnPostNote" runat="server" Text="我要留言" OnClick="btnPostNote_Click" />
            <asp:Table ID="tblNotes" runat="server">
            </asp:Table>
        </asp:Panel>
        <asp:Panel ID="panelPost" runat="server" Visible="false" HorizontalAlign="Center">
            <table>
                <tr>
                    <th>
                        <span class="redStar">*</span> 姓名:
                    </th>
                    <td>
                        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <th>
                        <span class="redStar">*</span> 信箱:
                    </th>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server" Width="350px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <th>
                        網站:
                    </th>
                    <td>
                        <asp:TextBox ID="txtWebSite" runat="server" Width="350px"></asp:TextBox>
                    </td>
                </tr>
                <tr valign="middle">
                    <th>
                        <span class="redStar">*</span>驗證碼:
                    </th>
                    <td>
                        <asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox>
                        &nbsp;&nbsp;&nbsp;
                        <asp:Image ID="imgCaptcha" runat="server" ImageAlign="Top" ToolTip="請在驗證欄位內輸入圖中的文字" />
                        <asp:Button ID="btnCaptcha" runat="server" Text="重新產生" ToolTip="重新產生驗證碼" 
                            onclick="btnCaptcha_Click" ValidationGroup="vgCaptcha" />
                    </td>
                </tr>
                <tr class="top">
                    <th>
                        <span class="redStar">*</span> 留言:
                    </th>
                    <td rowspan="2">
                        <asp:TextBox ID="txtNote" runat="server" Rows="6" TextMode="MultiLine" Width="350px"></asp:TextBox>
                    </td>
                </tr>
                <tr class="top">
                    <th>
                        <asp:Button ID="btnSubmit" runat="server" Text="送出" OnClick="btnSubmit_Click" 
                            ValidationGroup="vgMain" /><br />
                        <asp:Button ID="btnCancel" runat="server" Text="取消" onclick="btnCancel_Click" 
                            ValidationGroup="vgCancel" />
                    </th>
                </tr>
            </table>
            <asp:HiddenField ID="hfCaptcha" runat="server" />
            <asp:RequiredFieldValidator runat="server" ID="rfvName" ControlToValidate="txtName"
                Display="None" ErrorMessage="請輸入姓名" ForeColor="Red" SetFocusOnError="True" 
                ValidationGroup="vgMain"></asp:RequiredFieldValidator>
            <asp:RequiredFieldValidator runat="server" ID="rfvEmail" ControlToValidate="txtEmail"
                ErrorMessage="請輸入 Email" ForeColor="Red" SetFocusOnError="True" 
                Display="None" ValidationGroup="vgMain"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator runat="server" ID="revEmail" ErrorMessage="請輸入正確的 Email!"
                ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="txtEmail"
                ForeColor="Red" SetFocusOnError="True" Display="None" 
                ValidationGroup="vgMain"></asp:RegularExpressionValidator>
            <asp:RegularExpressionValidator runat="server" ID="revWebSite" ErrorMessage="請輸入正確的網站 URL!"
                ValidationExpression="http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?" ControlToValidate="txtWebSite"
                ForeColor="Red" SetFocusOnError="True" Display="None" 
                ValidationGroup="vgMain"></asp:RegularExpressionValidator>
            <asp:RequiredFieldValidator runat="server" ID="rfvCaptcha" ControlToValidate="txtCaptcha"
                Display="None" ForeColor="Red" ValidationGroup="vgMain"></asp:RequiredFieldValidator>
            <asp:CustomValidator ID="cvCaptcha" runat="server" ControlToValidate="txtCaptcha"
                ClientValidationFunction="ValidateCaptcha" ErrorMessage="驗證碼不正確!" ValidateEmptyText="true"
                Display="None" ForeColor="Red" ValidationGroup="vgMain"></asp:CustomValidator>
            <asp:RequiredFieldValidator ID="rfvNote" runat="server" ControlToValidate="txtNote"
                ErrorMessage="請輸入留言" ForeColor="Red" SetFocusOnError="True" Display="None" 
                ValidationGroup="vgMain"></asp:RequiredFieldValidator>
            <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True"
                ShowSummary="False" ForeColor="Red" ValidationGroup="vgMain" />
        </asp:Panel>
    </div>
    </form>
</body>
</html>
.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;

namespace Ex7_2_Notes
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        private static string[] captchaDigits;
        private static Random random = new Random();
        private const int CAPTCHA_LEN = 6;
        private const int CAPTCHA_WIDTH = 80;
        private const int CAPTCHA_HEIGHT = 26;
        private static List<NoteItem> notesList = new List<NoteItem>();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                initCaptcha();
            }
        }

        private void refreshCaptcha()
        {
            string captcha = getCaptchaString(CAPTCHA_LEN);
            hfCaptcha.Value = captcha;
            string captchaUrl = getCaptchaImage(captcha);
            if (captchaUrl != null)
            {
                imgCaptcha.ImageUrl = captchaUrl;
            }
        }

        private void initCaptcha()
        {
            captchaDigits = new string[35];
            int i, j;
            for (i = 1; i < 10; i++)
            {
                captchaDigits[i - 1] = i.ToString();
            }
            char c = 'a';
            for (j = 1; j <= 26; i++, j++)
            {
                captchaDigits[i - 1] = c.ToString();
                c++;
            }
        }

        private string getCaptchaString(int len)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < len; i++)
            {
                int n = random.Next(captchaDigits.Length);
                sb.Append(captchaDigits[n]);
            }
            return sb.ToString();
        }

        private string getCaptchaImage(string s)
        {
            string imageUrl = "~/images/" + s + ".png";
            string serverPath = HttpContext.Current.Server.MapPath("~/images");
            string imageFileName = serverPath + "/" + s + ".png";
            Bitmap bmp = new Bitmap(CAPTCHA_WIDTH, CAPTCHA_HEIGHT, PixelFormat.Format24bppRgb);
            Graphics g = Graphics.FromImage(bmp);

            g.TextRenderingHint = TextRenderingHint.AntiAlias;
            g.Clear(Color.Orange);
            g.DrawRectangle(Pens.White, 1, 1, CAPTCHA_WIDTH - 3, CAPTCHA_HEIGHT - 3);
            g.DrawRectangle(Pens.Gray, 2, 2, CAPTCHA_WIDTH - 3, CAPTCHA_HEIGHT - 3);
            g.DrawRectangle(Pens.Black, 0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT);
            g.DrawString(s, new Font("Courier New", 12, FontStyle.Bold), SystemBrushes.WindowText, new PointF(4, 4));

            // save to file
            FileStream objFileStream = null;
            try
            {
                objFileStream = new FileStream(imageFileName, FileMode.OpenOrCreate);
                BinaryWriter objBinaryWriter = new BinaryWriter(objFileStream);
                bmp.Save(objFileStream, ImageFormat.Png);
            }
            catch (Exception ex)
            {
                imageUrl = null;
            }
            finally
            {
                if (objFileStream != null) objFileStream.Close();
                g.Dispose();
                bmp.Dispose();
            }
            return imageUrl;
        }

        protected void btnPostNote_Click(object sender, EventArgs e)
        {
            panelList.Visible = false;
            panelPost.Visible = true;
            refreshCaptcha();
            txtName.Focus();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            NoteItem item = new NoteItem(txtName.Text.Trim(), txtEmail.Text.Trim().ToLower(),
                txtWebSite.Text.Trim(), txtNote.Text.Trim());
            notesList.Add(item);
            tblNotes.Rows.Clear();
            foreach (NoteItem i in notesList)
            {
                tblNotes.Rows.Add(i.ToTableRow());
            }
            panelList.Visible = true;
            panelPost.Visible = false;
        }

        protected void btnCaptcha_Click(object sender, EventArgs e)
        {
            refreshCaptcha();
            txtCaptcha.Text = "";
            txtCaptcha.Focus();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            txtName.Text = "";
            txtEmail.Text = "";
            txtWebSite.Text = "";
            txtCaptcha.Text = "";
            txtNote.Text = "";
            panelList.Visible = true;
            panelPost.Visible = false;
        }
    }
}
ShoppingCart-cheat

.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ShopingCart.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>加入購物車</title>
</head>
<body>
    <h1 align="center">
        選購商品加入購物車</h1>
    <hr />
    <form id="form1" runat="server">
    <table align="center" border="0">
        <tr align="left">
            <th>
                產品清單
            </th>
            <td>
                &nbsp;
            </td>
            <th>
                我的購物車
            </th>
        </tr>
        <tr align="left">
            <td>
                <asp:ListBox ID="lbProduct" runat="server" Rows="12" SelectionMode="Multiple" DataTextField="ProductName"
                    DataValueField="ProductID" Width="160px" ValidationGroup="product"></asp:ListBox>
            </td>
            <td align="center">
                <asp:Button ID="btnAddAll" runat="server" Text="全部加入" 
                    onclick="btnAddAll_Click" />
                <br /><br />
                <asp:Button ID="btnAdd" runat="server" Text="加入" OnClick="btnAdd_Click" 
                    ValidationGroup="product" />
                <br /><br />
                <asp:Button ID="btnRemove" runat="server" Text="移除" OnClick="btnRemove_Click" 
                    ValidationGroup="cart" />
                <br /><br />
                <asp:Button ID="btnRemoveAll" runat="server" Text="全部移除" 
                    onclick="btnRemoveAll_Click" />
            </td>
            <td>
                <asp:ListBox ID="lbCart" runat="server" Rows="12" SelectionMode="Multiple" DataTextField="ProductName"
                    DataValueField="ProductID" Width="160px" ValidationGroup="cart"></asp:ListBox>
            </td>
        </tr>
    </table>
    <asp:RequiredFieldValidator ID="rfvProduct" runat="server" 
        ErrorMessage="請從產品清單之中至少選擇一項產品!" ControlToValidate="lbProduct" Display="None" 
        SetFocusOnError="True" ValidationGroup="product"></asp:RequiredFieldValidator>
    <asp:RequiredFieldValidator ID="rfvCart" runat="server" 
        ControlToValidate="lbCart" Display="None" ErrorMessage="請從購物車之中至少選擇一項產品!" 
        SetFocusOnError="True" ValidationGroup="cart"></asp:RequiredFieldValidator>
    <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
        ShowMessageBox="True" ShowSummary="False" ValidationGroup="product" />
    <asp:ValidationSummary ID="ValidationSummary2" runat="server" 
        ShowMessageBox="True" ShowSummary="False" ValidationGroup="cart" />
    </form>
</body>
</html>
.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ShopingCart
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        private List<ProductVO> listProd;   // 產品清單
        private List<ProductVO> listCart;   // 購物清單
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadProduct();
            }
        }

        /// <summary>
        /// 從資料庫載入產品
        /// </summary>
        private void loadProduct()
        {
            ProductDAO dao = new ProductDAO();
            listProd = dao.FindAll();
            lbProduct.DataSource = listProd;
            lbProduct.DataBind();
            Session["ProductList"] = listProd;
            listCart = new List<ProductVO>();
            Session["ShoppingCart"] = listCart;
            updateButtonState();
        }

        /// <summary>
        /// 更新按鈕的狀態
        /// </summary>
        private void updateButtonState()
        {
            btnAdd.Enabled = btnAddAll.Enabled = (listProd != null) && (listProd.Count > 0);
            btnRemove.Enabled = btnRemoveAll.Enabled = (listCart != null) && (listCart.Count > 0);
        }

        /// <summary>
        /// 移動
        /// </summary>
        /// <param name="lbSrc">來源 ListBox</param>
        /// <param name="listSrc">來源清單</param>
        /// <param name="lbDst">目的地 ListBox</param>
        /// <param name="listDst">目的地清單</param>
        private void moveSelectedItems(ListBox lbSrc, List<ProductVO> listSrc, ListBox lbDst, List<ProductVO> listDst)
        {
            List<ProductVO> xList = new List<ProductVO>();
            int[] selected = lbSrc.GetSelectedIndices();
            for (int i = 0; i < selected.Length; i++)
            {
                ProductVO vo = listSrc[selected[i]];
                xList.Add(vo);
            }
            foreach (ProductVO vo in xList)
            {
                listSrc.Remove(vo);
                listDst.Add(vo);
            }
            lbSrc.DataSource = listSrc;
            lbSrc.DataBind();
            lbDst.DataSource = listDst;
            lbDst.DataBind();
            lbDst.ClearSelection();
            foreach (ProductVO vo in xList)
            {
                for (int i = 0; i < lbDst.Items.Count; i++)
                {
                    if (lbDst.Items[i].Value.Equals(vo.ProductID))
                    {
                        lbDst.Items[i].Selected = true;
                    }
                }
            }
        }

        /// <summary>
        /// 按下加入按鈕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            listProd = (List<ProductVO>)Session["ProductList"];
            listCart = (List<ProductVO>)Session["ShoppingCart"];
            moveSelectedItems(lbProduct, listProd, lbCart, listCart);
            Session["ProductList"] = listProd;
            Session["ShoppingCart"] = listCart;
            updateButtonState();
        }

        /// <summary>
        /// 按下移除按鈕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRemove_Click(object sender, EventArgs e)
        {
            listProd = (List<ProductVO>)Session["ProductList"];
            listCart = (List<ProductVO>)Session["ShoppingCart"];
            moveSelectedItems(lbCart, listCart, lbProduct, listProd);
            Session["ProductList"] = listProd;
            Session["ShoppingCart"] = listCart;
            updateButtonState();
        }

        /// <summary>
        /// 按下全部加入按鈕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < lbProduct.Items.Count; i++)
            {
                lbProduct.Items[i].Selected = true;
            }
            btnAdd_Click(sender, e);
        }

        /// <summary>
        /// 按下全部移除按鈕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRemoveAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < lbCart.Items.Count; i++)
            {
                lbCart.Items[i].Selected = true;
            }
            btnRemove_Click(sender, e);
        }
    }
}
SqlQuery-cheat

.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="SqlQuery.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>SQL 查詢</title>
    <style type="text/css">
    #wrapper { margin:1em auto; padding:1em; width:900px; background-color:#FFC; text-align:center; }
    #input { margin: 0 auto; text-align:left; }
    #buttons, #result { margin: 1em auto;}
    table { margin: 0 auto; text-align:left; }
    tr:nth-child(odd) { background-color:#eeedfc; }
    tr:nth-child(even) { background-color:#eefcee; }
    tr:first-child { background-color:#e7e7e7; }
    td, th { margin:4px; padding:4px; }
    th { text-align:center }    
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div id="wrapper">
    <h1>SQL 指令練習</h1>
    <hr />
    <div id="input">
        <asp:TextBox ID="txtSQL" runat="server" Rows="10" TextMode="MultiLine" 
            Width="100%"></asp:TextBox>
    </div>
    <div id="buttons">
        <asp:Button ID="btnExecute" runat="server" Text="執行" OnClick="btnExecute_Click" ToolTip="執行 INSERT, UPDATE, DELETE" />
        &nbsp;
        <asp:Button ID="btnQuery" runat="server" Text="查詢" OnClick="btnQuery_Click" ToolTip="執行 SELECT" />
    </div>
    <div id="result">
    <asp:PlaceHolder ID="phResult" runat="server"></asp:PlaceHolder>
    </div>
    </div>
    </form>
</body>
</html>
.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;

namespace SqlQuery
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        private const string ConnStrDatabase1 =
@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
 
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// 顯示錯誤訊息
        /// </summary>
        /// <param name="msg"></param>
        private void showError(string msg)
        {
            phResult.Controls.Clear();
            Label b = new Label();
            b.Text = msg;
            b.ForeColor = Color.Red;
            phResult.Controls.Add(b);
        }

        /// <summary>
        /// 顯示執行結果
        /// </summary>
        /// <param name="msg"></param>
        private void showResult(string msg)
        {
            phResult.Controls.Clear();
            Label b = new Label();
            b.Text = msg;
            b.ForeColor = Color.Blue;
            phResult.Controls.Add(b);
        }

        /// <summary>
        /// 按下『執行』按鈕,執行 INSERT, UPDATE, DELETE
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExecute_Click(object sender, EventArgs e)
        {
            string sql = txtSQL.Text.Trim();
            try
            {
                using (SqlConnection conn = new SqlConnection(ConnStrDatabase1))
                {
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    conn.Open();
                    int n = cmd.ExecuteNonQuery();
                    showResult("執行結果:" + n);
                    conn.Close();
                }
            }
            catch (Exception ex)
            {
                showError(ex.ToString());
            }
        }

        /// <summary>
        /// 按下『查詢』按鈕,執行 SELECT
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            string sql = txtSQL.Text.Trim();
            try
            {
                using (SqlConnection conn = new SqlConnection(ConnStrDatabase1))
                {
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    conn.Open();
                    SqlDataAdapter ada = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    ada.Fill(ds);
                    phResult.Controls.Clear();
                    foreach (DataTable table in ds.Tables)
                    {
                        Label space = new Label();
                        space.Text = "<p>&nbsp;</p>";
                        phResult.Controls.Add(space);
                        GridView gv = new GridView();
                        gv.DataSource = table;
                        gv.DataBind();
                        phResult.Controls.Add(gv);
                    }
                }
            }
            catch (Exception ex)
            {
                showError(ex.ToString());
            }
        }
    }
}
TicTacToe-cheat

.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TicTacToe.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>井字遊戲</title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <asp:Panel ID="panelWrapper" runat="server" HorizontalAlign="center" Visible="true">
        <asp:Panel ID="panelRegister" runat="server" HorizontalAlign="center" Visible="true">
            <h1>Tic-Tac-Toe</h1>
            <hr />
            <h1>井字遊戲</h1>
            <asp:Table ID="Table1" runat="server" HorizontalAlign="Center">
                <asp:TableRow ID="TableRow1" runat="server" BackColor="Blue">
                    <asp:TableCell ID="TableCell1" runat="server" ForeColor="White">藍方姓名:</asp:TableCell>
                    <asp:TableCell ID="TableCell2" runat="server">
                        <asp:TextBox ID="txtBlue" runat="server" ValidationGroup="GameRegister" />
                    </asp:TableCell>
    </asp:TableRow>
    <asp:TableRow ID="TableRow2" runat="server" BackColor="Red">
                    <asp:TableCell ID="TableCell3" runat="server" ForeColor="White">紅方姓名:</asp:TableCell>
     <asp:TableCell ID="TableCell4" runat="server">
                        <asp:TextBox ID="txtRed" runat="server" ValidationGroup="GameRegister" />
                    </asp:TableCell>
    </asp:TableRow>
    <asp:TableRow ID="TableRow3" runat="server">
                    <asp:TableCell ID="TableCell5" ColumnSpan="2" runat="server">
                        <asp:Button ID="btnPlay" Text="開始玩" OnClick="btnPlay_Click" runat="server" 
       ValidationGroup="GameRegister" />
                        <asp:Button ID="btnReset" Text="清除" OnClick="btnPlay_Click" runat="server" />
                    </asp:TableCell>
    </asp:TableRow>
   </asp:Table>
   <asp:RequiredFieldValidator ID="rfvBlueName" runat="server" ControlToValidate="txtBlue"
                ErrorMessage="請輸入藍方姓名!" Display="None" SetFocusOnError="true" 
    ValidationGroup="GameRegister" />
            <asp:RequiredFieldValidator ID="rfvRedName" runat="server" ControlToValidate="txtRed"
                ErrorMessage="請輸入紅方姓名!" Display="None" SetFocusOnError="true" 
    ValidationGroup="GameRegister" />
            <asp:CompareValidator ID="cvNames" runat="server" ControlToValidate="txtBlue" 
    ControlToCompare="txtRed" Operator="NotEqual" ErrorMessage="藍方姓名與紅方姓名不可相同!" 
    Display="None" SetFocusOnError="True" ValidationGroup="GameRegister" />
   <asp:ValidationSummary ID="vsRegister" runat="server" ForeColor="Red"
                    ShowSummary="false" ShowMessageBox="true" ValidationGroup="GameRegister" />
            <asp:Label ID="lblMessage" runat="server" ForeColor="red"></asp:Label>
  </asp:Panel>
  <asp:Panel ID="panelPlay" runat="server" HorizontalAlign="center" Visible="false">
            <p><asp:Label ID="lblPlayRun" runat="server" Font-Size="Larger" Text="第1回合"></asp:Label></p>
   <asp:Label ID="lblHint" runat="server"></asp:Label>
   <table class="solidBorder">
                <tr>
                    <td><asp:Button ID="btn00" runat="server" OnClick="btn_Click" Width="40px" Height="40px"
       Font-Bold="True" Font-Size="Larger" CommandArgument="0,0" /></td>
                    <td><asp:Button ID="btn01" runat="server" OnClick="btn_Click" Width="40px" Height="40px"
       Font-Bold="True" Font-Size="Larger" CommandArgument="0,1" /></td>
                    <td><asp:Button ID="btn02" runat="server" OnClick="btn_Click" Width="40px" Height="40px"
       Font-Bold="True" Font-Size="Larger" CommandArgument="0,2" /></td>
                </tr>
                <tr>
                    <td><asp:Button ID="btn10" runat="server" OnClick="btn_Click" Width="40px" Height="40px"
       Font-Bold="True" Font-Size="Larger" CommandArgument="1,0" /></td>
                    <td><asp:Button ID="btn11" runat="server" OnClick="btn_Click" Width="40px" Height="40px"
       Font-Bold="True" Font-Size="Larger" CommandArgument="1,1" /></td>
                    <td><asp:Button ID="btn12" runat="server" OnClick="btn_Click" Width="40px" Height="40px"
       Font-Bold="True" Font-Size="Larger" CommandArgument="1,2" /></td>
                </tr>
                <tr>
                    <td><asp:Button ID="btn20" runat="server" OnClick="btn_Click" Width="40px" Height="40px"
       Font-Bold="True" Font-Size="Larger" CommandArgument="2,0" /></td>
                    <td><asp:Button ID="btn21" runat="server" OnClick="btn_Click" Width="40px" Height="40px"
       Font-Bold="True" Font-Size="Larger" CommandArgument="2,1" /></td>
                    <td><asp:Button ID="btn22" runat="server" OnClick="btn_Click" Width="40px" Height="40px"
       Font-Bold="True" Font-Size="Larger" CommandArgument="2,2" /></td>
                </tr>
            </table>
            <asp:Button ID="btnResult" runat="server" Text="看結果" Visible="false" 
    OnClick="btnResult_Click" />
   <br />
            <asp:Literal ID="litLog" runat="server"></asp:Literal>
  </asp:Panel>
  <asp:Panel ID="panelResult" runat="server" HorizontalAlign="center" Visible="false">
            <table>
                <tr>
                    <td class="textAlignRight">藍方勝: </td>
     <td><asp:Label ID="lblBlueWins" runat="server"></asp:Label></td>
     <td> 次 </td>
    </tr>
    <tr>
                    <td class="textAlignRight">紅方勝: </td>
     <td><asp:Label ID="lblRedWins" runat="server"></asp:Label></td>
     <td> 次 </td>
    </tr>
    <tr>
                    <td class="textAlignRight">平手: </td>
     <td><asp:Label ID="lblDue" runat="server"></asp:Label></td>
     <td> 次 </td>
    </tr>
   </table>
   <asp:Button ID="btnReplay" runat="server" Text="再玩一次" OnClick="btnReplay_Click" />
            <asp:Button ID="btnRestart" runat="server" Text="重新開始" OnClick="btnRestart_Click" />
  </asp:Panel>
    </asp:Panel>
    </form>
</body>
</html>

.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Text;

namespace TicTacToe
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        private const int MATRIX_DIM = 3; // 井字棋盤尺寸:3x3
        private int turn = 1;   // 輪到那一方? 0=藍方; 1=紅方
        private int[,] matrix = null; // 井字棋盤
        private Button[] buttons = null; // 井字棋盤中的按鈕
        private string[] symbol = { "O", "X" }; // 雙方的符號 0=藍方(O); 1=紅方(X)
        private Color[] color = { Color.Blue, Color.Red }; // 雙方顏色 0=藍方; 1=紅方
        private int blueWins = 0;   // 藍方贏的累計次數
        private int redWins = 0;    // 紅方贏的累計次數
        private int runCount = 0;   // 目前遊戲進行到第幾個回合?
        private int stepCount = 0;  // 本回合遊戲進行到第幾個步驟?
        private StringBuilder log;  // 本回合遊戲歷程紀錄

        protected void Page_Load(object sender, EventArgs e)
        {
            buttons = new Button[]{btn00,btn01,btn02,
                                   btn10,btn11,btn12,
                                   btn20,btn21,btn22};
            if (!IsPostBack)
            {
                resetAll();
            }
            else
            {
                restoreFromSession();
            }
        }


        private void resetAll()
        {
            cleanup();
            runCount = 0;
            blueWins = 0;
            redWins = 0;
            txtBlue.Text = "";
            txtRed.Text = "";
            saveToSession();
        }


        private void saveToSession()
        {
            Session["matrix"] = matrix;
            Session["turn"] = turn;
            Session["stepCount"] = stepCount;
            Session["runCount"] = runCount;
            Session["blueWins"] = blueWins;
            Session["redWins"] = redWins;
            Session["log"] = log;
        }


        private void restoreFromSession()
        {
            matrix = (int[,])Session["matrix"];
            turn = (int)Session["turn"];
            stepCount = (int)Session["stepCount"];
            runCount = (int)Session["runCount"];
            blueWins = (int)Session["blueWins"];
            redWins = (int)Session["redWins"];
            log = (StringBuilder)Session["log"];
        }


        private void cleanup()
        {

            matrix = new int[MATRIX_DIM, MATRIX_DIM];
            for (int i = 0; i < MATRIX_DIM; i++)
            {
                for (int j = 0; j < MATRIX_DIM; j++)
                {
                    matrix[i, j] = -1;
                }
            }
            for (int i = 0; i < buttons.Length; i++)
            {
                buttons[i].Text = " ";
                buttons[i].BackColor = Color.White;
                buttons[i].Enabled = true;
            }
            btnResult.Visible = false;
            turn = 1;
            stepCount = 0;
            log = new StringBuilder();
            litLog.Text = "";
        }


        private void disableCells()
        {
            for (int i = 0; i < buttons.Length; i++)
                buttons[i].Enabled = false;
        }


        private void takeTurn()
        {
            stepCount++;
            turn = 1 - turn;
            if (turn == 0)
            {
                lblHint.Text = "輪到藍方(" + txtBlue.Text + ")";
                lblHint.ForeColor = Color.Blue;
            }
            else
            {
                lblHint.Text = "輪到紅方(" + txtRed.Text + ")";
                lblHint.ForeColor = Color.Red;
            }
        }


        protected void btnPlay_Click(object sender, EventArgs e)
        {
            if (sender == btnPlay)
            {
                if (txtBlue.Text.Trim().Length < 1)
                {
                    lblMessage.Text = "請輸入藍方姓名!";
                }
                else if (txtRed.Text.Trim().Length < 1)
                {
                    lblMessage.Text = "請輸入紅方姓名!";
                }
                else
                {
                    panelRegister.Visible = false;
                    panelPlay.Visible = true;
                    takeTurn();
                    runCount = 1;
                    lblPlayRun.Text = "第 " + runCount + " 回合";
                }
            }
            else if (sender == btnReset)
            {
                resetAll();
            }
            saveToSession();
        }

        private int analysis()
        {
            for (int i = 0; i < 3; i++)
            {
                if ((matrix[i, 0] >= 0) && (matrix[i, 0] == matrix[i, 1]) &&
                    (matrix[i, 1] == matrix[i, 2]))
                {
                    return matrix[i, 0];
                }
            }
            for (int i = 0; i < 3; i++)
            {
                if ((matrix[0, i] >= 0) && (matrix[0, i] == matrix[1, i]) &&
                    (matrix[1, i] == matrix[2, i]))
                {
                    return matrix[0, i];
                }
            }
            if ((matrix[0, 0] >= 0) && (matrix[0, 0] == matrix[1, 1]) &&
                (matrix[1, 1] == matrix[2, 2]))
            {
                return matrix[0, 0];
            }
            if ((matrix[0, 2] >= 0) && (matrix[0, 2] == matrix[1, 1]) &&
                (matrix[1, 1] == matrix[2, 0]))
            {
                return matrix[0, 2];
            }
            return -1;
        }


        private void judge()
        {
            int n = analysis();
            if (n >= 0)
            {
                if (n == 0)
                {
                    lblHint.Text = "藍方勝!";
                    lblHint.ForeColor = Color.Blue;
                    blueWins++;
                }
                else
                {
                    lblHint.Text = "紅方勝!";
                    lblHint.ForeColor = Color.Red;
                    redWins++;
                }
                btnResult.Visible = true;
                disableCells();
            }
            else if (stepCount == 9)
            {
                lblHint.Text = "雙方平手!";
                btnResult.Visible = true;
                disableCells();
            }
            else
            {
                takeTurn();
                btnResult.Visible = false;
            }
        }


        private void logStep(int row, int col, Button btn)
        {
            log.Append("<br />步驟 " + stepCount + ":" +
                row + "," + col + "," +
                (turn == 0 ? "藍" : "紅") + "," +
                symbol[turn]);
            litLog.Text = log.ToString();
            matrix[row, col] = turn;
            btn.Enabled = false;
            btn.Text = symbol[matrix[row, col]];
            btn.BackColor = color[matrix[row, col]];
            judge();
        }


        protected void btn_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            if (btn == null) return;
            char[] sep = { ',' };
            string[] tokens = btn.CommandArgument.Split(sep);
            int row = int.Parse(tokens[0]);
            int col = int.Parse(tokens[1]);
            logStep(row, col, btn);
            saveToSession();
        }


        protected void btnResult_Click(object sender, EventArgs e)
        {
            panelPlay.Visible = false;
            panelResult.Visible = true;
            lblBlueWins.Text = blueWins.ToString();
            lblRedWins.Text = redWins.ToString();
            int due = runCount - (blueWins + redWins);
            lblDue.Text = due.ToString();
        }


        protected void btnReplay_Click(object sender, EventArgs e)
        {
            panelResult.Visible = false;
            panelPlay.Visible = true;
            cleanup();
            takeTurn();
            runCount++;
            lblPlayRun.Text = "第 " + runCount + " 回合";
            saveToSession();
        }

        protected void btnRestart_Click(object sender, EventArgs e)
        {
            panelResult.Visible = false;
            panelRegister.Visible = true;
            resetAll();
            saveToSession();
        }
    }
}
UnitConvert-OKhtml

.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="UnitConvert.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>單位轉換</title>
    <style type="text/css">
        div
        {
            text-align:center;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <img src="tiger.jpg" alt="" align="right"/>
    <h1>單位轉換</h1>
    <h5 style="color:Red">(小數點第2 位以下四捨五入)</h5>
    <hr />
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
            <asp:ListItem Value="0">攝氏溫度轉華氏溫度</asp:ListItem>
            <asp:ListItem Value="1">華氏溫度攝氏溫度</asp:ListItem>
        </asp:DropDownList>

        <br />
        <asp:Label ID="lb1" runat="server" Text="攝氏溫度"></asp:Label>
        <asp:TextBox ID="tb1" runat="server"></asp:TextBox>
        <asp:Label ID="lb2" runat="server" Text="→ 華氏溫度"></asp:Label>
        <asp:TextBox ID="tb2" runat="server" ReadOnly="True"></asp:TextBox>
        <br />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="tb1" ErrorMessage="RequiredFieldValidator">請輸入</asp:RequiredFieldValidator>
        <br />
        <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="tb1" 
            ErrorMessage="RangeValidator" Type="Double">請輸入數字</asp:RangeValidator>
        <br />
        <asp:Button ID="Button1" runat="server" Text="轉換" onclick="Button1_Click" />
        <br />
        <span style="color:Green">
        <asp:Literal  ID="Literal1" runat="server"></asp:Literal>
        </span>

    </div>
    </form>
</body>
</html>

.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UnitConvert
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string type = DropDownList1.SelectedValue;
            tb1.Text = "";
            tb2.Text = "";
            if (type == "0")
            {
                lb1.Text = "攝氏溫度";
                lb2.Text = "→ 華氏溫度";
                Literal1.Text = "華氏溫度 = 攝氏溫度 * 9 / 5 + 32";
            }
            else
            {
                lb1.Text = "華氏溫度";
                lb2.Text = "→ 攝氏溫度";
                Literal1.Text = "攝氏溫度 = (華氏溫度 - 32 ) * 5 / 9";
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            double temp = double.Parse(tb1.Text);
            string type = DropDownList1.SelectedValue;
            if (type == "0")
            {
                tb2.Text = "" + Math.Round(temp * 9 / 5 + 32, 2);
            }
            else {
                tb2.Text = "" + Math.Round((temp - 32) * 5 / 9, 2);
            }
        }
    }
}