Disabling the events of a button c# - c#

I am trying to make a trading game and I am trying to add a function that if you buy more than 10 items the buy button does not work anymore. I have started with an if statement
int limit = 10;
int quantity = int.Parse(textBox13.Text);
//Quantity 1
if (quantity >= limit)
{
MessageBox.Show("You have gone beyond the limit!");
}
I am just unsure what the code is that I should use. I have tried making the button invisible if you cant afford this however I would like to try this function.

YourButtonIdHere.Enabled = false;

By setting ButtonID enable to False for disable the button.
Syntax: .Enabled = ;
Example: btnID.Enabled = false;

you can simply disable your button
button1.Enabled = false; // For Disable
button1.Enabled = true; // For Enable
if it does not match with your criteria you can also only disable button's click event
button1.Click -= button1_Click; // For Disable
button1.Click += button1_Click; // For Enable

You can also do it when the text is being entered. Advantage of doing this is that you button will be enabled and disabled while entering text and you won't have to create new event for it. Hope it helps.
private void textBox13_TextChanged(object sender, EventArgs e)
{
try
{
if(Int.TryParse(textBox13.Text) > limit)
{
button1.Enabled=false;
}
else
{button1.Enabled=true;
}
}
catch
{
button1.Enabled=true;
}
}

Related

Disabling a checkbox when another checkbox is clicked

I am trying to disable the thin and crispy checkbox when traditional checkbox is clicked. I have these in a group due to me enabling the whole group when the numericUpDown value is set to 1. When I click traditional checkbox, it doesn't disable the thin and crispy checkbox. I am using windows form application
Code
private void NudQuantity1_ValueChanged(object sender, EventArgs e)
{
if (NudQuantity1.Value == 0)
{
gbCheesePizza.Enabled = false;
}
else
{
gbCheesePizza.Enabled = true;
}
if (CBXTraditional1.Checked == true)
{
CBXthinandcrispy1.Enabled = false;
}
}
When I run this code outside of a groupbox, it works perfectly.
I don't think this block should be inside the event handler
if (CBXTraditional1.Checked == true)
{
CBXthinandcrispy1.Enabled = false;
}
It means that, provided you've got no other event handling for the checkboxes, this code will only be executed when you change the value of NudQuantity1 so it won't execute anything when you click the checkboxes afterwards.
Try use radio buttons as Steve mentioned. They do this for you.

UWA - back button handling

I've used backrequest event like below code and on appbar title back button or mobile device hardware button I should click twice on button till event work.
What should I do to it work with just one click?
SystemNavigationManager.GetForCurrentView().BackRequested += (sender, e) =>
{
bool handeled = e.Handled;
if (Frame.CanGoBack && !handeled)
{
handeled = true;
Frame.GoBack();
}
e.Handled = handeled;
};
if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
{
Windows.Phone.UI.Input.HardwareButtons.BackPressed += (sender, e) =>
{
bool handeled = e.Handled;
if (Frame.CanGoBack && !handeled)
{
handeled = true;
Frame.GoBack();
}
e.Handled = handeled;
};
}
I had the same issue. Every time I wanted to navigate back, I had to press the back button twice. Until I found out, that the SplitView was responsible for this problem. I had to close it, before navigating.
For example, if you want to move from Page1 to another page and then go back, use something like this on Page1:
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
MySplitView.IsPaneOpen = false;
}
I hope it helps, even if you said that on a blank project (obvious without a Hamburger menu) the result was the same.

Check boxes in C#

How to check the box dynamically without firing check changed function? I have 20 checkboxes that are dynamically created and I have a drop-down that determines how many checkboxes are to be checked.
If I selected 3 and click on 6th check box, that should check checkboxes 9, 7 and 8. In this process I don't want to fire checkchanged function.
CheckBox cb1 = (CheckBox)sender;
selectedbox = int.Parse(cb1.Name);
for (int i = 1; i < selectedquantity; i++)
{
premiumticket[selectedbox].Checked = true;
//here check changed firing i dont want that
selectedbox++;
}
You can't stop CheckBox from firing event when it's state changed. Consider to either unsubscribe from event when you don't need it:
for (int i = 0; i < selectedquantity; i++)
{
premiumticket[selectedbox + i].CheckedChanged -= checkBox_CheckedChanged;
premiumticket[selectedbox + i].Checked = true;
premiumticket[selectedbox + i].CheckedChanged += checkBox_CheckedChanged;
}
or use some flag to omit handling of event if you don't need it:
flag = false;
for (int i = 0; i < selectedquantity; i++)
premiumticket[selectedbox + i].Checked = true;
flag = true;
And in handler:
private void checkBox_CheckedChanged(object sender, EventArgs e)
{
if (!flag)
return;
//...
}
I can't see really solution how not to fire the event. You could disable the event with -= and then add it again with +=.
checkBox.CheckedChanged -= checkBox_CheckedChanged;
checkBox.Checked = true;
checkBox.CheckedChanged += checkBox_CheckedChanged;
The big disadvantag of this is that you would have to fire the event manually if you would like to have this event once, when you're updating the values.
I'd rather set a flag in the class and check this flag in the update code.
Remove the event attached then attach it after the you change the check :
{
cb1.CheckedChanged -= new EventHandler(cb1_CheckedChanged);
premiumticket[selectedbox].Checked = true;
cb1.CheckedChanged += new EventHandler(cb1_CheckedChanged);
}
private void cb1_CheckedChanged(object sender, EventArgs e)
{
// Some COde
}
Re-subscribing (unsubscribing/subscribing) technique is not very nice, because you have to deal with every event handler, making it common, adding flags, etc.
What is really simple to do is to use another event - Click - to simply check changes to the control which are made by user:
private void checkBox1_Click(object sender, EventArgs e)
{
checkBox2.Checked = checkBox1.Checked;
checkBox3.Checked = false;
}
private void checkBox2_Click(object sender, EventArgs e)
{
// this is not called when you set "Checked" programmatically
}
It is obvious, what you have to implement different pattern, to actually do something with data (save them or react on changes), if they are changed programmatically. In above example, clicking checkBox2 will run handler, where you, to example, save something into configuration, while setting checkBox2.Checked = true, when clicking checkBox1, will not.
It may happens, what for some CheckBox'es you will use only Click, for others - only CheckedChanged.

Track Bar Only fire event on final value not ever time value changes

I am working on a pretty basic C# visual studio forms application but am having some issue getting the track bar to act as I want it to so hoping someone in the community might have a solution for this.
What I have is a pretty basic application with the main part being a track bar with a value of 0 to 100. The user sets the value of the track to represent "the amount of work to perform" at which point the program reaches out to some devices and tells them to do "x" amount of work (x being the value of the trackbar). So what I do is use the track bars scroll event to catch when the track bars value has changed and inside the handler call out to the devices and tells them how much work to do.
My issue is that my event handler is called for each value between where the track bar currently resides and where ever it ends. So if it is slid from 10 to 30, my event handler is called 20 times which means I am reaching out to my devices and telling them to run at values I don't even want them to run at. Is there someway only to event when scroll has stopped happening so you can check the final value?
Just check a variable, if the user clicked the track bar. If so, delay the output.
bool clicked = false;
trackBar1.Scroll += (s,
e) =>
{
if (clicked)
return;
Console.WriteLine(trackBar1.Value);
};
trackBar1.MouseDown += (s,
e) =>
{
clicked = true;
};
trackBar1.MouseUp += (s,
e) =>
{
if (!clicked)
return;
clicked = false;
Console.WriteLine(trackBar1.Value);
};
For the problem #roken mentioned, you can set LargeChange and SmallChange to 0.
Try the MouseCaptureChanged event - that is the best for this task
A user could also move the track bar multiple times in a short period of time, or click on the track multiple times to increment the thumb over instead of dragging the thumb. All being additional cases where the value that registers at the end of a "thumb move" is not really the final value your user desires.
Sounds like you need a button to confirm the change, which would then capture the current value of the trackbar and send it off to your devices.
Try this with the trackbar_valuechanged event handler:
trackbar_valuechanged(s,e) {
if(trackbar.value == 10){
//Do whatever you want
} else{
//Do nothing or something else
}
}
I found a fairly reliable way to do this is to use a timer hooked up in the trackbar.Scroll event:
private Timer _scrollingTimer = null;
private void trackbar_Scroll(object sender, EventArgs e)
{
if (_scrollingTimer == null)
{
// Will tick every 500ms (change as required)
_scrollingTimer = new Timer()
{
Enabled = false,
Interval = 500,
Tag = (sender as TrackBar).Value
};
_scrollingTimer.Tick += (s, ea) =>
{
// check to see if the value has changed since we last ticked
if (trackBar.Value == (int)_scrollingTimer.Tag)
{
// scrolling has stopped so we are good to go ahead and do stuff
_scrollingTimer.Stop();
// Do Stuff Here . . .
_scrollingTimer.Dispose();
_scrollingTimer = null;
}
else
{
// record the last value seen
_scrollingTimer.Tag = trackBar.Value;
}
};
_scrollingTimer.Start();
}
}
I had this problem just now as I'm implementing a built in video player and would like the user to be able to change the position of the video but I didn't want to overload the video playback API by sending it SetPosition calls for every tick the user passed on the way to his/her final destination.
This is my solution:
First, the arrow keys are a problem. You can try your best to handle the arrow keys via a timer or some other mechanism but I found it more pain than it is worth. So set the property SmallChange and LargeChange to 0 as #Matthias mentioned.
For mouse input, the user is going to have to click down, move it, and let go so handle the MouseDown, MouseUp, and the Scroll events of the trackbar like so:
private bool trackbarMouseDown = false;
private bool trackbarScrolling = false;
private void trackbarCurrentPosition_Scroll(object sender, EventArgs e)
{
trackbarScrolling = true;
}
private void trackbarCurrentPosition_MouseUp(object sender, MouseEventArgs e)
{
if (trackbarMouseDown == true && trackbarScrolling == true)
Playback.SetPosition(trackbarCurrentPosition.Value);
trackbarMouseDown = false;
trackbarScrolling = false;
}
private void trackbarCurrentPosition_MouseDown(object sender, MouseEventArgs e)
{
trackbarMouseDown = true;
}
I had a similar problem, only with a range TrackBar Control. Same idea applies to this also, only it's easier for this case.
I handled the MouseUp Event on the TrackBar to launch the procedures I needed, only after you would let go of the mouse button. This works if you drag the bar to your desired position or just click it.
private void rangeTrackBarControl1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
YourProcedureHere();
}
i solved the problem for my application with two events:
catch the Trackbar-ValueChange-Event
whithin the value-change event disable the valuechange event and enable the MouseUp-Event
public MainWindow()
{
//Event for new Trackbar-Value
trackbar.ValueChanged += new System.EventHandler(trackbar_ValueChanged);
}
private void trackbar_ValueChanged(object sender, EventArgs e)
{
//enable Trackbar Mouse-ButtonUp-Event
trackbar.MouseUp += ch1_slider_MouseUp;
//disable Trackbar-ValueChange-Event
trackbar.ValueChanged -= ch1_slider_ValueChanged;
}
private void trackbar_MouseUp(object sender, EventArgs e)
{
//enable Trackbar-ValueChange-Event again
trackbar.ValueChanged += new System.EventHandler(trackbar_ValueChanged);
//disable Mouse-ButtonUp-Event
trackbar.MouseUp -= trackbar_MouseUp;
//This is the final trackbar-value
textBox.AppendText(trackbar.Value);
}
ATTENTION: this works if the trackbar is moved by mose. It is also possible to move the trackbar by keyboard. Then futher code must be implemented to handle this event.

ToggleButton in C# WinForms

Is it possible to create a toggle button in C# WinForms? I know that you can use a CheckBox control and set it's Appearance property to "Button", but it doesn't look right. I want it to appear sunken, not flat, when pressed. Any thoughts?
You can just use a CheckBox and set its appearance to Button:
CheckBox checkBox = new System.Windows.Forms.CheckBox();
checkBox.Appearance = System.Windows.Forms.Appearance.Button;
Check FlatStyle property. Setting it to "System" makes the checkbox sunken in my environment.
You may also consider the ToolStripButton control if you don't mind hosting it in a ToolStripContainer. I think it can natively support pressed and unpressed states.
thers is a simple way to create toggle button. I test it in vs2010. It's perfect.
ToolStripButton has a "Checked" property and a "CheckOnClik" property. You can use it to act as a toggle button
tbtnCross.CheckOnClick = true;
OR
tbtnCross.CheckOnClick = false;
tbtnCross.Click += new EventHandler(tbtnCross_Click);
.....
void tbtnCross_Click(object sender, EventArgs e)
{
ToolStripButton target = sender as ToolStripButton;
target.Checked = !target.Checked;
}
also, You can create toggle button list like this:
private void Form1_Load(object sender, EventArgs e)
{
arrToolView[0] = tbtnCross;
arrToolView[1] = tbtnLongtitude;
arrToolView[2] = tbtnTerrain;
arrToolView[3] = tbtnResult;
for (int i = 0; i<arrToolView.Length; i++)
{
arrToolView[i].CheckOnClick = false;
arrToolView[i].Click += new EventHandler(tbtnView_Click);
}
InitTree();
}
void tbtnView_Click(object sender, EventArgs e)
{
ToolStripButton target = sender as ToolStripButton;
if (target.Checked) return;
foreach (ToolStripButton btn in arrToolView)
{
btn.Checked = false;
//btn.CheckState = CheckState.Unchecked;
}
target.Checked = true;
target.CheckState = CheckState.Checked;
}
How about this?
Assuming you have System.Windows.Forms referenced.
var cbtnToggler = new CheckBox();
cbtnToggler.Appearance = Appearance.Button;
cbtnToggler.TextAlign = ContentAlignment.MiddleCenter;
cbtnToggler.MinimumSize = new Size(75, 25); //To prevent shrinkage!
Hope this helps ;)
This is my simple codes I hope it can help you
private void button2_Click(object sender, EventArgs e)
{
if (button2.Text == "ON")
{
panel_light.BackColor = Color.Yellow; //symbolizes light turned on
button2.Text = "OFF";
}
else if (button2.Text == "OFF")
{
panel_light.BackColor = Color.Black; //symbolizes light turned off
button2.Text = "ON";
}
}
When my button's FlatStyle is set to system, it looks flat. And when it's set to popup, it only pops up when mouses over. Either is what I want. I want it to look sunken when checked and raised when unchecked and no change while mousing over (the button is really a checkbox but the checkbox's appearance property is set to button).
I end up setting the FlatStyle to flat and wrote a new Paint event handler.
private void checkbox_paint(object sender, PaintEventArgs e)
{
CheckBox myCheckbox = (CheckBox)sender;
Rectangle borderRectangle = myCheckbox.ClientRectangle;
if (myCheckbox.Checked)
{
ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
Border3DStyle.Sunken);
}
else
{
ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
Border3DStyle.Raised);
}
}
I give a similar answer to this question:
C# winforms button with solid border, like 3d
Sorry for double posting.
You can always code your own button with custom graphics and a PictureBox, though it won't necessarily match the Windows theme of your users.
I ended up overriding the OnPaint and OnBackgroundPaint events and manually drawing the button exactly like I need it. It worked pretty well.
use if command to check status and let operate as a toggle button
private void Protection_ON_OFF_Button_Click(object sender, EventArgs e)
{
if (FolderAddButton.Enabled == true)
{
FolderAddButton.Enabled = false;
}
else
{
FolderAddButton.Enabled = true;
}
}
You should look into Siticone I use it and I love it. It works exactly like a checkbox but is a toggle button. Its downside is a message box will come up every time you open Visual Studios so I just installed a tool that disables it. You can also look into Guana but I found that to have a few bugs :)
Changing a CheckBox appearance to Button will give you difficulty in adjustments. You cannot change its dimensions because its size depends on the size of your text or image.
You can try this: (initialize the count variable first to 1 | int count = 1)
private void settingsBtn_Click(object sender, EventArgs e)
{
count++;
if (count % 2 == 0)
{
settingsPanel.Show();
}
else
{
settingsPanel.Hide();
}
}
It's very simple but it works.
Warning: This will work well with buttons that are occasionally used (i.e. settings), the value of count in int/long may be overloaded when used more than it's capacity without closing the app's process. (Check data type ranges: http://msdn.microsoft.com/en-us/library/s3f49ktz.aspx)
The Good News: If you're running an app that is not intended for use 24/7 all-year round, I think this is helpful. Important thing is that when the app's process ended and you run it again, the count will reset to 1.

Categories