2012年8月15日 星期三

OBJ 陣列 for VC++

之前寫VC++ 都會用很笨的方式在寫, 最近發現,原來是可以用成陣列的方式在寫,


這樣的程式就可以省很多空間了


 


假設我有3個textBox 的OBJ, 那以寫的方式會用


textBox1->Text = "123";


textBox2->Text = "123";


textBox3->Text = "123";


 


如果OBJ多了一點,這樣就只好用EXCEL 來幫助寫程式了。


 


其實,還有更好的方式,用OBJ的ARRAY來寫:


以下是個範例:


 


先宣告一個GLOBAL 變數


           public ref class Form1 : public System::Windows::Forms::Form


           {


           public:


                     static array <System::Windows::Forms::TextBox^>  ^TextBoxArray = gcnew array <System::Windows::Forms::TextBox^>(10);


                     Form1(void)


                     {


                                InitializeComponent();


                                //


                                //TODO: Add the constructor code here


                                //


                     }


           }


 


接著在LOAD FORM時,載入物件


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


                                           int i;          


                                           TextBoxArray [0] = textBox3;


                                           TextBoxArray [1] = textBox4;


                                           TextBoxArray [2] = textBox5;


 


                                           for (i =0; i<3; i++)


                                           {


                                                     TextBoxArray [i]->Text = "ABC";


                                           }


                                }



最後做一個BUTTON來做測試其他功能


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


                                           int i; 


                                           TextBoxArray [0] = textBox3;


                                           TextBoxArray [1] = textBox4;


                                           TextBoxArray [2] = textBox5;


 


                                           for (i =0; i<3; i++)


                                           {


                                                     TextBoxArray [i]->Text = "kkk";


                                           }


                                }






好棒,這樣程式碼就可以乾淨許多

沒有留言:

張貼留言