C#动态加载控件

C#动态加载控件

本文介绍C#如何动态加载用户自定义控件。
我在这里自定义一个简单控件,该控件由lable和TextBox组成。
在这里插入图片描述

public partial class collegeConfig : UserControl
{
    public string _name = null;
    public string _number = null;
    public collegeConfig()
    {
        InitializeComponent();
    }
    public bool Initialize(string name = "电子学院",string number = "2019000001")
    {
        textBox1.Text = name;
        textBox2.Text = number;
        _name = name;
        _number = number;
        return true;
    }

    private void textBox1_TextChanged(object sender, System.EventArgs e)
    {
        _name = textBox1.Text;
    }

    private void textBox2_TextChanged(object sender, System.EventArgs e)
    {
        _number = textBox2.Text;
    }
}

其中Initialize用来更新控件的院系名称和代码,字段_name 和_number 用来获取控件当前的值,这样一个可读可写的简单控件就建立成功了,当然用属性替代字段效果更好,更加严谨,我这里偷懒就不改了。
接下来是在一个panel里面如何动态增加自定义控件。直接上代码。

public partial class addControlDynamic : Form
{
    public List<collegeConfig> _lscollegeconfig = new List<collegeConfig>();
    public addControlDynamic()
    {
        InitializeComponent();
    }
    private void butAdd_Click(object sender, EventArgs e)
    {
        collegeConfig collegeConfig = new collegeConfig();
        _lscollegeconfig.Add(collegeConfig);
        collegeConfig.Initialize("电子学院",_lscollegeconfig.Count.ToString());
        refreshwindow();
    }
    private void refreshwindow()
    {
        Point point = new Point();
        panel1.Controls.Clear();
        for (int i = 0; i < _lscollegeconfig.Count; i++)
        {
            point.Y = _lscollegeconfig[i].Height * i;
            _lscollegeconfig[i].Location = point;
            panel1.Controls.Add(_lscollegeconfig[i]);
        }
    }
    private void butDelete_Click(object sender, EventArgs e)
    {
        if (_lscollegeconfig.Count <= 0)
        {
            return;
        }
        _lscollegeconfig.RemoveAt(_lscollegeconfig.Count - 1);
        refreshwindow();
    }
}

我这里是用一个collegeConfig的List来实现功能的,增加控件就往List里面add,删除直接Remove掉,操作完List后刷新下panel即可。
效果如下:
在这里插入图片描述

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值