11/7第七週 自製陣列
這次程式全程將利用程式碼來建立物件,不依靠任何工具箱的功能
首先,進入表單程式的畫面
接者,在 public partial class Form1 : Form裡頭輸入下列程式碼
//System.Windows.Forms.Button Button1;
System.Windows.Forms.Button[] Buttons;
int c = 0;
然後,在表單程式( private void Form1_Load(object sender, EventArgs e))裡輸入
mybutton();
//Button1 = new System.Windows.Forms.Button();
//Button1.Location = new Point(100, 100);
//Button1.Size = new Size(100, 100);
//Button1.Text = "happy";
//Button1.BackColor = Color.Red;
//this.Controls.Add(Button1);
接者建立private void Button1_Click(object sender, System.EventArgs e)
在內部輸入
Button btn = (Button)sender;
MessageBox.Show(btn.Text);
再來,建立 private void mybutton()
在內部設計一迴圈形成按鈕的形式
以及建立size大小、text名稱、BackColor按鈕背景顏色、按鈕位置
如此一來即可單單利用程式來建立出9宮格
Ex:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
//System.Windows.Forms.Button Button1;
System.Windows.Forms.Button[] Buttons;
int c = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
mybutton();
//Button1 = new System.Windows.Forms.Button();
//Button1.Location = new Point(100, 100);
//Button1.Size = new Size(100, 100);
//Button1.Text = "happy";
//Button1.BackColor = Color.Red;
//this.Controls.Add(Button1);
}
private void Button1_Click(object sender, System.EventArgs e)
{
Button btn = (Button)sender;
MessageBox.Show(btn.Text);
}
private void mybutton()
{
//Button1 = new System.Windows.Forms.Button();
//Button1.Location = new Point(100, 100);
//Button1.Size = new Size(100, 100);
//Button1.Text = "happy";
//Button1.BackColor = Color.Red;
//this.Controls.Add(Button1);
Buttons = new System.Windows.Forms.Button[9];
for (int i = 0; i < 9; ++i)
{
Buttons[i] = new Button();
this.Controls.Add(Buttons[i]);
Buttons[i].Size = new Size(80, 80);
Buttons[i].Text = i.ToString();
Buttons[i].BackColor = Color.SkyBlue;
Buttons[i].Click += new System.EventHandler(this.Button1_Click);
if (i <= 2)
{
Buttons[i].Location = new System.Drawing.Point(100 + i * 80, 100);
}
else if (i > 2 && i <= 5)
{
Buttons[i].Location = new System.Drawing.Point(100 + (i - 3) * 80, 180);
}
else if (i > 5 && i <= 9)
{
Buttons[i].Location = new System.Drawing.Point(100 + (i - 6) * 80, 260);
}
}
}
}
}
沒有留言:
張貼留言