在项目中有时需要动态创建一系列的控件,并初始化它们,下面展示一个我在项目中应用到方法:

 

  

/// <summary>
        /// 创建并初始化所有的图片控件和标签控件
        /// </summary>
        private void InitialAllControls()
        {
            int iRow = 0;
            int iColumn = 0;
            //从配置文件中获取设置的行数和列数
            if (ConfigurationManager.AppSettings["RowNum"] != null && ConfigurationManager.AppSettings["Column"] != null)
            {
                iRow = int.Parse(ConfigurationManager.AppSettings["RowNum"].ToString());
                iColumn = int.Parse(ConfigurationManager.AppSettings["Column"].ToString());
            }
            string strRC = "R" + iRow.ToString() + "C" + iColumn.ToString();
            //从配置文件获取控件的参数信息成功
            if (GetControlConfigInfo(strRC))
            {
                //获取了当前画面的图片的控件的间距大小(X方向)
                int iBigImgDx = BigPicDx + BigPicSizeX;
                //获取了当前画面的图片的控件的间距大小(Y方向)
                int iBigImgDy = BigPicDy + BigPicSizeY;
                string lbName, pbbkName;

                for (int i = 1; i <= iRow; i++)
                {
                    for (int j = 1; j <= iColumn; j++)
                    {
                        lbName = string.Format("lbW{0}{1}", i, Convert.ToChar(j + 64));
                        pbbkName = string.Format("pbBK{0}{1}", i, Convert.ToChar(j + 64));
                        PictureBox pbbk = new PictureBox();
                        pbbk.Name = pbbkName;
                        pbbk.Location = new Point(FirstPicTop + (j - 1) * iBigImgDx, FirstPicLeft + (i - 1) * iBigImgDy);
                        pbbk.Size = new Size(BigPicSizeX, BigPicSizeY);
                        pbbk.BackColor = Color.Transparent;
                        pbbk.Visible = true;

                        Label lb = new Label();
                        lb.Name = lbName;
                        lb.Location = new Point(pbbk.Location.X + LabelRx, pbbk.Location.Y + LabelRy);
                        lb.Height = LabelSizeY;//配置
                        lb.Width = LabelSizeX;//配置
                        lb.TextAlign = ContentAlignment.MiddleCenter;
                        lb.Visible = true;
                        //添加控件到画面
                        this.Controls.Add(pbbk);
                        this.Controls.Add(lb);
                        //将label控件放置在画面最前端
                        lb.BringToFront();
                    }
                }
            }
        }