Konstantin  Mokhov
Konstantin Mokhov

Reputation: 127

dynamically changing picture box

i dynamically create several picture box, and EventHandler. when user click on pictureBox, the program should delete tрis item. (the item that the user selected)

i try do

for (int i = 1; i <= sunduki; i++)
        {
            PictureBox PBObj = new PictureBox();
            PBObj.Location = new System.Drawing.Point(i * 100, 101);
            PBObj.Name = "pictureBox" + i.ToString();
            PBObj.Size = new System.Drawing.Size(108, 80);
            PBObj.TabIndex = i;
            PBObj.BackgroundImage = Image.FromFile(@"syndyk1.jpg");
            PBObj.BackgroundImageLayout = ImageLayout.Zoom;
            PBObj.Click += new System.EventHandler(pb_Click); 
            PB.Add(PBObj);
            Controls.Add(PB[PB.Count - 1]);}

and in pb_click

private void pb_Click(object sender, EventArgs e)
    { PB[this].Visible = false; }

but i have an error. (PB is the list with pictureBox)

Upvotes: 1

Views: 401

Answers (1)

Sayse
Sayse

Reputation: 43300

The sender argument will be the object that has been clicked, in this case it is the PictureBox object.

private void pb_Click(object sender, EventArgs e)
{ 
   var pb = sender as PictureBox;
   if(pb != null)
   {
       pb.Visible = false;
   }
}

Note: This doesn't delete the picture box, but makes it not visible. Controls deletion is handled by the disposal of the form.

Upvotes: 2

Related Questions