今天编程,想在窗体中动态添加控件,并且使用数组的方式来添加,但是不管怎么,都只能添加第一个,后面的无法添加,于是写了一个测试程序,还是如此,希望编程高手帮帮忙
代码如下:
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 testAddForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.button1.Text = "test";
        }        private void button1_Click(object sender, EventArgs e)
        {
            Label[] lblshow =new Label [3];
            lblshow[0] = new Label();
            lblshow[0].Text = "12";
            lblshow[1] = new Label();
            lblshow[1].Text = "34";
            lblshow[2] = new Label();
            lblshow[2].Text = "56";
            int t = 0;
            foreach (Label a in lblshow)
            {
                this.Controls.Add(a);
                a.Location = new Point(50 + t, 100);
                t += 50;
            }
            //this.Controls.AddRange(lblshow);
        }
    }
}

解决方案 »

  1.   


            private void button1_Click(object sender, EventArgs e)
            {
                Label[] lblshow = new Label[3];
                lblshow[0] = new Label();
                lblshow[0].Text = "12";
                lblshow[1] = new Label();
                lblshow[1].Text = "34";
                lblshow[2] = new Label();
                lblshow[2].Text = "56";
                int t = 0;
                foreach (Label a in lblshow)
                {              
                    this.Controls.Add(a);
                    //a.Location = new Point(50 + t, 100); 
                    a.Location = new Point(50 + t, 100+t); //试了一下,后面加个t就行 不知道为什么
                    t += 50;
                }
                //this.Controls.AddRange(lblshow);
            }
      

  2.   

    最终结果:将控件的AutoSize属性置为true;