winform中动态生成多行label,同时添加滚动条

设计思路大概是这样的,Form内添加一个groupBox,groupBox内添加一个panel,panel的属性AutoScroll=true,在panel内动态添加label。

原始From如下:

winform中动态生成多行label,同时添加滚动条

动态添加的代码如下:

    public partial class Form1 : Form
    {
        string[] _DataSource = new string[] { "1" ,"2222" ,"33333333333333","1","2","3","4" };
        int _LX = 25;
        int _LY = 35;
        int _LWidth = 60;
        int _LHeight = 12;
        int _LMaxChar = 8;
        int _YSpace = 20;
        int _XSpace = 10;
        int _WellCounts = 0;
        int _TbX = 0;
        int _TbWidth = 100;
        int _TbHeight = 21;
        TextBox[] textBoxes;
        public Form1()
        {
            InitializeComponent();
            InitializeForm();
        }

        private void InitializeForm()
        {
            _WellCounts = _DataSource.Length;
            Label[] labels = new Label[_WellCounts];
            textBoxes = new TextBox[_WellCounts];

            for (int i = 0; i < _WellCounts;i++)
            {
                string str = _DataSource[i];
                str = str.Length > _LMaxChar ? str.Substring(0, _LMaxChar - 1) + "..." : str;
                var l = new Label() { Text = str, AutoSize = false ,Size = new Size(_LWidth,_LHeight) };
                if (i == 0)
                {
                    l.Location = new Point(_LX,_LY);
                }
                else
                {
                    _LY = _LY + _YSpace + labels[i - 1].Size.Height;
                    l.Location = new Point(_LX,_LY);
                }
                var t = new TextBox() { Size = new Size(_TbWidth,_TbHeight) };
                this.panel1.Controls.Add(l);
                this.panel1.Controls.Add(t);
                labels[i] = l;
                textBoxes[i] = t;
            }
             
            _TbX = _LX + _LWidth + _XSpace;
            for (int i = 0;i < _WellCounts;i++)
            {
                textBoxes[i].Location = new Point(_TbX,labels[i].Location.Y - 4 );
            }
        }

    }

实现效果图:

winform中动态生成多行label,同时添加滚动条

对了,业务上还有需求就是点击关闭Form后,可以判断是否要关闭,代码如下:

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            var result = MessageBox.Show(string.Format("部分输入值不合法!\n继续退出?"),
                    "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (result == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
        } 

winform中动态生成多行label,同时添加滚动条

上一篇:C#各种委托介绍


下一篇:UWP 利用Windows.UI.Composition实现简单的放大??效果