首页 > Windows开发 > 详细

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

时间:2019-12-25 10:57:52      阅读:128      评论:0      收藏:0      [点我收藏+]

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

原始From如下:

技术分享图片

动态添加的代码如下:

    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 );
            }
        }

    }

实现效果图:

技术分享图片

对了,业务上还有需求就是点击关闭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,同时添加滚动条

原文:https://www.cnblogs.com/yingzilovexiaoxiong/p/12095221.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!