Elfoc
Elfoc

Reputation: 3689

Change button image after clicking it

i have picturebox with picture cb.

PBr1_1.Image = new Bitmap(@"Logos\\Images\\cb.png");

I'd like to change image to cg.png and do some action when i click this image. I was trying something like that but without success:

private void PBr1_1_Click(object sender, EventArgs e)
{    
   if (PBr1_1.Image.ToString() == "cb.png")
          {
             PBr1_1.Image = new Bitmap(@"Logos\\Images\\cg.png");
            // Do some stuff.
          }
}

And then do the same when i click image with cb. To visualise this cb is black circle button image, and cg is green one.

How can i do this?

Upvotes: 0

Views: 12305

Answers (2)

Steve
Steve

Reputation: 216333

Jason is right, you should use some kind of temporary storage to save your current bitmap.
The Tag property is useful in this kind of situations. Here a sample code: (Without error handling)

somewhere in your load event

PBr1.Tag = "cb.png";`
PBr1_1.Image = new Bitmap(Path.Combine("Logos\\Images", PBr1.Tag.ToString());

and then in button click

private void PBr1_1_Click(object sender, EventArgs e) 
{     
   string imgPath = "Logos\\Images";
   PBr1_1.Image.Dispose();
   PBr1_1.Tag = (PBr1_1.Tag == "cb.png" ? "cg.png") : "cb.png") ; 
   Bitmap bm = new Bitmap(Path.Combine(imgPath, PBr1.Tag.ToString());
   PBr1_1.Image = bm; 
} 

Upvotes: 3

seveves
seveves

Reputation: 1282

Are you sure that "PBr1_1.Image.ToString()" really returns only the image name? Maybe you should check this by writing PBr1_1.Image.ToString() to console or something like that

Upvotes: 0

Related Questions