Show items (checkboxes, radiobuttons etc...) by case (if...else...etc...) - c#

I am trying to make a little game in C#.
The program asks the user for a any number.
The user then presses "GO" (button1) and the program checks whether the number is an even number or not. (x % 2 == 0)
I'm trying to get the program to show 4 checkboxes/radio buttons out of total of 8 depending on each case.
For example:
If the number is an EVEN NUMBER: The program will show options 2,5,3,6.
If the number is an ODD NUMBER: The program will show options 1,4,7,8.
(Options 1-8 were already included in the design.)
I need help with the if (x % 2 == 0) part. What do I write in it to make the checkboxes/radiobuttons appear or disappear?
By the way, is there a way to ask the user for a number without him having to click "GO"?
Like, use ENTER instead. If yes, what event is that?
Also, is there a way to limit the textbox to INT only?
I know it's asking you to do the job, but I have tried, and I'm still a real beginner, therefore I think my way of learning is by actually experiencing it.
public partial class Form1 : Form
{
int x;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
x = int.Parse(textBox1.Text);
if (x % 2 == 0)
{
}
}
}

The Visible property of the CheckBox (inherited from Control) will aid you in making the needed controls visible when you wish them to be. Your if would look something like,
if (num % 2 == 0)
{
box1.Visible = false;
box2.Visible = true;
// ...
}
else
{
box1.Visible = true;
box2.Visible = false;
// ...
}
However, this can be optimized a bit by using the condition to set the visibility of all the CheckBoxs at the same time instead of coding two conditionals - something like:
box1.Visible = !(num % 2 == 0);
box2.Visible = (num % 2 == 0);
// ...
As for on pressing enter, check the OnKeyDown event for you control, you can do this through the designer. Your event method would look like:
private void myControl_OnKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// Handle enter key pressed here
}
}
This should help you with your problems.
ADDITIONAL RESPONSE
List<CheckBox> boxes = new List<CheckBox>();
// Add all boxes and do other stuff, disable all
foreach (CheckBox box in boxes)
{
box.Visible = false;
}

In order to limit the textbox to int, you could override OnKeyPressed. As for your checkboxes, you could use the Visible or Checked properties.

Related

How do I capture the "Enter" key in a windows form?

I am trying to get the text of a textbox and save it to a variable when the user presses the enter key (when the textbox has info and is focused) since this is already inside a method i haven't been able to put another method inside like txtbox1_keypress (or i've been doing it wrong) so I need to be just code lines that i can insert in this method
private void df1_Click(object sender, EventArgs e)
{
txtres.Focus();
//timer
timeLeft = 50;
timer1.Start();
//mult
do
{
ban = 0;
m1 = r.Next(1, 4);
txtm1.Text = m1.ToString();
m2 = r.Next(2, 6);
txtm2.Text = m2.ToString();
res = m1 * m2;
//here is where i want to read txtm2 and continue with the rest
if(txtres.Text == res.ToString())
{
pun++;
}
ban++;
} while (timeLeft > 0 || ban != 10);
if(pun == 10 && level == 0)
{
level++;
System.IO.File.WriteAllText(#".\level.lvl", level.ToString());
}
}
Since you mentioned you want to run it inside KeyPress event, here is the example:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (int) Keys.Enter)
{
//do the logic
}
}
Add a button as the accept button of the form, this will trigger whenever enter is pressed.
Also, your loop (do -- while) should be done within the timer1_tick method, and take out the loop, the timer will execute the code within every interval it ticks until the timer reaches your maximum of 50.
As was mentioned, the loop will kill your GUI and it wont allow input.

NumericUpDown error MessageBox

I would like to ask what code should I insert to to my "numGPA" to inform the user that they have exceeded the "maximum".
Right now if the try to "submit" a value above the maximum, my visual studio will only play a "ding" sound.
Instead of that I would like to have a message box that says something like "Only a value from 0 to 4 is allowed"
I found this code on Google and despite me changing the numericUpDown1 to numGPA it does not work.
if (numGPA.Value >= 4 || numGPA.Value <= 0)
{
MessageBox.Show("Error. Number must be between 0 and 4");
numGPA.Value = 1;
numGPA.ReadOnly = true;
}
Do take a look at this video to get a clear picture of what I am saying
https://www.youtube.com/watch?v=XVv-it6x044&feature=youtu.be
Instead of the "ding" sound effect played #0.06, I would like a MessageBox.
You can do that with the TextChange event. You can (and should) also set the minimum and maximum properties to limit the input with the arrows.
Private Sub NumericUpDown1_Changed(sender As Object, e As EventArgs) Handles NumericUpDown1.TextChanged
If IsNumeric(NumericUpDown1.Text) AndAlso _
CInt(NumericUpDown1.Text) > NumericUpDown1.Maximum Then MsgBox("Oops! Too big.")
End Sub
The best way is to let the user edit and only check when he has finished. This will trigger the ValueChanged event.
Here we can get at the entered value by grabbing the internal TextBox control.
I suggest using a helper function, maybe like this:
void nudCheck(NumericUpDown nud)
{
TextBox tb = (TextBox) nud.Controls[1];
if (Convert.ToInt32(tb.Text) > nud.Maximum)
{
string msg = tb.Text + " is too large! Setting value to maximum: " + nud.Maximum;
tb.Text = "" + nud.Maximum;
nud.Value = nud.Maximum;
// do what you want with the message string!
//MessageBox.Show(msg); // not recommended!
toolTip1.Show(msg, nud); // add a ToolTip component to your form for this!
}
}
Call it here:
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
nudCheck(numericUpDown1);
}
We also want to suppress the error sound for the case when the user presses Enter, best in the KeyDown event..
private void numericUpDown1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
nudCheck(numericUpDown1);
e.SuppressKeyPress = true;
}
}
Note that bringing up an actual MessageBox will bring back the bell sound and force the user to get rid of it. So I have used a ToolTip, but a Label would also work, if you have the space..
Obviously you may want to add similar code to check input lower than the Minimum..

How to assign a value to a checkbox and use it in a formula?

I'm very new to all this programming and c# windows application, so go easy on me.
Basically I have 13 checkboxes which I want to assign values to, so when the checkboxes are checked those value goes into a formula:
consumption = energy * 15 / 1000
The "energy" is representing the checkboxes. I want all checked checkBoxes values to go there.
If its not possible to assign a value, what is the best way of doing it?
The only way I know is doing the following for each one:
if (checkBox1.CheckState == CheckState.Checked)
{
energy += energy + 1200;
}
I would like to do a foreach method but I don't know how to.
You can store the values in the Tag property of the Checkbox control and you can do a foreach on Form.Controls check if it is an instance of CheckBox and perform your logic.
An example
int energy = 0;
foreach(Control control in this.Controls)
{
//you can have additional checks like name starts with to identify energy checkboxes
if (control is CheckBox)
{
energy = energy + Convert.ToInt32(control.Tag);
}
}
If yo have exactly 13 check box control, you can do that this way
First you have to set the CheckedChanged event in every check box to the next event
private void All_CheckedChanged(object sender, EventArgs e)
{
//Check if all the checkboxes are checked
if(checkBox1.Checked && checkBox2.Checked ... && checkbox13.Checked)
{
//If they are checked calculate your value with your formula
var energy = EvaluateEnergy();
}
}
Then the EvaluateEnergy can be something like this
private int EvaluateEnergy()
{
var energy = 0;
if(checkBox1.Checked)
{
//Assign to every check box a energy value e.g 10
energy += 10;
}
if(checkBox2.Checked)
{
//e.g 20
energy += 20;
}
......
return energy + 1600;
}
So assuming energy is a member in your class and you have a method to compute the consumption like:
public partial class Form1 : Form
{
private double energy;
....
public double consumption
{
get { return energy*15.0/1000; }
}
(note the double and 15.0/1000 because 15/1000 is integer division and is 0)
You can then add an event for all your checkboxes that increments/decrements energy by 1200 whenever one is checked or unchecked:
private void CheckedChanged(object sender, EventArgs e)
{
energy += ((CheckBox) sender).Checked ? 1200 : -1200;
}
(energy be equal to 0 when all checkboxes are unchecked)
you can add the event to each checkbox in the designer:

How to restrict user to TextBox if value entered is incorrect

In my program I have a TextBox who's value must be set in a specific integer range. If it is not within this range, it should warn the user and then highlight the incorrect text inside of the TextBox for re-editing (implying that the user must enter a value that is in the correct range before they are allowed to leave the TextBox). How would I change my code so that it performs these operations?
This is what I have so far. I am using a TextChanged event. This code warns the user about the restriction breach and refocuses (I would like to highlight the value instead) on the TextBox, but does not prevent the user from clicking out of it afterward:
int maxRevSpeed;
//Max Rev Speed -- Text Changed
private void maxRevSpeed_textChanged(object sender, RoutedEventArgs e)
{
if (maxRevSpeed_textBox.Text == "" || maxRevSpeed_textBox.Text == " ")
maxRevSpeed = 0;
else
{
maxRevSpeed = Convert.ToInt32(maxRevSpeed_textBox.Text);
if (maxRevSpeed <= 0 || maxRevSpeed > 45)
{
MessageBox.Show("Reverse Sensor speed must be between 0 and 45 FPM", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
}
maxRevSpeed_textBox.Focus();
}
}
Please note that this question is a revisit of a former question of mine. I am aware that it may be "frowned upon" to take this approach to a TextBox, but regardless I would still like to figure out how to implement such a thing. Thank you.
Update 1:
After looking at everyone's suggestions I have updated my code:
//Max Rev Speed -- Text Changed
private void maxRevSpeed_textChanged(object sender, RoutedEventArgs e)
{
if (maxRevSpeed_textBox.Text == "" || maxRevSpeed_textBox.Text == " ") //Is Empty or contains spaces
maxRevSpeed = 0;
else if (!Regex.IsMatch(maxRevSpeed_textBox.Text, #"^[\p{N}]+$")) //Contains characters
maxRevSpeed = 0;
else
maxRevSpeed = Convert.ToInt32(maxRevSpeed_textBox.Text);
}
//Max Rev Speed -- Lost Focus
private void maxRevSpeed_LostFocus(object sender, RoutedEventArgs e)
{
if (maxRevSpeed <= 0 || maxRevSpeed > 45)
{
MessageBox.Show("Reverse Sensor speed must be between 0 and 45 FPM", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
//Supposed to highlight incorrect text -- DOES NOT WORK
maxRevSpeed_textBox.SelectionStart = 0;
maxRevSpeed_textBox.SelectionLength = maxRevSpeed_textBox.Text.Length;
}
}
The integer representing the text in the textBox is now dealt with in the textChanged event. The LostFocus event handles the warning and the re-selection of the incorrect text value. However, the highlight text method works when it is in the textChanged event, but not in it's current location. Why is that, and how can I fix it?
If you just want to stop focus from leaving a TextBox, all you need to do is to set the Handled property of the KeyboardFocusChangedEventArgs object to true in a PreviewLostKeyboardFocus handler when your invalid condition is true:
private void PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
e.Handled = IsInvalidValue;
}
This of course assumes that you have a property named IsInvalidValue that you set to true when the entered data is invalid and false otherwise.
You can prevent the user from entering the text or out of range by using PreviewTextInput handler of textbox, call it like this.
private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!char.IsDigit(e.Text, e.Text.Length - 1))
{
e.Handled = true;
}
}
The code above is for entering numbers only, you can change it according to your requirements, hope it helps :)
Hi I suppose you are using C#, here you can find a relevant post: C# auto highlight text in a textbox control
As they stated the following code should select the text inside texbox
In Windows Forms and WPF:
maxRevSpeed_textBox.SelectionStart = 0;
maxRevSpeed_textBox.SelectionLength = textbox.Text.Length;

Tabbing within a textbox - Tab between value before and after decimal point

I am newbie to Winform C#. Now I am in a challenging requirement, but it may be silly for you guys.
Could any of you please help me with the code for my requirement below.
I have a textbox for decimal value (Amount) in Winform app. I have kept good validations etc. It allows only 2 digits after decimal point. Also if the user tabs from previous control to this textbox, the whoe value (Decimal number in the textbox say for example "22223.39" will be highlighted). All good.
But my business user wants like, if he tabs from previous control to this textbox, and supposing they want to change the digits after the decimal point alone in the above example i.e "39" they want to tab and just keyin so that it will only be overwrited with a new value and the value "22223" will stay still. They should be able to back front and back again.
i.e its like, in simple words, if the user tabs within a textbox, it should first go to the number field and highlight the number (In above example it should highlight "22223" and then if the user again presses tab, it should go and highlight the digits after decimal (In above example 39"). I am unsure how to do it. And, if the user again presses the tab for 3rd time, it should move to the next control/textbox(Asusual).
But I got idea of keeping 2 textboxes, which is silly. I want exact same functionality what I mentioned and only in textbox and its C# Winform app.
Also I dont need the numeric updown control which has got some limitations wrt our requirement.
As Jeremy Thompson rightly says, this is a bad idea so you should probably try and convince the user to use some other more standard input method.
That said, mainly as an exercise in seeing if I could make this work I came up with the following subclassed textbox control that behaves correctly in every trial I could think of off the top of my head. That includes things like correctly tabbing in and out of the textbox as well as highlighting the decimal part again when left arrowing backwards.
The main trick is the IsInputKey override - the rest of the code came from me testing things. If you do end up using something based on this please test it thoroughly since as with any warping of standard control functionality it is likely to have odd corner case gotchas.
public class TabTextBox : TextBox
{
public bool ready_to_leave = false;
protected override void OnEnter(EventArgs e)
{
this.SelectionStart = 0; // this.Text.IndexOf(".") + 1;
this.SelectionLength = this.Text.IndexOf(".");
}
protected override bool IsInputKey(Keys keyData)
{
if (keyData == Keys.Tab && !ready_to_leave)
{
return true;
}
else
{
return base.IsInputKey(keyData);
}
}
protected override void OnLeave(EventArgs e)
{
ready_to_leave = false;
base.OnLeave(e);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (ready_to_leave)
{
e.Handled = true;
}
base.OnKeyPress(e);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyData == Keys.Tab && !ready_to_leave)
{
this.SelectionStart = this.Text.IndexOf(".") + 1;
this.SelectionLength = 2;
ready_to_leave = true;
e.Handled = true;
}
else
{
base.OnKeyDown(e);
}
}
protected override void OnKeyUp(KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
if (this.SelectionStart - 1 < this.Text.IndexOf("."))
ready_to_leave = false;
}
base.OnKeyUp(e);
}
}
Its not a good idea, it goes against standard operation of window applications.
Plus you'll have to turn off TabStop on your controls and do the Tabbing yourself. I would talk to the user with the above in mind and ask if pressing the "." would be good enough to highlight the decimal places. Here's some code to demonstrate my proposed solution:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 190 && textBox1.Text.IndexOf(".") > 0)
{
textBox1.SelectionStart = textBox1.Text.IndexOf(".") + 1;
textBox1.SelectionLength = 2;
e.SuppressKeyPress = true;
}
}
If you want multiple textboxes to share this functionality, go into the InitializeComponent() and do the following:
this.textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);
this.textBox2.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);
this.textBox3.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);

Categories