1.新建Winform程序
1.1拖一个 FlowLayoutPanel 控件
属性:
Dcok = Fill
1.2拖一个 Panel 控件
属性:
Margin = 10, 10, 10, 10
Visible = False
1.3拖一个 Label 控件
属性:
AutoSize = False
Size = 381, 23
TextAlign = MiddleLeft
1.4拖一个 Button 控件
以上这些是为了方便用代码的时候有个定位参考,大体了解位置
2.开始写代码
2.1新建类 TempData.cs
public class TempData
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
2.1新建类 panelyh.cs,重绘Panel的样式
代码太长就不拷贝了,后面放源代码
2.2模拟几条数据,并开始循环往 FlowLayoutPanel 中添加控件
List<TempData> list = new List<TempData>()
{
new TempData{ Id=1, Age=12, Name="zs" },
new TempData{ Id=2, Age=35, Name="ls" },
new TempData{ Id=3, Age=29, Name="zl" }
};
for (int i = 0; i < list.Count; i++)
{
flowLayoutPanel.Controls.Add(panel(list[i]));
}
2.3代码实现 Panel
private Panel Pal(TempData T)
{
panelyh pan = new panelyh();
pan.BackColor = Color.WhiteSmoke;
//添加Label
pan.Controls.Add(Lbl(T));
//添加Button
pan.Controls.Add(Btn(T));
pan.Dock = DockStyle.Top;
pan.Location = new Point(10, 10);
pan.Name = $"panel{T.Id}";
pan.Size = new Size(535, 50);
pan.BackColor = Color.White;
return pan;
}
2.4代码实现 Label
private Label Lbl(TempData T)
{
Label la = new Label
{
AutoSize = false,
Margin = new Padding(5, 10, 3, 0),
Font = new Font("微软雅黑", 10F, FontStyle.Bold),
Location = new Point(19, 11),
Name = $"lbl{T.Id}",
Size = new Size(380, 30),
TextAlign = ContentAlignment.MiddleLeft,
Text = $"Id:{T.Id} Age:{T.Age} Name:{T.Name}"
};
return la;
}
2.5代码实现 Button
private Button Btn(TempData T)
{
Button btn = new Button
{
Cursor = Cursors.Hand,
FlatStyle = FlatStyle.Flat,
Font = new Font("微软雅黑", 10F, FontStyle.Bold, GraphicsUnit.Point,
((byte)(134))),
Location = new Point(427, 10),
Margin = new Padding(0),
Name = $"btn{T.Id}",
Size = new Size(75, 30),
Text = "按钮",
TabIndex = 14,
TextAlign = ContentAlignment.MiddleCenter,
UseVisualStyleBackColor = false
};
btn.Click += delegate { btn_click(T.Id); };
btn.FlatAppearance.BorderSize = 0;
btn.FlatAppearance.MouseDownBackColor = Color.BlueViolet;
btn.FlatAppearance.MouseOverBackColor = Color.Transparent;
return btn;
}
private void btn_click(int id)
{
MessageBox.Show($"点击按钮数据Id为:{id}");
}
3.下载链接
Demo下载链接: 百度云
提取码:1234