C# 用陣列建立多個元件
當需要建立多個元件時(例如:200個按鈕),就可以用動態陣列的方式來生成,以方便處理一大批類似的屬性及其行動。程式碼如下,用了物件與類別的概念:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
static int x = 0, y = 0;
public Form1()
{
InitializeComponent();
Label[] labelarray = new Label;//31個label
for (int i = 0; i < 31; i++)
{
labelarray = new Label();
labelarray.AutoSize = true;
if (i % 7 == 0)
{
x++;
y = 0;
}
labelarray.Location = new System.Drawing.Point(y * 16, x * 16);
y++;
labelarray.Name = "label" + Convert.ToString(i + 1);
labelarray.Size = new System.Drawing.Size(35, 13);
labelarray.TabIndex = 0;
labelarray.Text = Convert.ToString(i + 1);
this.Controls.Add(labelarray);
}
}
}
Reference: http://tw.myblog.yahoo.com/dust512/article?mid=36
頁:
[1]