I'm working on a programming assignment, and I'm trying to make this button take the values from two textboxes, and calculate the new location for the form window. I'm having trouble converting the textbox values to type int, and being made usable by the btnCompute_click method.
private void btnCompute_Click(object sender, EventArgs e)
{
int x = Convert.ToInt32(txtXvalue);
int y = Convert.ToInt32(txtYvalue);
Location = new Point(x,y);
}
private void xValue_TextChanged(object sender, EventArgs e)
{
int xValue =
Convert.ToInt32(txtXvalue);
}
private void yValue_TextChanged(object sender, EventArgs e)
{
int y =
Convert.ToInt32(txtYvalue);
}
I forgot to add some additional info, the acceptable values for x and y must be positive. Would I use an if...else statement to control the acceptable values?
user29... i have no idea why death... replied that. it makes no sense to me. but you question makes sense to me. i suppose death... did not understand your question.
First off, everything you ask does not need anything in the TextChanged methods.
Do all your handling in the btnCompute_Click() method because you want to do something *when you click your button, not when the user edits the text of the text boxes, according to your question.
The code that is in your TextChanged() methods will get executed whenever the Text values of those text boxes change. that's not what you asked for it to do. But you could use these events for example, if you wanted a label to become visible or hidden and to set the text of a label which shows text, so you can use it as an error message label, for instance if the integer value of a text box is negative or even if it cannot be parsed.
So in your btnCompute_Click() methods, you first want to get the int values. You need to decide exactly what you want your code to do if the text is not integers. In my opinion, most beginners code things like message boxes or something. I like to give the user feedback with Labels or a status bar message, depending on what I feel is appropriate. Since my first choice would be to use a Label to show the 'error' message when text boxes cannot be parsed to integers, then i would simply return from the button click method without doing anything when the values are not what i want. That way the user gets their messages without annoying popup message boxes or anything. But it's up to you whether you want to pop up a message box or not. Others have given you good code to do that. I want to give you good code that avoids what i consider annoying popup boxes.
When converting strings to an int, Convert.ToInt32 will throw an error if the string cannot be parsed. int.TryParse is the silver bullet for truly parsing strings to integers without any error. Here is the entire code i would use. I made a new project just to make sure i'm not giving you buggy code. I give you my code on how I handle this.
In your updated prerequisite, you mention x & y must be positive and not negative. I note to you that these are not the same. For instance, 0 is neither positive nor negative. I assume that you technically mean that x and y cannot be negative, (and that it does not need to be positive, since 0 should be allowed).
private void Form1_Load(object sender, EventArgs e)
{
lblErrorX.Text = null;
lblErrorY.Text = null;
}
private void btnMoveForm_Click(object sender, EventArgs e)
{
int x = 0; if (int.TryParse(txtX.Text, out x) == false) { return; }
int y = 0; if (int.TryParse(txtY.Text, out y) == false) { return; }
if (x < 0 || y < 0) { return; }
this.Location = new Point(x, y);
}
private void txtX_TextChanged(object sender, EventArgs e)
{
int x = 0;
if (int.TryParse(txtX.Text, out x) == false)
{ lblErrorX.Text = "X is not an valid integer."; return; }
if (x < 0) { lblErrorX.Text = "X cannot be negative."; return; }
lblErrorX.Text = null;
}
private void txtY_TextChanged(object sender, EventArgs e)
{
int y = 0;
if (int.TryParse(txtY.Text, out y) == false)
{ lblErrorY.Text = "Y is not an valid integer."; return; }
if (y < 0) { lblErrorY.Text = "Y cannot be negative."; return; }
lblErrorY.Text = null;
}
In my project, on the form, in the following left to right order: lblX, txtX, lblErrorX. I have the same corresponding for Y: lblY, txtY, lblErrorY. Then i have one Button: btnMoveForm. So my txtX corresponds to your txtXvalue. my btnMoveForm corresponds to your btnCompute, but to me, 'compute' means to calculate, which is not really what this button is doing. this button is moving the form, so that's why i name it as such.
I have played with setting both the Location and the DesktopLocation and it seems to do the same thing. I've always used Location and i just learned that DesktopLocation works too, but since Location is shorter, i use it.
Someone asked why i don't use if(!int.TryParse(...)) { return; } rather than my if(int.TryParse(...) == false) { return; }. My reason is unfortunately that i think ! is an easy one character to miss when reading code, so i avoid it, especially when that little mistake means the opposite of what the code really would do. So my use of '== false' is always for human clarity. But i do like the C# ease of only needing one character. I just think it's a shame that in my opinion, it's a lot safer to write code that is better for humans so we don't mistake it. That's the only reason i use '== false' instead of !. Use ! if you like. It's quite convenient. I regret not using it. hehe.
Oh, and the reason i set the lblErrorX.Text = null; and lblErrorY.Text = null; is on my form in design view, i give them a text value so i can see them. :) so when the program runs, i set the Text to be blank. But you can use the Visible property if you prefer. I just leave them always visible and only set their Text properties.
Based on your expanded criteria you can check for negative numbers conditionally or use Math.Abs to get the absolute value. Something like this.
int x, y;
if (int.TryParse(txtXvalue.Text, out x) && int.TryParse(txtYvalue.Text, out y))
{
if (x < 0 || y < 0)
{
MessageBox.Show("Negative numbers not allowed");
}
else
Location = new Point(x, y);
}
else
{
MessageBox.Show("Must be an Integer");
}
or
int x, y;
if (int.TryParse(txtXvalue.Text, out x) && int.TryParse(txtYvalue.Text, out y))
{
Location = new Point(Math.Abs(x), Math.Abs(y));
}
else
{
MessageBox.Show("Must be an Integer");
}
I think you are looking for this.
private void btnCompute_Click(object sender, EventArgs e)
{
int x = Convert.ToInt32(txtXvalue.Text);
int y = Convert.ToInt32(txtYvalue.Text);
DesktopLocation = new Point(Math.Abs(x), Math.Abs(y));
}
This gets the location for the desktop. Also you need the .Text to get the text inside the textbox. You should also check to make sure the text is not null or empty before using or it will cause an error.
If this isn't what you are looking for please explain a little more.
Related
I have been trying to create an Othello game, but I can't seem to be able to check for a case that is not there (checking for a black token, and if it isn't there, dont do anything)
private void CaseClick(object sender, MouseEventArgs e)
{
Case allCases = (Case)sender;
int a = 1;
if (allCases.ColorToken == Case.Token.Nothing)
{
Case caseToModify;
if (_turnIsBlack)
{
//Verify tokens from top to bottom
if (Cases[allCases.Position.X, allCases.Position.Y + a].ColorToken == Case.Token.White)
{
while (Cases[allCases.Position.X, allCases.Position.Y + a].ColorToken == Case.Token.White)
{
caseToModify = Cases[allCases.Position.X, allCases.Position.Y + a];
allCases.ColorToken = Case.Token.Black;
caseToModify.ColorToken = Case.Token.Black;
a++;
caseToModify.Refresh();
allCases.Refresh();
_turnIsBlack = false;
}
}
}
}
}
I was just wondering if there was a way to check for the black token that isn't there. Doesn't need to be for this specific code, just an example of checking for something, and if it is not there, do nothing
The position is assigned with coordinates like (0,0) (1,1), the game is an 8x8 with each case being assigned a coordinate
It's completely fine that way. These kind of statements are pretty common and although sometimes you may be able to write some fancy stuff my advice is to keep it simple unless the performance is super crucial.
I want to create a form that allows the user to set a certain amount of points in five different fields (NumericUpDown). When that amount of points reaches 0, the user can't add any more. (I still want the user to be able to remove points, though.)
Here is my code so far:
private void calculateValue() {
decimal tempValue = CMB_num_Aim.Value + CMB_num_Reflexes.Value +
CMB_num_Positioning.Value + CMB_num_Movement.Value + CMB_num_Teamwork.Value;
controlValue = currentValue - tempValue;
MyBox.CMB_tb_cv.Text = controlValue.ToString();
}
This Method (calculateValue) is calculates how many points the user have left (controlValue).
private void CMB_num_Aim_ValueChanged(object sender, EventArgs e) {
calculateValue();
if (controlValue < 0) {
//Prevent Default here
MessageBox.Show("You are out of points!");
}
}
This method (CMB_num_Aim_ValueChanged) fires when the value of the NumericUpDown control has changed. I have one of these for each field, each doing the same thing.
The method fires as expected, but I can't prevent it from happening - the user can apply more points than they have. How can I prevent the user from applying more points?
(I thought about making a mouseUp method, but I don't know if the user will use the mouse or if he will type in the value using the keyboard.)
Seems like you want to create a point distribution system between some skills - aim, movement, teamwork etc. You can do that easily by setting Maximum value of NumericUpDown control when you enter it. Subscribe all skill updown controls to the same event handler:
private void SkillNumericUpDown_Enter(object sender, EventArgs e)
{
var skill = (NumericUpDown)sender;
var availablePoints = 42;
var maxSkillPoints = 20; // usually you cannot assign all points to one skill
var unassignedPoints = availablePoints - SkillPointsAssigned;
skill.Maximum = Math.Min(maxSkillPoints, unassignedPoints + skill.Value);
if (unassignedPoints == 0)
{
MessageBox.Show("You are out of points!");
return;
}
if (skill.Value == maxSkillPoints)
{
MessageBox.Show("Skill maximized!");
return;
}
}
private decimal SkillPointsAssigned =>
CMB_num_Aim.Value +
CMB_num_Reflexes.Value +
CMB_num_Positioning.Value +
CMB_num_Movement.Value +
CMB_num_Teamwork.Value;
Benefit - you will not be able to input illegal value neither by arrows nor manually.
Replace
if (controlValue < 0) {
By
if (controlValue <= 0) {
My problem is when the user clicks on myButton the program operates perfectly fine. But if the user was to input a value less than 3 in the first textbox a message box will appear to the user stating that the value must be greater than 3 metres. If you click OK the next method in myButton runs anyway and the result message box appears anyway.
I've tried looking around to solve this problem of mine using Nested For Loops but failed to get them to work (most likely a fault on my end). I also prefer not to use Goto because it isn't exactly good programming practice to use. Of course you can tell me otherwise if you want :) .
// Button
private void myButton_Click(object sender, EventArgs e)
{
checkIfNumericalValue();
testIfTextBoxOnesMinimumIsMet();
testIfTextBoxTwosMinimumIsMet();
displayResultToUser();
resetOrClose();
}
// Textbox One
public void testIfTextBoxOnesMinimumIsMet()
{
if (length < 3)
{
MessageBox.Show("length must be greater than 3 metres");
}
}
Help would be greatly appreciated this is also my second attempt at C# on Visual Studio 2012. Do not worry this has nothing to do with my year 10 schooling as my school doesn't have a programming subject. This problem occurs in testIfTextBoxOnesMinimumIsMet() and testIfTextBoxOnesMinimumIsMet() as well but if someone can help me with this one method I should be able to fix the rest :)
You could throw an exception from your inner functions and catch it from your button's function, something like this:
// Button
private void myButton_Click(object sender, EventArgs e)
{
try
{
checkIfNumericalValue();
testIfTextBoxOnesMinimumIsMet();
testIfTextBoxTwosMinimumIsMet();
displayResultToUser();
resetOrClose();
}
catch (ArgumentException ex)
{
// The error message we defined at the exception we threw
MessageBox.Show(ex.Message);
}
}
// Textbox One
public void testIfTextBoxOnesMinimumIsMet()
{
if (length < 3)
{
throw new ArgumentException("Length must be greater than 3 meters.");
}
}
An alternative would be to deal with the validation within your button like so:
// Button
private void myButton_Click(object sender, EventArgs e)
{
checkIfNumericalValue();
if (length < 3)
{
MessageBox.Show("Length must be greater than 3 meters.");
return;
}
testIfTextBoxTwosMinimumIsMet();
displayResultToUser();
resetOrClose();
}
What happens above is that the return will leave that function without further processing anything else.
So, if I'm understanding this correctly, if the text boxes contain numerical values, text box 1 meets the minimum and text box 2 meets the minimum, you want to displayResultToUser() and then resetOrClose().
If that's the case, you can have the 3 methods checkIfNumericalValue(), testIfTextBoxOnesMinimumIsMet() and testIfTextBoxTwosMinimumIsMet() return a bool depending on what the minimum condition is and then write something like this:
private void myButton_Click(object sender, EventArgs e)
{
if (checkIfNumericalValue() && testIfTextBoxOnesMinimumIsMet(Convert.ToInt32(txtBoxOne.Text)) && testIfTextBoxTwosMinimumIsMet(Convert.ToInt32(txtBoxTwo.Text)))
{
displayResultToUser();
resetOrClose();
}
}
public bool testIfTextBoxOnesMinimumIsMet(int length)
{
if (length < 3)
{
MessageBox.Show("length must be greater than 3 metres");
return false;
}
return true;
}
It appears that you need some other variable to track whether or not you have encountered errors. To do this, you could have a bool noErrors variable defined, and you should return a boolean from your error check methods that is True if there were no errors, otherwise False. This way you know if you ran into any problems.
Finally, you should check for the state of errrorsFound before running any of your other methods.
For example:
// Button
private void myButton_Click(object sender, EventArgs e)
{
bool noErrors =
isNumericalValue() &&
textBoxOnesMinimumIsMet() &&
textBoxTwosMinimumIsMet();
if (noErrors)
{
displayResultToUser();
resetOrClose(); // I'm not sure if this should happen regardless of errors?
}
}
// Textbox One
public bool textBoxOnesMinimumIsMet()
{
if (length < 3)
{
MessageBox.Show("length must be greater than 3 metres");
return false;
}
return true;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# GUI application that stores an array and displays the highest and lowest numbers by clicking a button
This is updated from 13 hours ago as I have been researching and experimenting with this for a few. I'm new to this programming arena so I'll be short, I'm teaching myself C# and I'm trying to learn how to have integers from a user's input into a textbox get calculated from a button1_Click to appear on the form. Yes, this is a class assignment but I think I have a good handle on some of this but not all of it; that's why I'm turning to you guys. Thanks for all of the advice guys.
I'm using Microsoft Visual Studio 2010 in C# language. I'm using Windows Forms Application and I need to create a GUI that allows a user to enter in 10 integer values that will be stored in an array called from a button_Click object. These values will display the highest and lowest values that the user inputted. The only thing is that the array must be declared above the Click() method.
This is what I have come up with so far:
namespace SmallAndLargeGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void inputText_TextChanged(object sender, EventArgs e)
{
this.Text = inputText.Text;
}
public void submitButton_Click(object sender, EventArgs e)
{
int userValue;
if(int.TryParse(inputText.Text, out userValue))
{
}
else
{
MessageBox.Show("Please enter a valid integer into the text box.");
}
int x;
x = Convert.x.ToString();
int squaredResults = squared(x);
int cubedResults = cubed(x); squared(x);
squaredLabel.Text = x.ToString() + " squared is " + squaredResults.ToString();
cubedLabel.Text = x.ToString() + " cubed is " + cubedResults.ToString();
}
public static int squared(int x)
{
x = x * x;
return x;
}
public static int cubed(int x)
{
x = x * squared(x);
return x;
}
}
}
Now I can't run this program because line 38 shows an error message of: 'System.Convert' does not contain a definition for 'x' Also I still have to have an array that holds 10 integers from a textbox and is declared above the Click() method. Please guys, any help for me? This was due yesterday.
As a couple of comments have mentioned, there really isn't enough information here to provide you with a useful answer. There are two main User Interface frameworks in .Net for windows applications. One of these is commonly referred to as "WinForms" and the other is "WPF" or "Windows Presentation Foundation."
I'm going to go with you are most likely using WinForms as it is the older of the two technologies. The approach here can be used on both sides with a little tweaking. Setting text in a text box is very similar to setting text programaticly on a label. You can get more detail on that on MSDN: How to: Display Text on a Windows Form; How to: Use TextBox Controls to Get User Input.
If you are using WPF the "back end" code is pretty much the same. You just need to make sure your textbox has an x:Name="userInputTextBox" so you can reference it in your code behind. Be mindful that your users can input "1", "3" or "abcd" in the field. Ensuring your app doesn't bomb is most likely outside of the assignment but feel free to look up C# int.TryParse(...) and "Try Catch" :-)
Your button handler could look like this:
void btnUserClick_Click(object sender, System.EventArgs e)
{
int userValue;
if(int.TryParse(txtUserInput.Text, out userValue))
{
// We have the value successfully, do calculation
}
else
{
// We don't have the users value.
MessageBox.Show("Please enter a valid integer into the text box.")
}
}
In your retrieveInput_Click handler you are assigning the min/max numbers to a local int. Once you determine your min/max numbers in the logic, you will need to assign those local integers to a UI element for display.
Since we don't have any details on your specific UI choices, one simple solution could be to add 2 labels to your form, and then in the code you would place the result in the label:
for (int i = 0; i < numbers.Length; ++i)
{
if (numbers[i] < min)
min = numbers[i];
if (numbers[i] > max)
max = numbers[i];
}
// Assign Minimum to Label1
Label1.Text = "Minimum Value: " + min.ToString();
// Assign Maximum to Label2
Label2.Text = "Maximum Value: " + max.ToString();
define the textbox named textbox1 or txt_name
you can write the button1_Click function :
int i_value = Convert.ToInt16(txt_name.Text);
ok. I haven't try catch the exceptions.... :(
maybe above answer is right.
btw, i think this question mainly focus on how to get int type from text box. right?
I am trying to get this piece of code working in C#, what I want to do is if a textfield is updated to validate its an integer (HP is an integer).
So by attempting to convert the input to an integer, I either get a new integer, and sets the value to it, or if it fails, it takes the previous verified value and pushes back to the text field (pretty much ignoring the input, updating it, and it is now a validated input).
In my head this is all logic and working, in effect its not. Please help.
private void Input_HP_TextChanged(object sender, EventArgs e)
{
Try
{
HP = Convert.ToInt32(Input_HP.Text);
}
catch(Exception e)
{
Input_HP.Text = HP;
}
}
You can use try.parse, but you will want to set it to a temporary variable. In your case, using HP will overwrite your variable you want to save.
int tempInt;
if(Int32.TryParse(Input_HP.Text, out tempint))
{
HP = tempInt;
}
else
{
Input_HP.Text = HP.ToString();
}
Int.TryParse is probably what you are looking for:
int HP;
if (int.TryParse(Input_HP.Text, out HP))
{
// the number is an integer at this point
}
If HP is an integer you cannot directly assign it to the Text property because this is of type String. This should be a compile time error, for this part of the code you should be using the .ToString() function...
Input_HP.Text = HP.ToString();
Of course, you should be using a TryParse for this conversion anyway. I guess what you want is something like this...
private void Input_HP_TextChanged(object sender, EventArgs e)
{
int i = 0;
if(int.TryParse(Input_HP.Text, out i))
{
HP = i;
}
else
{
Input_HP.Text = i.ToString();
}
}