Toggle background image with button click - c#

This is my first post so I apologise if I do anything wrong :-)
I know a little bit about coding but I'm new to C#. I've created a form and I want to toggle the form BackgroundImage between two different images when a "Change Background" button is clicked. I found this code that will toggle between image and no image:
this.BackgroundImage = this.BackgroundImage == null ? Properties.Resources.image1 : null;
I thought I might be able to use it to achieve what I want but I couldn't get it to work. I'm guessing I need completely different code? I thought an "if" statement would be the way to go but I can't figure that out either.
Thanks in advance for any help.

Imagine you want to switch between 2 images. Use a flag to determine which one is up and then change the image based on that flag.
private int imgId=0;
Then button_click should contains:
this.BackgroundImage = imgId==0 ? Properties.Resources.image2 : Properties.Resources.image1;
imgId=imgId==0 ?1:0;

this.BackgroundImage = this.BackgroundImage == null ? Properties.Resources.image1 : null;
checks if the background is null, then if it is null returns an image and otherwise returns null.
You can use this code for your problem but I advise you to create a variable to check instead of the two images. The equality operator on full images isn't that performant ;)
I'll try to code really clear here and leave the difficult if operator out for better understanding.
//This variable doesn't erase if it's outside the function
private bool firstImage = true;
public function SwitchImage(){
if (firstImage == true){
//set background
this.BackgroundImage = Properties.Resources.image2
//update var
firstImage = false;
} else {
//set background
this.BackgroundImage = Properties.Resources.image1
//update var
firstImage = true;
}
}

Related

C# WinForm - Toggle the background image on a label

I have a label that is setup to look like a UK Standard Number Plate.
The font is set to Charles Wright.
I want to be able to toggle the background image of this label with the use of a button, but I want this button to be able to identify what image is currently being used so that it can change the image accordingly.
The images are stored in the 'Properties.Resources' as 'plainFrontNumberPlate.bmp' and 'borderedFrontNumberPlate.bmp'.
I have tried:
if(this.label1.Image == Resources.plainFrontNumberPlate)
{
this.label1.Image = Resources.borderedFrontNumberPlate;
}
else
{
this.label1.Image = Resources.plainFrontNumberPlate;
}
But when I try to test this. The first click changes the image to 'borderedFrontNumberPlate.bmp but not back to 'plainFrontNumberPlate.bmp when I click a twice.
use this code
public Form1()
{
InitializeComponent();
this.label1.Image.Tag = "plainFrontNumberPlate";
}
private void btnChangeImage_Click(object sender, EventArgs e)
{
switch (this.label1.Image.Tag.ToString())
{
case "plainFrontNumberPlate":
object borderedFrontNumberPlate = Resources.ResourceManager.GetObject("borderedFrontNumberPlate");
this.label1.Image = (Image)borderedFrontNumberPlate;
this.label1.Image.Tag = "borderedFrontNumberPlate";
break;
case "borderedFrontNumberPlate":
object plainFrontNumberPlate = Resources.ResourceManager.GetObject("plainFrontNumberPlate");
this.label1.Image = (Image)plainFrontNumberPlate;
this.label1.Image.Tag = "plainFrontNumberPlate";
break;
}
}
Thank you both 'Jimi' & 'Meysam Asadi' both your answers & comments worked. I preferred to use 'Meysam Asadi' code example as it was clearly laid out and easier for me to understand.
The combination of your help has solved my issue. Thank you

How do I enable or re-enable a textbox in a windows forms application, or why is my tbx.Enable = true; code not functional? (C#)

I have a multiline textbox (tbxReminderText) in the following code that is not responding to my including tbxReminderText.Enabled = true;, even after trying to include it in multiple other locations. There is no difference whether or not I have the Enabled property set to true or false in the designer properties listing. Trying to refresh the controls, or anything else that I can think of trying, is not working. Here's the applicable code:
private void EditEntry_Load(object sender, EventArgs e) {
EntryType.Entries currentTypeEdited = new EntryType.Entries();
if (mainForm.alarmCLB.SelectedIndex != -1) {
currentTypeEdited = EntryType.Entries.Alarm;
} else if (mainForm.reminderCLB.SelectedIndex != -1) {
currentTypeEdited = EntryType.Entries.Reminder;
} else {
currentTypeEdited = EntryType.Entries.Timer;
//lets change the controls accordingly
//(no event handler to remove for the existing dtp
this.Controls.Remove(dtpActiveAt);
//change existing label
lblRingAt.Text = "Duration:";
//set up new control properties
/* MUCH dynamic insertion of controls removed here for brevity;
* -+=this is in part of the above if/else branch not used for the
* EntryType.Entries.Reminder, which is where my issue lies=+- */
this.Controls.Add(nudTmrHrs);
this.Controls.Add(lblTmrHours);
this.Controls.Add(nudTmrMin);
this.Controls.Add(lblTmrMinutes);
this.Controls.Add(nudTmrSec);
this.Controls.Add(lblTmrSeconds);
}
switch (currentTypeEdited) {
case EntryType.Entries.Alarm:
//edit our alarm entry heah
tbxReminderText.Text = "unavailable";
tbxReminderText.Enabled = false;
tbxName.Text =
HeadsUp.activeAlarms[mainForm.alarmCLB.SelectedIndex].Name;
dtpActiveAt.Value =
HeadsUp.activeAlarms[mainForm.alarmCLB.SelectedIndex].ActiveAt;
break;
case EntryType.Entries.Timer:
//edit timer heah
tbxReminderText.Text = "unavailable";
tbxReminderText.Enabled = false;
tbxName.Text =
HeadsUp.activeTimers[mainForm.timerCLB.SelectedIndex].Name;
//okay the following isn't a DTP, it's a 3 number field; we're
//going to have to handle this one differently, hopefully not with
//a completely different form
/*dtpActiveAt.Value =
HeadsUp.activeTimers[mainForm.timerCLB.SelectedIndex].remaining*/
break;
case EntryType.Entries.Reminder:
//reminder tiem
tbxReminderText.Text =
HeadsUp.activeReminders[mainForm.reminderCLB.SelectedIndex].Msg;
tbxReminderText.Enabled = true;
tbxName.Text =
HeadsUp.activeReminders[mainForm.reminderCLB.SelectedIndex].Name;
dtpActiveAt.Value =
HeadsUp.activeReminders[
mainForm.reminderCLB.SelectedIndex].ActiveAt;
break;
}
}
As annotated in the block commenting inline, the problem lies in the code branches selected in the if/else if/else statement activated when mainForm.reminderCLB.SelectedIndex != -1 (verified that it's taking this branch), and in the switch/case block active when currentTypeEdited = EntryType.Entries.Reminder.
I've googled and looked quite a bit on here, but I'm not finding anything similar. I'm guessing that I've made a stupid error somewhere, and I'm just not seeing it in code review... Can anybody help in pointing out the mistake that I made, a pointer to applicable resources (I've already looked at Controls.* on MSDN, etc), or let me know what other information I should include for better troubleshooting?
Any assistance is greatly appreciated.
Most likely the parent container has property Enabled set to false. When the parent container is not enabled children will not be enabled as well even if you try to set them to true.
Edit
try examining tbxReminderText.Parent.Enabled property value in the watch window and check its value before setting tbxReminderText.Enabled to true.

Change Textbox text from another frame(container)

I see here lot of similar question, but I still not find answer that help me in situation.
I have two frame(lets say FrameChild), one is "in" another(practically FrameChild is in this frame, lets say FrameMain).
When I insert all parameters in FrameChild and tap on button witch is on bottom of FrameMain I call method that return string...
Now when i get string i need to change textbox text in FrameChild
I have tray many way.
First idea was something like:
FrameChild frm = new FrameChild;
frm.textbox.text = "somestring";
But nothing happen.
Than i thing use some property.
in FrameChield:
public string setTicNo
{
set
{
textBox.Text = value;
}
}
in FrameMain:
FrameChild frm = new FrameChild;
frm.setTicNo = "somestring";
When i debbuging I get value, but textbox still is empty...
On the end I try to bind textbox text on setTicNo;
public string setTicNo
{
get
{
return setTicNo;
}
set
{
setTicNo = value;
}
}
Xaml:
Text = {Binding setTicNo, Mode=TwoWay,UpdateSourceTrigger=Explicit}
(here i try use more bindings, but every time i get infinite loop.
Please help , I not have more ideas..
Thanx
Did you try building a single view model and bind it to both frames, if it was passed by ref which is the default it will change the value once you do.
A side note implement a INOTIFYPROPERTYCGANGED in the View model

Declaring a new object via variable name

I'm fairly new to C# (and programming in general) so stick with me if I make any huge errors or talk complete bull.
So what I'm trying to do is have a private void that resizes the background image of a button. I send the name of the button to the private void via a string. Anyway, the code looks something like this:
ButtonResize("Zwaard");
protected void ButtonResize(string Button)
{
string ButNaam = "btn" + Button;
Button Butnaam = new Button();
Butnaam.Text = ButNaam;
if (Butnaam.BackgroundImage == null)
{
return;
}
else
{
var bm = new Bitmap(Butnaam.BackgroundImage, new Size(Butnaam.Width, Butnaam.Height));
Butnaam.BackgroundImage = bm;
}
}
But it doesn't work like that. I can't seem to find a way to declare a new object named the value I have in a string. What I want my code to do is instead of making a button called "Butnaam", I want it to create a button called btnZwaard (the value of the string Butnaam).
How do I tell C# I want the value of the variable to be the name of a new button, not literally what I type?
Thanks in advance.
Are you looking for something like this? By passing the Button to the method you can then act on the object. If this is what you are looking for then you should read Passing Reference-Type Parameters
protected void ButtonResize(Button button)
{
if (button != null && button.BackgroundImage != null)
{
button.BackgroundImage = new Bitmap(button.BackgroundImage, new Size(newWidth, newHeight));
}
}
A string is a piece of text. You subsequently refer to it as a class, which is wrong. Assuming it were right you create a new button rather than "resize its image".
What you want to do to get you started is create a new function in the same class as the dialog that has the button. That function can resize the image of the control.
Edit: this doesn't seem like a good starting point for learning a language, btw. Please find a good online tutorial for starting in C# (e.g. a hello world application).

Infragistics UltraGrid: GroupBy row ForeColor changes when clicked

Using Infragistics UltraGrid in WinForms in C#:
I am conditionally changing the color of the ForeColor of some GroupByRows on a grid. When the user clicks the row, the color changes back to the active/selected/hot tracked/whatever color until they click on something else. I'd like the text color of the rows that I have conditionally colored to never change. Here's how I'm setting the color:
Row.Appearance.ForeColor = System.Drawing.Color.Orange;
Any idea how to make it stick even when the row is clicked?
Thanks!
This can be done with a draw filter to set the fore color of the description since this would apply at all times.
A simple example is the following draw filter which will make all group by rows that have an integer value that is even orange:
public class GroupByRowDrawFilter:IUIElementDrawFilter
{
public bool DrawElement(DrawPhase drawPhase, ref UIElementDrawParams drawParams)
{
GroupByRowDescriptionUIElement element = (GroupByRowDescriptionUIElement)drawParams.Element;
if (element.GroupByRow.Value is int)
{
int value = (int)element.GroupByRow.Value;
if (value % 2 == 0)
{
drawParams.AppearanceData.ForeColor = Color.Orange;
}
}
return false;
}
public DrawPhase GetPhasesToFilter(ref UIElementDrawParams drawParams)
{
if (drawParams.Element is GroupByRowDescriptionUIElement)
return DrawPhase.BeforeDrawElement;
return DrawPhase.None;
}
}
To apply the draw filter use the following line of code:
this.ultraGrid1.DrawFilter = new GroupByRowDrawFilter();
Note that this approach requires that the condition be in the draw filter. If this doesn't work for you, you could modify your logic where you are currently setting the ForeColor to set the Tag property of the GroupByRow instead and then check the Tag property in the draw filter to determine if you need to apply your logic.
I think you should also change the
grd.DisplayLayout.Override.SelectedRowAppearance.ForeColor = System.Drawning.Color.Orange;
or better
grd.DisplayLayout.Override.GroupByRowAppearance.ForeColor = System.Drawning.Color.Orange;
sorry, but I'm away from a PC where I can test.
Usually these properties could be changed effectively in the InitializeLayout event where you get the Layout object inside the event arguments.
e.Layout.Override.GroupByRowAppearance.ForeColor = Color.Orange;
EDIT: At the moment the only solution that I have found is the following
private void grd_BeforeRowActivate(object sender, RowEventArgs e)
{
// You need to add the additional logic required by you to
// determine which rows need to have the forecolo changed...
if (e.Row.IsGroupByRow == true)
grd.DisplayLayout.Override.ActiveRowAppearance.ForeColor = Color.Orange;
else
grd.DisplayLayout.Override.ResetActiveRowAppearance();
}
Infragistics says:
the "Ability to have active and selected conditional appearances for the GroupByRows" has been determined to be a new product idea

Categories