背景:在做项目的时候可能需要根据一定数量创建某些控件并修改其属性,本文以控件label、ConboBox控件进行动态创建。
程序运行前后的的Form动态图
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace C__动态创建label和combobox控件
{
public partial class Form1 : Form
{
private List<KeyValuePair<Label, ComboBox>> dynamicControls;
public Form1()
{
dynamicControls = new List<KeyValuePair<Label, ComboBox>>();
InitializeComponent();
CreateDynamicControls();
}
private void CreateDynamicControls()
{
for(int i=0;i<6;i++)
{
Label label = new Label();
label.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
label.Text = $"相机{i + 1}";
label.Location = new System.Drawing.Point(50, 10 + i * 30);
ComboBox comboBox = new ComboBox();
comboBox.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
comboBox.Items.AddRange(new object[] { "Option 1", "Option2", "Option3" });
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox.Location = new System.Drawing.Point(150, 10 + i * 30);
comboBox.Width = 500;
this.Controls.Add(label);
this.Controls.Add(comboBox);
dynamicControls.Add(new KeyValuePair<Label, ComboBox>(label, comboBox));
}
}
//保存动态控件的文本信息
private void SaveDynamicControlText()
{
foreach (var pair in dynamicControls)
{
Console.WriteLine($"Label:{pair.Key.Text},ComboBox:{pair.Value.SelectedItem}");
}
}
}
}
源代码下载
下载链接腾讯云盘
https://share.weiyun.com/ouZjoUzF