Image move on button click - c#

I want move an image in one picture box to another and vice versa on a button click, I'm pretty sure my code should work in theory, but it just won't execute for some reason. Any help would be much appreciated please!!
Here's my code:
int chicken_move = 0;
private void button_Chicken_Click(object sender, EventArgs e)
{
chicken_move++;
if (chicken_move > 1)
{
chicken_move = 0;
}
switch (chicken_move)
{
case 0:
pictureBox_Micro.Image = pictureBox_Uncooked.Image;
pictureBox_Uncooked.Image = null;
break;
case 1:
pictureBox_Uncooked.Image = pictureBox_Micro.Image;
pictureBox_Micro.Image = null;
break;
}

You need to use swap technique to change picture. Otherwise, you will lost it after first click.
public partial class Form1 : Form
{
private bool isFirstOne;
Image forSwap;
public Form1()
{
InitializeComponent();
string path1 = #"C:\Users\...\...\somePic.png";
pictureBox1.Image = Image.FromFile(path1);
forSwap = null;
isFirstOne = false;
}
private void button1_Click(object sender, EventArgs e)
{
switch (isFirstOne)
{
case true:
forSwap = pictureBox2.Image;
pictureBox1.Image = pictureBox2.Image;
pictureBox2.Image = null;
break;
case false:
forSwap = pictureBox1.Image;
pictureBox2.Image = pictureBox1.Image;
pictureBox1.Image = null;
break;
}
isFirstOne = !isFirstOne;
}
}

Try not setting the Image of one pictureBox to the Image of the other.
Try setting the Image to a reference to the actual image (file, etc.).
Or try using pictureBox.ImageLocation to set it.

Considering you set the chicken_move variable as global, there is nothing wrong
with the code. Try providing image file location:
pictureBox_Micro.ImageLocation = "UncookedImage.jpg";
pictureBox_Uncooked.ImageLocation = "MicroImage.jpg";

Related

Changing image value in DataGridViewImageColumn does not remove previous image

The problem:
When changing what image shows up in the cell of a DataGridViewImageColumn, the previous image is still there behind the new image:
(Note the red error behind the green checkmark)
What I have:
The image is showing status on connectivity to a machine. When the machine's status is updated an event is raised and the image is updated.
The declaration of the DataGridViewImageColumn:
DataGridViewImageColumn imc = new DataGridViewImageColumn
{
HeaderText = "C$",
Name = "imc",
Width = 25,
ImageLayout = DataGridViewImageCellLayout.Stretch,
ValuesAreIcons = true
};
Defaults are set:
sDGView.Columns["imc"].DefaultCellStyle.NullValue = null;
((DataGridViewImageCell)sDGView.Rows[0].Cells["imc"]).Value = null;
Event when a row is added:
private void SDGView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
((DataGridViewImageCell)sDGView.Rows[LastRow].Cells["imc"]).Value = null;
}
Method called when online status changed:
private void SetStatusImage(int ri)
{
var status = Core.Machines[ri].OnLine;
//sDGView.Rows[ri].Cells["imc"].Dispose();
var image = (DataGridViewImageCell)sDGView.Rows[ri].Cells["imc"];
if (status is null)
{
image.Value = StatusImg[0];
}
else if (status is true)
{
image.Value = StatusImg[1];
}
else
{
image.Value = StatusImg[2];
}
}
The images:
public Icon[] StatusImg { get; private set; } = new Icon[]
{
Properties.Resources.Minus_Grey,
Properties.Resources.Tick_Green,
Properties.Resources.Error_Red
};
What I've tried...
I've tried setting the image.Value to null - no change
I've called the Dispose() method on the cell itself and then created a new cell to take its place and set the value to the current image -- the previous image still shows up behind!
It seems each time I change the value of the cell, another image is simply added on top. I can verify by watching the memory size of the program increase as the image changes. The old one never actually goes away even with calling the Dispose() method.
Edit:
I tried having the main form call the Refresh() method in case it just needed to be redrawn. - no change
I tried removing the image variable and setting the image directly:
private void SDGView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
((DataGridViewImageCell)sDGView.Rows[LastRow].Cells["imc"]).Value = StatusImg[0];
}
private void SetStatusImage(int ri)
{
var status = Core.Machines[ri].OnLine;
//sDGView.Rows[ri].Cells["imc"].Dispose();
//var image = (DataGridViewImageCell)sDGView.Rows[ri].Cells["imc"];
if (status is null)
{
//image.Value = StatusImg[0];
((DataGridViewImageCell)sDGView.Rows[ri].Cells["imc"]).Value = StatusImg[0];
}
else if (status is true)
{
//image.Value = StatusImg[1];
((DataGridViewImageCell)sDGView.Rows[ri].Cells["imc"]).Value = StatusImg[1];
}
else
{
//image.Value = StatusImg[2];
((DataGridViewImageCell)sDGView.Rows[ri].Cells["imc"]).Value = StatusImg[2];
}
}
--same result - previous image still persists behind the newly selected image.
(Note the red error behind the green checkmark)
I tested such scenario with this simple code:
private void PlanningDayPlans_Load(object sender, EventArgs e)
{
DataGridViewRow r = new DataGridViewRow();
this.DataGridView1.Rows.Add(r);
}
private void Button1_Click(object sender, EventArgs e)
{
this.DataGridView1.Rows(0).Cells(0).Value = My.Resources.todo2;
}
private void Button2_Click(object sender, EventArgs e)
{
this.DataGridView1.Rows(0).Cells(0).Value = My.Resources.cross;
}
And it works without issues:
The pictures are PNG with transparent backgrounds (would show the problem), I can switch them back and forth and it works well.
This is for un-bound and DataSource-less scenario.
I think I know where your problem probably is created. You set the ValuesAreIcons property, which affects alpha channel of the background so that it is "correct" for icons. I would try to ommit this settings and use PNG icons, it will be fine.

C# Winforms App requires two clicks on Button_Click Event

The button requires two clicks to fire up the event. Here is an image and the code.There is a combobox which triggers the button with different items, but when I click the button to show an item in a panel on the page, I have to click it twice so it can trigger the event. After selecting an item once by twice-clicking it, every next time i click it works with one click, just like it should.
Here is the image of the combobox which triggers the button
And there is the code :
namespace Carbon
{
public partial class ucAnaliza : MetroFramework.Controls.MetroUserControl
{
static ucAnaliza _instance;
public static ucAnaliza Instance3
{
get
{
if (_instance == null)
_instance = new ucAnaliza();
return _instance;
}
}
public MetroFramework.Controls.MetroPanel MetroAnaliza
{
get { return mPanelAnaliza; }
set { mPanelAnaliza = value; }
}
public ucAnaliza()
{
InitializeComponent();
}
private void ucAnaliza_Load(object sender, EventArgs e)
{
}
private void mPotvrdiElementi_Click(object sender, EventArgs e)
{
switch (((ComboBox)mDropAnaliza).SelectedItem.ToString())
{
case "Главна рамка":
_instance = this;
ucGlavna uc = new ucGlavna();
uc.Dock = DockStyle.Bottom;
mPanelAnaliza.Controls.Add(uc);
break;
case "Челна рамка":
_instance = this;
ucCelna uc2 = new ucCelna();
uc2.Dock = DockStyle.Bottom;
mPanelAnaliza.Controls.Add(uc2);
break;
case "Подолжна рамка":
_instance = this;
ucPodolzna uc3 = new ucPodolzna();
uc3.Dock = DockStyle.Bottom;
mPanelAnaliza.Controls.Add(uc3);
break;
}
}
}
}
Here is the code from the designer for the button :
// mPotvrdiElementi
//
this.mPotvrdiElementi.BackColor = System.Drawing.Color.Transparent;
this.mPotvrdiElementi.CausesValidation = false;
this.mPotvrdiElementi.Cursor = System.Windows.Forms.Cursors.Hand;
this.mPotvrdiElementi.ForeColor = System.Drawing.SystemColors.MenuBar;
this.mPotvrdiElementi.Image = global::Carbon.Properties.Resources.Checked_Checkbox_24px;
this.mPotvrdiElementi.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.mPotvrdiElementi.ImageSize = 24;
this.mPotvrdiElementi.Location = new System.Drawing.Point(758, 34);
this.mPotvrdiElementi.Name = "mPotvrdiElementi";
this.mPotvrdiElementi.Size = new System.Drawing.Size(80, 25);
this.mPotvrdiElementi.Style = MetroFramework.MetroColorStyle.Orange;
this.mPotvrdiElementi.TabIndex = 4;
this.mPotvrdiElementi.TabStop = false;
this.mPotvrdiElementi.Text = "Потврди";
this.mPotvrdiElementi.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.mPotvrdiElementi.UseCustomBackColor = true;
this.mPotvrdiElementi.UseCustomForeColor = true;
this.mPotvrdiElementi.UseSelectable = true;
this.mPotvrdiElementi.UseStyleColors = true;
this.mPotvrdiElementi.Click += new System.EventHandler(this.mPotvrdiElementi_Click);
I know it is a long time ago but I was having the same problem...
But I found a solution to the problem and is working every time and not killing the usability.
private int focusFlag = 0;
private void MainForm_MouseEnter(object sender, EventArgs e)
{
if (focusFlag < 1)
{
this.FocusMe();
++focusFlag;
}
}
This will not always try to focus on that form when trying to go to other forms or something else, it will just focus once and that is enough... after that it will behave normally :)
It seems the MetroForm doesn´t get Focus until you click within the form and it is just a bug from the developers of the MetroFramework when using certain Metro Controls within the Form.
I have seen others posting the same problem when they are using the MetroFramework.
Hopefully this will help.

c# . if (image == Properties.Resources.image)

I want to do an if stament on an image
if (SortName.Image == Properties.Resources.RadioEmpty)
{
SortName.Image = Properties.Resources.Radio;
}
else
{
SortName.Image = Properties.Resources.RadioEmpty;
}
but its on working any idea what I'm doing wrong ?
o.k additional information
1.
//SortName = A picture box
//Properties.Resources.RadioEmpty = Resources\RadioEmpty.png
//Properties.Resources.Radio = Resources\Radio.png
2.
Nope no errors
3.I wanted to use a custom image for a radio button. A have a picture box with the above code on click. RadioEmpty is the default so I check to see if the picturebox's image is the same as image form the Resources folder is so do code.
i advise you use tag for this issue see this code
private void Form1_Load(object sender, EventArgs e)
{
//in form load the radio is checked or unckecked
//here my radio is unchecked at load
pictureBox1.Image = WindowsFormsApplication5.Properties.Resources.Add;
pictureBox1.Tag = "UnChecked";
}
private void pictureBox1_Click(object sender, EventArgs e)
{
//after pictiurebox clicked change the image and tag too
if (pictureBox1.Tag.ToString() == "Checked")
{
pictureBox1.Image = WinFormsApplication.Properties.Resources.Add;
pictureBox1.Tag = "UnChecked";
}
else
{
pictureBox1.Image = WinFormsApplication.Properties.Resources.Delete;
pictureBox1.Tag = "Checked";
}
}
compare the names. Something like this (unverified)
if (SortName.Image.Name.Equals(Properties.Resources.RadioEmpty.Name))
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Bitmap bm1;
Bitmap bm2;
private void button1_Click(object sender, EventArgs e)
{
bm1 = new Bitmap(Properties.Resources.firegirl1);
bm2 = new Bitmap(Properties.Resources.Zemli2);
pictureBox1.Image = bm1;
pictureBox2.Image = bm2;
if (pictureBox1.Image==pictureBox2.Image)
{
MessageBox.Show("Some");
}
else
{
MessageBox.Show("Differ");
}
}
}

Must I remove a form assigned to a TabPage and then add a new one, or can I access the existing one to change values it contains dynamically?

I am dynamically assigning forms to tab pages. It works fine, except when I try to assign
an updated version of the form (with different text values assigned to the controls) to the tab page. I am actually a little surprised that it doesn't crash when I create multiple instances of the form and assign them to the tab page (if the new ones are just stacking on top of the older ones, you would think the new one would be on top and the new values are visible).
So...what do I need to do to remove the previous form I added to the tab page before adding the new version? Or can I access the existing form and change its values.
I guess it would be clearer if I just showed the code:
Main form:
private enum TabControls {
BasicInfo,
ConfidentialInfo,
RolesAndSecurity,
InactiveInfo
}
string currentNode = string.Empty;
public Form1() {
InitializeComponent();
CenterToScreen();
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) {
currentNode = e.Node.Name;
UpdateActiveTabForNode();
}
// This is called both by treeView1_AfterSelect (sic, I changed the name to
// treeViewSearchWorker) and by tabControlWorker_SelectedIndexChanged().
// currentNode is set/overwritten on clicking a node and saved in a form var.
// The active tab page is always known via the TabControl's SelectedIndex
// property, so there is no need to pass in either value.
private void UpdateActiveTabForNode() {
int ActiveTabPage = tabControlWorker.SelectedIndex;
switch (ActiveTabPage) {
case (int)TabControls.BasicInfo:
if (tabPageBasicInfo.Controls.Count > 0) {
;// tabPageBasicInfo.Controls.Remove(0);<-- What to pass in here?
}
BasicInfoPseudoTab bipt = new BasicInfoPseudoTab(currentNode);
tabPageBasicInfo.Controls.Add(bipt);
tabPageBasicInfo.BringToFront();
bipt.Show();
break;
case (int)TabControls.ConfidentialInfo:
ConfidentialInfoPseudoTab cipt = new ConfidentialInfoPseudoTab(currentNode);
tabPageConfidentialInfo.Controls.Add(cipt);
cipt.Show();
break;
case (int)TabControls.RolesAndSecurity:
RolesAndSecurityPseudotab raspt = new RolesAndSecurityPseudotab(currentNode);
tabPageRolesAndSecurity.Controls.Add(raspt);
raspt.Show();
break;
case (int)TabControls.InactiveInfo:
InactiveInformationPseudoTab iipt = new InactiveInformationPseudoTab(currentNode);
tabPageInactiveInfo.Controls.Add(iipt);
iipt.Show();
break;
default: {
break;
// TODO: Do something?
}
}
}
private void tabControlWorker_SelectedIndexChanged(object sender, System.EventArgs e) {
UpdateActiveTabForNode();
}
}
====
Form that serves as one of the pseudo tabPages:
public partial class BasicInfoPseudoTab : Form {
String _aNodeName = String.Empty;
public BasicInfoPseudoTab(String ANodeName) {
InitializeComponent();
// Without this, you get "TopLevel control cannot be added to a control"
this.TopLevel = false;
this.FormBorderStyle = FormBorderStyle.None;
this.Visible = true;
this.Dock = DockStyle.Fill;
_aNodeName = ANodeName;
SetDisplayVals();
}
private void SetDisplayVals() {
if (_aNodeName == "NodeBuckingham") {
textBoxFirstName.Text = "Buckingham";
textBoxLastName.Text = "Piranha";
textBoxNickname.Text = "B.P.";
}
else if (_aNodeName == "NodeVolcano") {
textBoxFirstName.Text = "Volcano";
textBoxLastName.Text = "Jerry";
textBoxNickname.Text = "V.J.";
} else if (_aNodeName == "NodeParsons") {
textBoxFirstName.Text = "Parsons";
textBoxLastName.Text = "Spalding";
textBoxNickname.Text = "P.S.";
} else {
textBoxFirstName.Text = String.Empty;
textBoxLastName.Text = String.Empty;
textBoxNickname.Text = String.Empty;
}
}
Updated:
I got it working by declaring the form variables outside the event handler and disposing them if they were not null before proceeding.
string currentNode = string.Empty;
BasicInfoPseudoTab bipt;
ConfidentialInfoPseudoTab cipt;
RolesAndSecurityPseudotab raspt;
InactiveInformationPseudoTab iipt;
. . .
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) {
currentNode = e.Node.Name;
UpdateActiveTabForNode();
}
private void UpdateActiveTabForNode() {
int ActiveTabPage = tabControlWorker.SelectedIndex;
switch (ActiveTabPage) {
case (int)TabControls.BasicInfo:
if (null != bipt) {
bipt.Dispose();
}
bipt = new BasicInfoPseudoTab(currentNode);
tabPageBasicInfo.Controls.Add(bipt);
bipt.Show();
break;
. . .
As you wish, use module level variables, one for each form, if null, new it, else as above. If you are creating forms constantly on top of each other how are you ever going to clean up? Check the size of your working set as you keep creating forms.

Clear a Picturebox.backgroundimage in c#

I have a picturebox where i can load a image into its .backgroundimage function and now i have a button that is suppose to clear it but doesn't. I have tried using this code:
secondcapturebox.Dispose();
But yet still the image is in the picturebox.
Please Help,
Thanks
You have to set it to null. Like this:
private void button1_Click(object sender, EventArgs e) {
if (pictureBox1.BackgroundImage != null) {
pictureBox1.BackgroundImage.Dispose();
pictureBox1.BackgroundImage = null;
}
}
Have you tried...
secondcapturebox.BackgroundImage = null;
pictureBox1.Image = null;
pictureBox1.Invalidate();
pictureBox1.BringToFront();
pictureBox1.BackgroundImage = null;

Categories

Resources