Addition using a single TextBox - c#

I am writing a c# windowsform application for addition of two entries in a single text box.
I have 1 text box, 1 add button and 1 result button.
I need to achieve following algo,
User enter the no in text box. It will be stored in int n1.
User will press add button. At this time the content of the textbox.text will be get cleared and user must be able to enter the secound value in it.
This secound value will get stored in int n2.
Now when user click on result button he should get int result=n1+n2
I have written following in add buttons's click event,
n1=convert.Int32(textbox1.text);
textbox1.text="";
n2=convert.Int32(textbox1.text);//exception occures here
And result button's click event has,
textbox1.text=result.tostring();
I leanred the working of this program and find out that it is due to NULL value assignment to int n2.
I am bit confused how can I achieve above problem using single textbox?
Is there any way to provide the textbox.txt value through user through textbox field only?
Is there any property of textbox which I need to set?
I am very new to .net! Please help!
Thanks in advance for your kind attention!

move n2 = Convert.Int32(textbox1.Text); to your result button's click event
Add button click event:
n1=convert.Int32(textbox1.text);
textbox1.text="";
result button's click event:
n2=convert.Int32(textbox1.text);
result=n1+n2;
textbox1.text=result.tostring();

try something like this:
private int result=0;
addMethod()
{
//here you can use also int.TryParse
if(string.isnullorempty(textbox1.text.trim()))
textbox1.text="0";
result+=convert.toint32(textbox1.text);
textbox1.text=string.empty;
}
resultMethod()
{
textbox1.text=result.tostring();
}

look at the folloing code
private int i = 0;
private int[] a = new int[2];
private void button1_Click(object sender, EventArgs e)
{
int b;
if(Int32.TryParse(textBox1.Text, out b))
{
a[i] = b;
i++;
textBox1.Text = "";
}
else
{
MessageBox.Show(#"Incorrect number");
}
}
private void resultbutton2_Click(object sender, EventArgs e)
{
int sum = a[0] + a[1];
MessageBox.Show("Sum: " + sum);
}
}

You code contains a couple of errors:
You are using Int32 Convert.ToInt32(String) which is bad, because will throw an exception if the user enters something that can't be cast to an Int32, you should use Boolean Int32.TryParse(String, out Int32) instead, and check if the conversion is successful.
You are calling n2 = Convert.ToInt32(textbox1.Text); right after you set textbox1.Text = ""; and this is also bad, because it won't wait for a user input, it will try to convert an empty string to an integer right away, which will yield an exception.
You can't know when the user has finished inserting his number, so you have to rely to something external to the TextBox to let you know you should perform the addition.
Try the following:
Place a TextBox.
Place a Button.
Initialize a "grandTotal" integer variable to zero.
When the user press the button, parse the content of the TextBox in a temporary "submittedValue" integer variable, then sum this temporary variable to your "grandTotal" variable, and display the resulting "grandTotal" variable value.
This way you'll be able to continuously perform the addition operation on the previous total.
Example
The global variable:
protected Int32 GrandTotal = 0;
The Button click event handler:
Int32 currentValue = 0;
if (Int32.TryParse(userValue.Text, out currentValue))
{
GrandTotal += currentValue;
MessageBox.Show(String.Format("The new total is: {0}", GrandTotal));
}
else
{
MessageBox.Show("Invalid value!");
}

I have no idea why you are doing it in this fashion.
Still you can do this as
Declare n1, n2 as int? at the form level
Then in your Add click event do it in this fashion
if (! n1.HasValue)
{
n1 = int.Parse(textBox1.Text);
}
n2 = int.Parse(textBox1.Text);
textBox1.Text = "";
if you are going to do this for lotz of number then use List<int?> myIntList = new List<int?>() and your add event would be
myIntList.Add(int.Parse(textBox1.Text));
textBox1.Text = "";
and the result is int? result = myIntList.Sum();

Related

How do you add something to an uninitialized variable? c#

Im trying to make a cookie clicker style thing where every time you click something it adds 1 to a variable. Im trying to do int clicks = clicks + 1 but it says that it is use of an uninitialized variable. I tried to set int clicks = 0 but then it says that clicks is already defined in the scope. I tried to see if i could do something like if (clicks == null) but obviously it cant check it because it is not a variable. I have only used c# for like a day, can someone please help?
private void cookie_Click(object sender, EventArgs e)
{
int clicks = 0;
clicks = clicks + 1;
numClicks.Text = "" + clicks;
}
^ this is the code. i also realized when i click it, it resets itself to 0 and goes back to 1, so it cant go 1, 2, 3 etc. is there a way to set the variable when the form starts and then start to add on clicks? im so dumb
int clicks = clicks + 1;
Is indeed nonsensical. This is the code that is declaring and initializing clicks, so it makes perfect sense that we can't ask "what is the value of clicks?" (in order so we can add one to it); until we have definitely assigned a value to clicks, the value is undefined.
Instead:
int clicks = 0;
And then when you want to increment it:
clicks++;
You'll want to do something like this:
int clicks = 0;//Define an integer 'clicks' and set it to 0
//and in your click handler:
clicks = clicks + 1;//Increment your count.
Note:
Clicks is an integer, it can never be null. (look up c# primitives for more info)
Using int clicks = clicks + 1 doesn't make sense. At the right side of the equation, what's the value of clicks? It's not defined yet.
The problem with your implementation is that every time the function gets called the first thing it does is sets clicks to 0. You need to initialize it outside of the function to avoid this. If you initialize it in the class it will be set to 0 initially when the class is created then you can increase the value everytime the functions is called. Not sure exactly your use case but without more information I would recommend doing something like this.
class YourClass {
// initialize outside of the function that increases the counter
int clicks = 0;
// rest of the code in class
private void cookie_Click(object sender, EventArgs e)
{
clicks++;
// this would also work: clicks = clicks + 1;
numClicks.Text = "" + clicks;
}
}

How can I increase one of two numbers in a comparative statement with a button click

I'm making a little UWP app in C# that simulates drawing straws. The problem that I'm having is that I want the user to get to a point where they click a button, and the variable baseNumber (initially set to 2 -- the fewest amount of drawn straws to make any sense) is compared to a randomly generated number that is passed through from another button event. I have this part down.
The part that is giving me fits is that I want the next user to then click the same button, and I want the baseNumber incremented by 1, and have that new number compared to the losingStraw. If that user is declared safe, I want the number to increment again for the next user with their button click, until ultimately the numbers equal each other, a user draws the short straw, and another code path is taken.
I'm very new to coding, so what I want might not even be possible. Here's an example of what I've tried, below. I have also tried variants on a do / do while and a for loop.
If I could somehow stop something like a for loop at each pass and make it wait for user input (the button press), that would be ideal. I couldn't figure that out either though.
Any help or ideas you can offer would be greatly appreciated!
private void drawButton_Click(object sender, RoutedEventArgs e)
{
int baseNumber = 2;
int losingStraw = Convert.ToInt32(drawButton.Tag);
if (baseNumber < losingStraw)
{
instructions.Text = "You are safe!";
baseNumber = baseNumber++; // that doesn't work at all. I was hoping that baseNumber
}
else
{
instructions.Text = "You have drawn the losing straw";
}
}
You have to write baseNumber++; instead of baseNumber = baseNumber++; since ++ aka the unary operators helps increases integer value by one. Thus baseNumber++; means baseNumber = baseNumber + 1;
Edit
In your case the variable int baseNumber = 2; has been declare and initialized in the event itself thus every-time the event is fired the baseNumber will be initialized by 2 and you would not be able to see any changes. Thus you can do something like this
int baseNumber; // you can do 2 here as well
public YourFormName()
{
baseNumber = 2;
}
private void drawButton_Click(object sender, RoutedEventArgs e)
{
int losingStraw = Convert.ToInt32(drawButton.Tag);
if (baseNumber < losingStraw)
{
instructions.Text = "You are safe!";
baseNumber = baseNumber++; // that doesn't work at all. I was hoping that baseNumber
}
else
{
instructions.Text = "You have drawn the losing straw";
}
}
Just put the baseNumber outside the method, can be globally declared so that everytime you increment it, it will never to reset to 2 again when entered on butotn click :) -HAPPY CODING-
public class YourClass
{
int baseNumber = 2;
private void drawButton_Click(object sender, RoutedEventArgs e)
{
int losingStraw = Convert.ToInt32(drawButton.Tag);
if (baseNumber < losingStraw)
{
instructions.Text = "You are safe!";
baseNumber = baseNumber++; // that doesn't work at all. I was hoping that baseNumber
}
else
{
instructions.Text = "You have drawn the losing straw";
}
}
}

Convert string from TextBox to Number in WPF

I have an application with four text boxes. I want user to be able to enter a value in the first three text boxes. The fourth will give the result (box1 + box2 + box3) / 3.
My textboxes look like this.
private void rBox_1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
CheckIsNumber(e);
}
And a function to let user enter only digits.
private void CheckIsNumber (TextCompositionEventArgs e)
{
int result;
if (!int.TryParse(e.Text, out result))
{
e.Handled = true;
}
}
The problem is I don't know how to convert and store a value from each textbox in an int.
I've created a null int value to store. In public MainWindow().
int box1_value;
And for function I did this.
public static int GetNumber (string arg)
{
int number = Int32.Parse(arg);
return number;
}
When I'm trying to apply this function this way, nothing happens. Program won't start, no errors, though.
public MainWindow()
{
InitializeComponent();
int box1_value = GetNumber(rBox_1.Text);
}
Remove the
int box1_value = GetNumber(rBox_1.Text);
from your mainwindow constructor.
You're parsing a string.Empty value to int in which the compiler will automatically halt during compilation. Hence your awkward error.
Create a new function called Calculate for calculating your values
private void Calculate()
{
if(string.IsNullOrEmpty(rBox_1.Text) ||
string.IsNullOrEmpty(rBox_2.Text) ||
string.IsNullOrEmpty(rBox_3.Text))
return;
var box1 = GetNumber(rBox_1.Text);
var box2 = GetNumber(rBox_2.Text);
var box3 = GetNumber(rBox_3.Text);
rBox_4.Text = ((box1 + box2 + box3)/3).ToString();
}
You have 2 options for adding the Calculate function:
add it in each rBox_1_PreviewTextInput function as follows:
if(e.Handled)
{
Calculate();
}
or create a button (named button1)
private void button1_Click(object sender, EventArgs e)
{
Calculate();
}
Some Comments: why the string.IsNUllOrEmpty in Calculate?
-> Your GetNumber function does not catch any false string values like Empty. Or you work with tryparse in the GetNumber function or you catch the empty values before you go into the function.
Try using TryParse Method :
int number = Int32.Parse(arg); /*Instead of this line in your code use below.*/
A possible duplicate thread
I would Suggest that you should Add validation to your 1st 3 Test-boxes using PreviewTextInput in that way, you do not have to try parse int in your c# code and will reduce the chance of errors in your code

TextBox accepts only int

I have a problem with my textbox. I wanted that one can manually set the interval of the x- and y-axis for a chart in the GUI over two textboxes. That works but when I type a char in or when I typed an int in and delete it, the program crashes immediately and I get a System.FormatException (without clicking the button to accept the changes). How can I solve it that one can just type in different signs without immediately crashing the program? My code below:
public void textBox2_TextChanged(object sender, EventArgs e)
{
x_axis_num = Convert.ToInt32(xAxisBox.Text, usC);
}
private void yAxisBox_TextChanged(object sender, EventArgs e)
{
y_axis_num = Convert.ToInt32(yAxisBox.Text);
}
That gets passed to another event:
chart1.ChartAreas[0].AxisX.Interval = x_axis_num;
chart1.ChartAreas[0].AxisY.Interval = y_axis_num;
In the line x_axis_num = Convert.ToInt32(xAxisBox.Text, usC);, you are taking whatever is in the text box and try to convert it to an integer value.
What do you think the conversion of "Hey, I'm not a number!" will do? It will crash horribly, basically because that text is not, and never will be, a number.
Instead, you can use the Int.TryParse method which will take any text and TRY to convert it to a number.
If the conversion is successful, then no problem. If it was not successful, then you get a false value on a flag indicating the text could not be converted.
Example:
int number;
bool result = Int32.TryParse(YourTextBox.Text, out number);
If the conversion is successful, then number has the value, otherwise, result is false so do something like this then:
if(result)
{
xAxisBox.Text = number.ToString();
x_axis_num = number;
}
else
{
xAxisBox.Text = string.Empty;
// Be careful here with what you set.
// This is the value you will set when the Text box has a non numeric value!
x_axis_num = 0;
}

textbox to accept integers

I've found different help through this website but still can't seem to convert a string to int. I've tried many different ways. Here are two of them. On button_click I need to read the textboxes and convert them to int so I can perform standard logic on them. (a > b functions). Below the first section is what I'm using to force the use of numbers during entry into the text boxes.
private void write_button_Click(object sender, EventArgs e)
{
int mat_od1 = int.Parse(matod_box.Text); //Input string in wrong format.
int mat_id1 = int.Parse(matid_box.Text);
int fod1 = int.Parse(fod_box.Text);
int fid1 = int.Parse(fid_box.Text);
int hp1 = int.Parse(hp_box.Text);
//This next section is just to show something else I've tried.
decimal mat_od = Convert.ToDecimal(matod_box.Text); //Same error.
decimal mat_id = Convert.ToDecimal(matid_box.Text);
decimal fod = Convert.ToDecimal(fod_box.Text);
decimal fid = Convert.ToDecimal(fid_box.Text);
decimal hp = Convert.ToDecimal(hp_box.Text);
decimal pass_od = mat_od;
}
private void fod_box_TextChanged(object sender, EventArgs e)
{
try
{
int numinput = int.Parse(fod_box.Text);
if (numinput < 1 || numinput > 500)
{
MessageBox.Show("You must enter a number between 0 and 500.");
}
}
catch (FormatException)
{
MessageBox.Show("You need to enter a number.");
fod_box.Clear();
}
Any help would be appreciated.
instead of int.Parse() you should use int.TryParse(string,out int)
this way you would be able to chek the output and decide wether the string was correctly parsed or not
int i;string s="";
if(int.TryParse(s,out i))
{
//use i
}
else
{
//show error
}
The int.parse conversion should work, as in this sample:
string s = "111";
int i;
if (int.TryParse(s, out i))
{
Console.Write(i);
}
else
{
Console.Write("conversion failed");
}
Are you sure you actually provide legal input for your ints? In any case, you should use TryParse like I did in my sample. Theres no need to use try..catch where you can use boolean methods provided by the framework, which will get you the same result..
All depends on what you are allowing to be put in the text box.
If it might not be a string that can be converted to an integer, including blank, then something like
int value;
if (int.TryParse(SomeString, out value)
{
// it is an int
}
else
{
// it's not an int, so do nothing raise a message or some such.
}
In addition to using Int32.TryParse in the button Click event handler as others have pointed out, you need to be careful what you're doing in the TextBox Changed event handler. You're code here is flawed:
private void fod_box_TextChanged(object sender, EventArgs e)
{
try
{
int numinput = int.Parse(fod_box.Text);
...
}
catch (FormatException)
{
MessageBox.Show("You need to enter a number.");
fod_box.Clear();
}
Calling foo_box.Clear() will clear any text from the textbox, calling the TextChanged handler to be executed again (unless the TextBox was already empty). So if you enter a non-numeric value, your message box will be displayed twice - the first time when it attempts to parse your non-numeric value, the second time when it attempts to parse an empty string as a result of the call to Clear().
In general, I'd avoid doing validation in the Changed event handler.

Categories