winform中動態生成多行label,同時添加滾動條


設計思路大概是這樣的,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;
            }
        } 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM