C# 代码动态生成label,为指定label改变颜色等

  #region 初始化数据
        public void InitData(string project) {
            List projectGroupSettingList = CMMConstants.projectGroupSettingList.Where(m => m.Project.Equals(project)).ToList();  //读取数据
            foreach (var item in projectGroupSettingList) {  //循环数据
                GroupControl gp = new GroupControl(); //动态创建控件
                gp.Height = 90;               //高
                gp.Text = project + "(" + item.Divide + ")"; //text值
                gp.Dock = DockStyle.Top;  //布局,置顶
                LabelControl lb = new LabelControl();  //动态创建label
                lb.Dock = DockStyle.Fill;  //布局,全铺
                lb.Padding = new Padding(5, 12, 5, 10);  //样式
                lb.Font = new Font("微软雅黑", 15);  //字体
         lb.Text = item.Divide + " " + project + " " + CMMConstants.curProject.VoltageLevel + " " + CMMConstants.curProject.AreaType;       //text值
                lb.Tag = project + "|" + item.Divide;   // tag值
                lb.Click += new EventHandler(Label_Click);   //为每个动态创建的label创建点击事件
                gp.Controls.Add(lb);    //在 GroupControl里添加lable
                pnList.Controls.Add(gp);   //同上, pnList是另一控件
            }
        }

        private void Label_Click(object sender, EventArgs e)        //lable的点击事件
        {
            LabelControl lb = sender as LabelControl;
            foreach (GroupControl item in pnList.Controls)
            {
                foreach (LabelControl items in item.Controls)
                {
                    items.ForeColor = Color.Black;
                }
            }
            lb.ForeColor = Color.Red;
        }
        #endregion
重点:动态创建label点击事件: lb.Click += new EventHandler(Label_Click);   //为每个动态创建的label创建点击事件

你可能感兴趣的:(c#,Form)