Switching PictureBox Images C# - c#

I'm trying to make a "checkbox" that has a custom check image. I need it to toggle between checked and unchecked when the user clicks the picturebox. I've tried the following code, and the first click shows the checked image fine, however a second click does nothing. Any ideas?
private void pictureBox7_Click(object sender, EventArgs e)
{
if (pictureBox7.Image == Image.FromFile(checkedImg))
{
pictureBox7.Image = Image.FromFile(uncheckedImg);
}
else
{
pictureBox7.Image = Image.FromFile(checkedImg);
}
}

Your if statement is wrong as it is unlikely to return true because you are comparing instances of the Image class which you recreate every time. You could modify it like this:
private bool _pbChecked = false;
private void pictureBox7_Click(object sender, EventArgs e)
{
var pictureBox = (PictureBox)sender;
string imgPath = _pbChecked ? uncheckedImg : checkedImg;
pictureBox.Image = Image.FromFile(imgPath);
_pbChecked = !_pbChecked;
}

Related

Parsing int does not work for some odd reason

I have a second form that pops up upon clicking a button, a user can input some parameters for a method, save the input within a variable, and then I parse the result to an int ( thus so I can utilize it within my method ). Now, upon parsing it, the value appears to be NULL as oppose to what the user inputted within the textboxes.
var displayproperties = new int[3];
using (Form2 form = new Form2())
{
try
{
if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int i = 0;
while (i == 0)
{
if (form.click) // ok button is clicked
{
// parse values
displayproperties[0] = int.Parse(form.Height);
displayproperties[1] = int.Parse(form.Width);
displayproperties[2] = int.Parse(form.Framerate);
goto break_0; // break out of loop ( loop is to check when button is clicked )
}
}
}
}
As you can see here, the values that the user inputs is Height,Width and Framerate respectively. It parses it to an int, as I explained, and stores it in the displayproperties int array.
This is the second form:
public string Height { get; set; }
public string Width { get; set; }
public string Framerate { get; set; }
public bool click = false;
public Form2()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e){}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Height = height.Text;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
Width = width.Text;
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
Framerate = framerate.Text;
}
public void OK_Click(object sender, EventArgs e)
{
click = true;
}
Ultimately, the values are then passed into this class:
public Class1(int width, int height)
However I get an out of range exception saying the value must be greater than zero. Goes without saying, the values I inputted were certainly greater than zero ( 800, 600, 60 respectively ) where 60 is used elsewhere.
Since my comment suggestion worked for you, I'll add it as an answer.
From what you've said, it sounds likely that you're not setting DialogResult anywhere, so your if statement is never being entered because the condition isn't met.
You should set the dialog result and close the form in OK_Click:
public void OK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
And then you should remove the extra code from your main form:
var displayproperties = new int[3];
using (Form2 form = new Form2())
{
try
{
if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// parse values
displayproperties[0] = int.Parse(form.Height);
displayproperties[1] = int.Parse(form.Width);
displayproperties[2] = int.Parse(form.Framerate);
}
}
}
The dialog result will serve as your click property so this is no longer required. By the way, I recommend switching to TryParse instead so that you can actively check if the input values are valid integers, as opposed to leaving it until exceptions are thrown.
An example of this:
string a = "hello"; // substitute user input here
int result;
if (!int.TryParse(a, out result))
{
MessageBox.Show($"{a} isn't a number!");
return;
}
MessageBox.Show($"Your integer is {result}");
If you're newish to programming, I recommend getting familiar with how to use the debugger. Setting a breakpoint and inspecting values as you stepped through the code would have revealed where the problem was very quickly. Microsoft have a tutorial for this.

How to change image in picturebox C#

I need to change the image by clicking on pictureBox, but when I click it again I can't return former picture
Here is my code:
private void PictureBox_Click(object sender, EventArgs e)
{
if (pictureBox.Image == Properties.Resources.openeye)
pictureBox.Image = Properties.Resources.closeeye;
else
pictureBox.Image = Properties.Resources.openeye;
}
How can I fix it?
Here's an example that demonstrates it with two images. One of an "x" another of an "o".
As you can see, the form has two instance variables x and o to store each of the Image objects. There is another flag field called isX which the ClickHandle event handler uses to check which image is currently displayed and switch to the other image, the event handler then toggles the isX field so the next click responds properly.
public void Main(string[] args)
{
var f1 = new Form1(); // form instance that holds the PictureBox
Task.Run(() => Application.Run(f1)); //I'm running this from LINQPad, but this would also work in a console application.
}
public class Form1 : Form // Derives from the Form class
{
private bool isX; // private instance variable to indicate which image is diplayed
private Image x; // private instance variable storing the x image
private Image o; // private instance variable storing the o image
// the picture box this form uses
private PictureBox p;
public Form1()
{
// load the images from wherever they are stored.
// I do this at construction time to avoid doing disk IO when clicking
x = Image.FromFile(#"C:\image\path\x.png");
o = Image.FromFile(#"C:\image\path\o.png");
// Initialize the picture box
p = new PictureBox {
Name = "p1",
Size = new Size(100,100),
Location = new Point(100,100),
Image = o //Initialize with the o image
};
// register the click event handler
p.Click += this.ClickHandle;
// set the flag to false, since the o image is what we start with
this.isX = false;
// add PictureBox p to the form
this.Controls.Add(p);
}
// handles the click action, registered to the PictureBox.Click event
private void ClickHandle(object sender, EventArgs e)
{
// use the flag to check which image is shown, and display the other image
if(this.isX) // this might work with your image == check, I didn't test it
{
p.Image = this.o;
}
else
{
p.Image = this.x;
}
// set the flag to the opposite of whatever the flag currently is
this.isX = ! isX;
}
}
You can set value of picturebox image, but you cant get it that way.
U can use global variable out of method and go this way.
int i = 0;
private void PictureBox1_Click(object sender, EventArgs e)
{
if (i == 0)
{
pictureBox1.Image = Properties.Resources.close;
i++;
}
else
{
pictureBox1.Image = Properties.Resources.open;
i--;
}
}
You can use this.
private void pictureBox1_Click(object sender, EventArgs e)
{
if (pictureBox1.Image!=null&& getSignatureLen( pictureBox1.Image) == getSignatureLen(Properties.Resources.openeye))
{
pictureBox1.Image = Properties.Resources.closeeye;
}
else
{
pictureBox1.Image = PProperties.Resources.openeye;
}
}
public long getSignatureLen(Image img)
{
using (System.IO.MemoryStream mStream = new System.IO.MemoryStream())
{
img.Save(mStream, img.RawFormat);
return mStream.Length;
}
}
You can save the value in the un-used Tag property, of the PictureBox object.
pictureBox1.Tag = 1; //Set it to whatever
if (pictureBox1.Tag == "1") { } //Do your check

PictureBox Show and Dispose

I want to show a PictureBox on button click, this should be on first click Show PictureBox, and on next click Hide PictureBox, again on third click show PictureBox and similar on fourth click again hide the PictureBox.
I have tried below code but it stuck after dispose of picture.
public bool i;
private void button1_Click(object sender, EventArgs e)
{
if (!i)
{
m1();
i = true;
}
else
{
m2();
i = false;
}
}
public void m1()
{
pictureBox1.Show();
}
public void m2()
{
pictureBox1.Dispose();
}
You don't need to Dispose your PictureBox. Just set the visibility like this:
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Visible = !pictureBox1.Visible;
}
pictureBox.Visible = true;
pictureBox.Visible = false;
I assume this is for Winforms? Calling Dispose will destroy the picturebox object in memory so that is why you are having the issue.
Use:
// Show the picture box
pictureBox.Visible = true;
// Hide the picture box
pictureBox.Visible = false;
// Show the picture box
pictureBox.Visible = true;
// Hide the picture box
pictureBox.Visible = false;

Making more than an event on a button

Please, I want to know how to make two events on one button like: when I first click on the button display an image and while still in debugging mode the second time I click
display another image. What are some ways to do this?
You can make something like:
protected void Button1Click(object sender, EventArgs e)
{
if (Img1.Visible == false)
{
Img1.Visible = true;
}
else
{
Img2.Visible = true;
}
}
I don't think you need two (or more) events to do what you want, you only need to trace how many times you clicked the button, for example using an instance variable.
private int clicks = 0;
protected void myButton_Click(object sender, EventArgs e)
{
if(clicks == 1)
{
// do something
}
if(clicks == 2)
{
// do other things
}
if(clicks > 2)
{
// something else
}
clicks++;
}
What about something like this: just make sure to declare the counter outside the button
int clickedCount = 0;
private void button1_Click(object sender, EventArgs e)
{
clickedCount++;
if (clickedCount % 2 == 0) { pictureBox1.ImageLocation = #"path"; } else { pictureBox1.ImageLocation = #"path"; }
}

How to use ColorDialog to place text in Textbox in C# / Excel Interop

How do you use the colorDialog to place the text version of a color into a textbox? I have a textbox and I fir the colorDialog upon clicking a button next to it. The tsring of the color goes into the text box, but the final result is of the form 'Color [Green]' and not simply 'Green'. Is there a better way to do this. My current code is as follows:
public partial class ColorTie : Form
{
public ColorTie()
{
InitializeComponent();
}
private void ColorTie_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = colorDialog1.Color.ToString();
}
}
}
If I'm understanding your question correctly, I believe the property you're looking for is Color.Name.
If your user selects red from your dialog, colorDialog1.Color.Name will return the string "Red". Beware though, because the user might select a color that doesn't have a Color.Name property value. To guard against this, you can check the Color.IsNamedColor property; if it's true you can use Color.Name like I described (otherwise you get back the RGB value).
Something like this:
if (colorDialog1.ShowDialog() == DialogResult.OK) {
if (colorDialog1.Color.IsNamedColor) {
Console.WriteLine("Named color: {0}", colorDialog1.Color.Name);
}
}
try this:
textBox1.Text = colorDialog1.Color.Name;
You can set the color in PictureBox, this is the best way for visualize and memorize your color choise:
private void button1_Click(object sender, EventArgs e)
{
ColorDialog cd = new ColorDialog();
if (cd.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(cd.Color.ToString());
pictureBox1.BackColor = cd.Color;
}
}

Categories

Resources