C#如何动态的生成多个pictureBox控件,生成的pictureBox能实现不同的点击事件?

2024-11-29 15:14:51
推荐回答(3个)
回答1:

private int _NO = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            int x = 0;
            int y =  _NO * 100;
            CreatePictureBox(_NO.ToString(), x, y);
            ++_NO;
            
        }


        private bool CreatePictureBox(string name, int locX, int locY)
        {
            try
            {
                PictureBox pb = new PictureBox();
                pb.Name = name;
                pb.Location = new Point(locX, locY);
                pb.BackColor = Color.LightBlue;
                this.Controls.Add(pb);
                pb.Click += new EventHandler(PictureBox_Click);
                return true;
            }
            catch
            {
                return false;
            }

        }


        private void PictureBox_Click(object sender, EventArgs e)
        {
            PictureBox pb = (PictureBox)sender;
            MessageBox.Show(pb.Name);
        }

回答2:

        public Form1()
        {
            InitializeComponent();
            for (int i = 1; i <= 3; i++)
            {
                PictureBox p = new PictureBox();
                p.Name = "pictureBox" + i.ToString();
                p.Size = new System.Drawing.Size(50, 50);
                p.Top = 20;
                p.Left = i * 60;
                p.Click += F;
                p.BackColor = Color.Red;
                Controls.Add(p);
            }
        }

        private void F(object sender, EventArgs e)
        {
            PictureBox p = sender as PictureBox;
            MessageBox.Show(p.Name);
        }

回答3:

就别逃避 勇敢面对