help me to cheat with numericUpDown1_ValueChanged event - c#

I have a Form and numericupdown control located on it. I want that in some conditions (_condition1) user cannot be able to change a value of numericupdown control. How can I do it ? I wrote some code but it works twice (double time).
class Form1 : Form
{
bool _condition1;
int _previousValue;
void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
if(_condition1)
{
numericUpDown1.Value = (decimal)_previousValue;
}
else
{
_previousValue = (int)numericUpDown1.Value;
}
}
}
Control must be enable.

numericUpDown1.ReadOnly = true;
?
.... edit: ..........
Another (ugly) solution would be to remove the event, change the value, and add the event again ..
numericupdown1.ValueChanged -= new EventHandler ....
numericupdown1.Value = value;
numericupdown1.ValueChanged += new EventHandler ....

Have you tried using the Validating event?
EDIT #1 Have you tried the Leave event?

Related

TextBox took back focus while other controls don't

I wanted to focus to a TextBox when I leave an other TextBox.
Let's say I have 3 textboxes. The focus is in the first one, and when I click into the second one, I want to put the focus into the last one instead.
I subscribed to the first textbox's Leave event and tried to focus to the third textbox like: third.Focus(). It gains focus for a moment but then the second one got it eventually (the one I clicked).
Strangely if I replace the second TextBox to a MaskedTextBox (or to any other control), the focus remains on the third one.
Pressing Tab does work though.
These are plain textboxes right from the toolbox.
What is the reason, how can I solve this?
Try to handle Enter event of the textBox2. (In properties window double click on Enter event)
//From Form1.Designer.cs
this.textBox2.Enter += new System.EventHandler(this.textBox2_Enter);
private void textBox2_Enter(object sender, EventArgs e)
{
textBox3.Focus();
}
EDIT:
This code looks very strange, but it works for me. According to this post HERE I use ActiveControl property instead of Focus() method. But behavior of TextBox is very strange because it try to be focused multiple times.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
foreach (Control control in Controls)
{
control.LostFocus += (s, e) => Console.WriteLine(control.Name + " LostFocus");
control.GotFocus += (s, e) =>
{
Console.WriteLine(control.Name + " GotFocus");
if (!requestedFocusToTextBox2) return;
ActiveControl = textBox2; //textBox2.Focus() doesn't work
requestedFocusToTextBox2 = false;
};
}
}
private bool requestedFocusToTextBox2;
private void textBox1_Leave(object sender, EventArgs e)
{
ActiveControl = textBox2;
requestedFocusToTextBox2 = true;
}
}

Enabling a button after number of edittexts has been filled

I want to make an activity with few edittext fields and a button which should be disabled until the most important of these fields has been filled. This is the code I am using but the button is staying disabled the whole time:
doneButton implementation
if((isEmpty(inputType)) || (isEmpty(inputAmount)) || (isEmpty(inputSupplier)))
doneButton.Enabled = false;
else
doneButton.Enabled = true;
This is the code for the isEmpty() method, which is checking if the edittext is empty or not:
private Boolean isEmpty(EditText etText) {
return etText.Text.ToString().Length == 0;
}
Thanks in advance ! :)
Why not use the TextChanged event:
EditText input = FindViewById<EditText>(Resource.Id.editText1);
input.TextChanged += input_TextChanged;
and then define the event handler for it?
private void input_TextChanged(object sender, TextChangedEventArgs e)
{
Console.WriteLine("input text changed");
// if text bigger than 0, enable the button, otherwise disable it
}
Much cleaner IMHO.
You will need to add this implementation(your code to check if the button stays disabled) inside the TextWatcher#afterTextChanged method , which you would add as a TextChanged listener. You will need to do this for all the edit texts you think are important.
Something like this:
inputType.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
if((isEmpty(inputType)) || (isEmpty(inputAmount)) || (isEmpty(inputSupplier)))
doneButton.setEnabled(false);
else
doneButton.setEnabled(true);
}
});
Similar listeners over inputAmount and inputSupplier should do the task.
The question is: On which event did you attach this code?
You can, for example, create a TextWatcher object and attach it to the relevant text fields. Something like:
inputType.addTextChangedListener(watcher);
In this watcher you would do the checks you have written and do:
doneButton.setEnabled(true/false);
I solved it like this:
inputType.AfterTextChanged += new EventHandler<AfterTextChangedEventArgs> (OnTextChange);
inputAmount.AfterTextChanged += new EventHandler<AfterTextChangedEventArgs> (OnTextChange);
inputSupplier.AfterTextChanged += new EventHandler<AfterTextChangedEventArgs> (OnTextChange);
where the OnTextChange() method is this:
public void OnTextChange(object sender, EventArgs e)
{
if((isEmpty(inputType)) || (isEmpty(inputAmount)) || (isEmpty(inputSupplier)))
doneButton.Enabled = false;
else
doneButton.Enabled = true;
}

Register MouseEnter/MouseLeave events for disabled controls in windows form?

I want to register MouseEnter/MouseLeave events for disabled buttons. It does not work allthough it does work for enabled buttons..
//Enable Disable controls on form load
EnableDisableControls("Load");
var grupButtons = control.Controls.OfType<Button>();
foreach (Button btns in grupButtons)
{
//btns.MouseMove += new MouseEventHandler(MainframeDataExchangeTool_MouseMove);
btns.MouseEnter += new EventHandler(btns_MouseEnter);
btns.MouseLeave += new EventHandler(btns_MouseLeave);
}
private void btns_MouseEnter(object sender, EventArgs e)
{
}
private void btns_MouseLeave(object sender, EventArgs e)
{
var parent = sender as Control;
string tipstring = string.Empty;
if (parent == null)
{
return;
}
string enter = sender.GetType().ToString() + ": MouseEnter";
}
It is working for enable button ...but what to do for disable button ... I have to show tooltip operation on mouseenter and make it disapper immediately on mouseleave ?
yes , when you disable button , events will disable.
you can use this trick:
put your button in panel1 ,
then use the same event of button for panel1. like this:
btns.MouseEnter += new EventHandler(btns_MouseEnter);
btns.MouseLeave += new EventHandler(btns_MouseLeave);
panel1.MouseEnter += new System.EventHandler(btns_MouseEnter);
panel1.MouseLeave += new System.EventHandler(btns_MouseLeave);
it will work.
You can try some Form-wide Mouse message solution like this:
//Suppose your disabled Button is button1
public partial class Form1 : Form, IMessageFilter
{
public Form1()
{
InitializeComponent();
button1.Enabled = false;
button1.BackColor = Color.Green;
//Try this to see it in action
button1.MouseEnter += (s, e) => {
button1.BackColor = Color.Red;
};
button1.MouseLeave += (s, e) => {
button1.BackColor = Color.Green;
};
Application.AddMessageFilter(this);//Add the IMessageFilter to the current Application
}
bool entered;
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == 0x200) //WM_MOUSEMOVE = 0x200
{
if (Control.FromHandle(m.HWnd) == button1.Parent &&
button1.ClientRectangle.Contains(button1.PointToClient(MousePosition)))
{
if (!entered) {
entered = true;
//Raise the MouseEnter event via Reflection
typeof(Button).GetMethod("OnMouseEnter", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
.Invoke(button1, new[] { EventArgs.Empty });
}
}
else if (entered) {
//Raise the MouseLeave event via Reflection
typeof(Button).GetMethod("OnMouseLeave", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
.Invoke(button1, new []{EventArgs.Empty});
entered = false;
}
}
return false;
}
}
Why can't you try this?
By adding MouseMove event on the form...
Alternatively, if you want an easy way of maintaining the event handling, you could just never actually disable the button. Add some sort of wrapper class around a button that changes the the implementation of your buttons.
The new disable property could just change some CSS on the button and change a property that would make the click handler not do anything (or other relevant events).
I tried many but ended up using this simple trick which I think it is more effective.
Create a subclass(CustomControl with just base control in it) which extends UserControl
then instead of setting "Enabled" property to false create a Method which disables just basecontrol in it instead of whole CustomControl.
Set the tool tip on CustomControl still will be able to fire eventhandlers setting the basecontrol disabled. This works wherever CustomControl is in use rather than coding on every form you use with.
Here is the hint.. :)
public partial class MyTextBox : UserControl
{
...
...
...
public void DisableMyTextBox()
{
this.txt.Enabled = false; //txt is the name of Winform-Textbox from my designer
this.Enabled = true;
}
public void EnableMyTextBox()
{
this.txt.Enabled = true;
this.Enabled = true;
}
//set the tooltip from properties tab in designer or wherever
}

Event handler for groupBox with radioButtons in C#

I have some radionButtons in groupBox and I need to do action what I could call "one of radiobuttons.checked changed" or find out from radiobutton what index is changed.
I've tryed to find it in list of events but I couldn't find the right one.
Edit:
To make it more clear: I need to know if exist some handel for what I'll write handler method for the goupBox not for single radioButton. I know how to use radiButton.checkedChanged, but it's not what I'm finding ..
Or differently I need to know what options have the groupBox in monitoring what happens inside this groupBox - I mean only the handlers for the groupBox. I'm finding handler "in the group box is something happens" or simimilar if any exist.
It's in WFA (Windows Presentation Application) in Visual studio 2012.
I think what you want to do is wire up all of the RadioButtons' CheckedChanged event to the same handler.
public Form1()
{
radioButton1.CheckedChanged += new EventHandler(radioButtons_CheckedChanged);
radioButton2.CheckedChanged += new EventHandler(radioButtons_CheckedChanged);
// ...
}
private void radioButtons_CheckedChanged (object sender, EventArgs e)
{
RadioButton radioButton = sender as RadioButton;
if (radioButton1.Checked)
{
// Do stuff
}
else if (radioButton2.Checked)
{
// Do other stuff
}
}
Nothing built in for that as far as I'm aware.
Set the tag property to some sort of indicator (0 to n) will do.
Add a CheckChangedHandler
Point all the buttons CheckChanged events at it.
then something like.
private void radioButtons_CheckedChanged (object sender, EventArgs e)
{
RadioButton radioButton = sender as RadioButton;
int buttonid = (int)radioButton.Tag;
switch (buttonid)
{
case 0 : // do something; break
}
}
If you've got a few of these I'd look at a radiogroup component.
I had the same problem: a group box named Button Type (gbxButtonType) with 6 radio buttons and another group box named Icon Type (gbxIconType) with 8 radio button. When the user selected one radio button from each group box, a MessageBox will appear with the selection applied after clicking the DisplayButton. My problem was that the group boxes didn't have a CheckedChanged event. The solution of AKN worked perfectly:
public Form1()
{
InitializeComponent();
for (int i = 0; i < gbxButtonType.Controls.Count; i++)
{
RadioButton rdb = (RadioButton)gbxButtonType.Controls[i];
rdb.CheckedChanged += new System.EventHandler(gbxButtonType_CheckedChanged);
}
for (int i = 0; i < gbxIconType.Controls.Count; i++)
{
RadioButton rdb = (RadioButton)gbxIconType.Controls[i];
rdb.CheckedChanged += new System.EventHandler(gbxIconType_CheckedChanged);
}
}
private void gbxIconType_CheckedChanged(object sender, EventArgs e)
{
if (sender == rdbAsterisk)
{
iconType = MessageBoxIcon.Asterisk;
}
else if (sender == rdbError)
{
iconType = MessageBoxIcon.Error;
}
...
else
{
iconType = MessageBoxIcon.Warning;
}
}
Similar to davenewza's answer (and likely should have been a comment, but I have insufficient reputation), but with the event firing only once for the entire group of radio buttons.
public Form1()
{
// Add a "CheckedChanged" event handler for each radio button.
// Ensure that all radio buttons are in the same groupbox control.
radioButton1.CheckedChanged += new EventHandler(radioButtons_CheckedChanged);
radioButton2.CheckedChanged += new EventHandler(radioButtons_CheckedChanged);
}
private void radioButtons_CheckedChanged (object sender, EventArgs e)
{
// Do stuff only if the radio button is checked (or the action will run twice).
if (((RadioButton)sender).Checked)
{
if (((RadioButton)sender) == radioButton1)
{
// Do stuff
}
else if (((RadioButton)sender) == radioButton2)
{
// Do other stuff
}
}
}
Groupbox will limit only one radio button checked
So Setp1: you can assign one "CheckedChanged" event handler to all you radio button
private void initRadio()
{
radio_button1.CheckedChanged += Radio_show_CheckedChanged;
radio_button2.CheckedChanged +=Radio_show_CheckedChanged;
}
And Setp2: implement this event handler like this (Filter by Radio Button's Text)
private void Radio_show_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = sender as RadioButton;
if (radioButton.Checked == true) { //limited only checked button do function
switch (radioButton.Text)
{
case "name1":
// do your stuff ...
break;
case "name2":
// do your stuff ...
break;
}
}
}
System.Windows.Forms.RadioButton.CheckedChanged
is the event you need
So do something like:
public Form1()
{
InitializeComponent();
this.radioButton1.CheckedChanged += new EventHandler(radioButton1_CheckedChanged);
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
// your action
}
I think your want to handle the selection of some radio buttons inside a groupbox using the groupbox control itself.
May be you wanted this basically to avoid code repetition.
(i.e) adding check change event for all the radio button in the designer which may be tedious when there are more control.
Since its already present under a group, why not use the group control object to manipulate controls with-in it and set the events.
This is how I understood your problem and hence the solution as indicated below.
Set a common handler for all radio button control in the group box
for (int i = 0; i < groupBox.Controls.Count; i++)
{
RadioButton rb = (RadioButton)groupBox.Controls[i];
rb.CheckedChanged += new System.EventHandler(evntHandler);
}
Inside the handler, you can determine which button was changed as indicated by others and do the necessary action.
//Here you go courtesy of Jock Frank Halliday
//^subscribe events to radio button check changed
private void seriesTxtBxEvent()
{
//Show txtBx
this.radBtn_RoomSeries.CheckedChanged += new EventHandler(showSeriesTxtBx_Event);
//Hide txtBx
this.radBtn_RoomNumber.CheckedChanged += new EventHandler(hideSeriesTxtBx_Event);
this.radBtn_RoomName.CheckedChanged += new EventHandler(hideSeriesTxtBx_Event);
this.radBtn_RoomLevel.CheckedChanged += new EventHandler(hideSeriesTxtBx_Event);
this.radBtn_RoomDep.CheckedChanged += new EventHandler(hideSeriesTxtBx_Event);
}
private void hideSeriesTxtBx_Event(object sender, EventArgs e)
{
tbx_SheetSeries.Visible = false;
}
private void showSeriesTxtBx_Event(object sender, EventArgs e)
{
tbx_SheetSeries.Visible = true;
}
//Form Start
void MainFormLoad(object sender, EventArgs e)
{
Control.ControlCollection locais = groupBoxLocalização.Controls;
foreach (CheckBox chkBox in locais)
{
chkBox.MouseUp += chkBoxLocais_MouseUp;
}
}
// Event
void chkBoxLocais_MouseUp(object sender, MouseEventArgs e)
{
//Tratar individualmente
CheckBox chk = (CheckBox)sender;
//ou para tratar todos objetos de uma vez
Control.ControlCollection locais = groupBoxLocalização.Controls;
foreach (CheckBox chkBox in locais) {
//chkBox....
}
}
You can maybe do it with Timer, but that's just bad for optimalization, the easy solution is that for every radiobutton you simply add only one function as ChekedChanged event.
Create a Checked event by double clicking on any of the radio buttons, copy the name of the method that Visual Studio creates for the event
Go to all radio buttons and change the event to the copied one from Properties Explorer > Events Section
In the generated method use the following code. This would fire event for all radio buttons but only "Do your thing" once
Code:
private void radioButtons_CheckedChanged (object sender, EventArgs e)
{
RadioButton rb = sender as RadioButton;
if (rb.Checked == false) return;
// Do your thing
}
Create Event Checked_Changed on one radio button from Designer Events list.
Add same event to each radio Button from dropdown in front of Checked_Changed
event of each radio
inside checked changed event use
private void CheckedChanged(object sender,EventArgs e)
{
var radio = groupBox.Controls.OfType<RadioButton>
().FirstOrDefault(r => r.Checked).Name;
}
you can get which radio is active now.

Why is there an infinite loop on my LostFocus Event

I'm a beginner with C# and I'm developing a basic application.
I want to check if the value of a textbox is a number with the following code :
private void check_value(object sender)
{
TextBox tb = (TextBox)sender ;
if (!Utility.isNumeric(tb.Text)){
MessageBox.Show(tb.Text.Length.ToString());
tb.Focus();
}
}
private void Amount_1_LostFocus(object sender, RoutedEventArgs e)
{
check_value(sender);
}
When I enter a letter in the textbox there is an infinite loop and it seems that the tb.Focus() actually cause the LostFocus event to be call recursively.
I don't understand why the call to the Focus method of an object triggers the LostFocus event of the same object.
Opening the modal MessageBox is responsible for loosing the focus. Try hook to Validating event.
As i said before in the link provided by Xaqron it's said that it's forbidden to use the Focus method in the LostFocus event.
And as I'm developing a WPF application there is no Validating event and CausesValidation property, so the others ways to validate the content is to use the TextChanged event or use binding validation.
Thank you for your answers.
Of course, in a perfectly valid program, you should not change Focus in the LostFocus event. This also applies to the Enter, GotFocus, Leave, Validating and Validated events, which Ms makes clear in the documentation https://learn.microsoft.com/pl-pl/dotnet/api/system.windows.forms.control.lostfocus.
However, in very unusual cases, you can use the timer to trigger changes to the Focus, bypassing this problem.
private TextBox tb = null;
private System.Windows.Forms.Timer MyTimer;
private void initialize()
{
MyTimer.Tick += new System.EventHandler(MyTimer_Tick);
MyTimer.Enable = false;
MyTimer.Interval = 100;
}
private void check_value(object sender)
{
tb = (TextBox)sender ;
if (!Utility.isNumeric(tb.Text)){
MessageBox.Show(tb.Text.Length.ToString());
MyTimer.Enable = true;
}
}
private void Amount_1_LostFocus(object sender, RoutedEventArgs e)
{
check_value(sender);
}
private void MyTimer_Tick(object sender, EventArgs e)
{
MyTimer.Enabled = false;
if (tb!=null) tb.Focus();
}

Categories

Resources