此节课共分三节介绍:
1:先看一个学生的例子:有点问题。
如何动态添加多个控件?
我要的效果是这样
这是是程序原有的控件。
textbox textbox textbox lable
textbox textbox textbox lable
textbox textbox textbox lable
当控件不可以满足时,我要添加一行控件
textbox textbox textbox lable 换行
textbox textbox textbox lable 换行
textbox textbox textbox lable 换行
textbox textbox textbox lable 换行
textbox textbox textbox lable 换行
这样的效果怎么弄?
这是我做的代码
for (int i = 0; i < 3; i++)
{
TextBox text = new TextBox();
text.Name = string.Format("text{0}", i + 1);
text.Left = i * 120;
panel1.Controls.Add(text);
}
好啦,上边是一个学生所提到的问题。
2:接下来是重点了,很高明的手法,控件集成。
不过用的form窗体程序,原理是一样的。
(1)先看图:
(2)看一下前台UI代码


1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Text; 7 using System.Windows.Forms; 8 9 namespace generateControl 10 { 11 public partial class Form1 : Form 12 { 13 public Form1() 14 { 15 InitializeComponent(); 16 x = textBox1.Location.X; 17 y = textBox1.Location.Y; 18 } 19 20 static int x, y; 21 private void button1_Click(object sender, EventArgs e) 22 { 23 GenerateControl(); 24 } 25 26 private void GenerateControl() 27 //完全可以将三个textbox合在一起,作为GenerateControl的整个控件。。。 28 { 29 y = y + 26; 30 TextBox txt1 = new TextBox(); 31 txt1.Location = new System.Drawing.Point(x, y); 32 this.Controls.Add(txt1); 33 34 TextBox txt2 = new TextBox(); 35 txt2.Location = new System.Drawing.Point(x+107, y); 36 this.Controls.Add(txt2); 37 38 TextBox txt3 = new TextBox(); 39 txt3.Location = new System.Drawing.Point(x+214, y); 40 this.Controls.Add(txt3); 41 42 Label lbl1 = new Label(); 43 lbl1.Text = "label1"; 44 lbl1.Location = new System.Drawing.Point(x+321, y); 45 this.Controls.Add(lbl1); 46 } 47 } 48 }
接下来,是一个事例程序,大家可以下载一下。
你把panel1的AutoScroll属性设为True再看看
==============================
不行
==============================
不行