views:

305

answers:

3

Does anybody know how I can write "cardImage1.BorderStyle = BorderStyle.Fixed3D;" without having to explicitly declare "cardImage1"?

I'm trying to put it into a method so that I don't need to write the code to toggle between two Border Styles when a Picture Box is clicked, for every single single picture box (there are 52!)

e.g. for each box currently I would need to have the following in its _click event.

        if (cardImage1.BorderStyle == BorderStyle.None)
        {
            cardImage1.BorderStyle = BorderStyle.Fixed3D;
        }
        else
        {
            cardImage1.BorderStyle = BorderStyle.None;
        }
+4  A: 

Assuming this is in an event handler, you should cast the sender argument to PictureBox and operate upon that directly.

private void pictureBox_Click(object sender, EventArgs args)
{
    var image = (PictureBox)sender;
    if (image.BorderStyle == BorderStyle.None)
    {
        image.BorderStyle = BorderStyle.Fixed3D;
    }
    else
    {
        image.BorderStyle = BorderStyle.None;
    }
}

You would then use the same event handler on all instances of the PictureBox.

Drew Noakes
A: 

Instead of creating a handler for each picture box, you could write a single method o handle the clicks for all your picture boxes:

 protected void onClickHandler(object sender, EventArgs e)
 {
    if (((PictureBox)sender).BorderStyle == BorderStyle.None)
    {
        ((PictureBox)sender).BorderStyle = BorderStyle.Fixed3D;
    }
    else
    {
        ((PictureBox)sender).BorderStyle = BorderStyle.None;
    }

}

You could also write a loop to go over all controls on a form and attac hthe event handler to all picture boxes (if that;s possible in your case)

// in your form load event do something like this:
foreach(Control c in this.Controls)
{
    PictureBox pb = c as PictureBox;
    if(pb != null)
       pb.Click += new EventHandler(onClickHandler); // where onClickHandler is the above function
}

Of course if you have other picture boxes on the form a solution would be to put the 52 picture boxes you are interested in in a panel and then instead of iterating over all the controls in the form (this.Controls) only iterate over the controls in the panel (thePanelControl.Controls)

Miky Dinescu
Thanks a lot everyone, this particular issue is solved and he idea behind it will be used a few more times in the project.You have no idea how long I was racking my brains about this last night!
Josh King
I'm only glad I could help :)
Miky Dinescu
A: 

Create a new type MyPictureBox and handle click event. Replace all PictureBox with MyPictureBox.

class MyPictureBox : PictureBox
{
    protected void this_Click(object sender, EventArgs e)
    {
        if (this.BorderStyle == BorderStyle.None)
        {
            this.BorderStyle = BorderStyle.Fixed3D;
        }
        else
        {
            this.BorderStyle = BorderStyle.None;
        }
    }
}
Ramesh Soni