Basically my question is how i add to a number like a calculator does for example? My code currently looks like this but it does a add operation instead of adding the number behind the existing number.
private void button1_Click(object sender, RoutedEventArgs e)
{
value1 = value1 + 1;
output = value1;
textresult.Text = output.ToString();
if the user presses the button twice it would be 2. I want it to be 11. How do i do this?
You should use string variable instead int variable
int a = 1;
int b = 1;
int c = a+b;
The result of c is 2
string a = "1";
string b = "1";
string c = a+b;
If you use string it will be "11"
Related
I have 4 text boxes and i would like to find the largest number of the 4, what methods are there that isnt a loop, these text boxes are total scores from 4 teams, the last button is the box that will show the largest number
i have to enter each value (value 1 to 5) in each button, and the result is the largest number of the four, i will be making these values up
private void button1_Click(object sender, EventArgs e)
{
int value1 = 0;
int value2 = 0;
int value3 = 0;
int value4 = 0;
int value5 = 0;
int result = 0;
if (Int32.TryParse(textBox4.Text, out value1) && Int32.TryParse(textBox2.Text, out value2) && Int32.TryParse(textBox6.Text, out value3) && Int32.TryParse(textBox14.Text, out value4) && Int32.TryParse(textBox13.Text, out value5))
{
result = value1 + value2 + value3 + value4 + value5;
textBox21.Text = result.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
int value1 = 0;
int value2 = 0;
int value3 = 0;
int value4 = 0;
int value5 = 0;
int result = 0;
if (Int32.TryParse(textBox11.Text, out value1) && Int32.TryParse(textBox10.Text, out value2) && Int32.TryParse(textBox9.Text, out value3) & Int32.TryParse(textBox8.Text, out value4) && Int32.TryParse(textBox15.Text, out value5))
{
result = value1 + value2 + value3 + value4 + value5;
textBox22.Text = result.ToString();
}
}
private void button3_Click(object sender, EventArgs e)
{
int value1 = 0;
int value2 = 0;
int value3 = 0;
int value4 = 0;
int value5 = 0;
int result = 0;
if (Int32.TryParse(textBox7.Text, out value1) && Int32.TryParse(textBox5.Text, out value2) && Int32.TryParse(textBox1.Text, out value3) & Int32.TryParse(textBox3.Text, out value4) && Int32.TryParse(textBox12.Text, out value5))
{
result = value1 + value2 + value3 + value4 + value5;
textBox23.Text = result.ToString();
}
}
private void button4_Click(object sender, EventArgs e)
{
int value1 = 0;
int value2 = 0;
int value3 = 0;
int value4 = 0;
int value5 = 0;
int result = 0;
if (Int32.TryParse(textBox20.Text, out value1) && Int32.TryParse(textBox19.Text, out value2) && Int32.TryParse(textBox18.Text, out value3) & Int32.TryParse(textBox17.Text, out value4) && Int32.TryParse(textBox16.Text, out value5))
{
result = value1 + value2 + value3 + value4 + value5;
textBox24.Text = result.ToString();
}
}
private void button5_Click(object sender, EventArgs e)
There are many ways to do this, however this might help you out
Make life easier with some short hand extension methods
Extension Methods
public static class TextBoxExtensions
{
public static int GetInt(this TextBox source)
{
// if TextBox null just return 0
if (source == null)
{
return 0;
}
// if it is a valid int, return it, otherwise return 0
// not we use string, in case someone put a space at the start or end
return int.TryParse(source.Text.Trim(), out var value) ? value : 0;
}
public static bool HasValidInt(this TextBox source)
{
// if TextBox null or its not an int return false
// otherwise return true
return source != null && int.TryParse(source.Text.Trim(), out var _);
}
}
Helper function to get Max
// helper function, this does not use a loop
// get the max of all textboxes
private int GetMax(params TextBox[] args)
{
return args.Where(x => x.HasValidInt()) // remove any invalid numbers
.Select(x => x.GetInt()) // project to int
.Max(); //get the max of all
}
Your existing code
using the extension methods
private void button4_Click(object sender, EventArgs e)
{
// this is just a better way to validate your text boxes with the extension method
if (textBox1.HasValidInt() && textBox2.HasValidInt() && textBox3.HasValidInt() && textBox4.HasValidInt())
{
// get the ints from all text boxes using extension method
var result = textBox1.GetInt() + textBox2.GetInt() + textBox3.GetInt() + textBox4.GetInt();
textBox6.Text = result.ToString();
}
}
Get max Version 1
This doesn't use a loop. However, does use Linq
private void button5_Click(object sender, EventArgs e)
{
// get the max of all textboxes using the helper method
textBox6.Text = GetMax(textBox1, textBox2, textBox3, textBox4).ToString();
}
Get max Version 2
This doesn't use a loop. However, does use Math.Max
private void button6_Click(object sender, EventArgs e)
{
// this is just a better way to validate your text boxes with the extension method
if (textBox1.HasValidInt() && textBox2.HasValidInt() && textBox3.HasValidInt() && textBox4.HasValidInt())
{
// use math to get the max
var result = 0;
result = Math.Max(result, textBox1.GetInt());
result = Math.Max(result, textBox2.GetInt());
result = Math.Max(result, textBox3.GetInt());
result = Math.Max(result, textBox4.GetInt());
textBox6.Text = result.ToString();
}
}
Additional Resources
Extension Methods (C# Programming Guide)
Extension methods enable you to "add" methods to existing types
without creating a new derived type, recompiling, or otherwise
modifying the original type. Extension methods are a special kind of
static method, but they are called as if they were instance methods on
the extended type. For client code written in C#, F# and Visual Basic,
there is no apparent difference between calling an extension method
and the methods that are actually defined in a type.
Getting Started with LINQ in C#
This section contains basic background information that will help you
understand the rest of the LINQ documentation and samples.
Int32.TryParse Method
Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the operation
succeeded.
params (C# Reference)
By using the params keyword, you can specify a method parameter that
takes a variable number of arguments.
You can send a comma-separated list of arguments of the type specified
in the parameter declaration or an array of arguments of the specified
type. You also can send no arguments. If you send no arguments, the
length of the params list is zero.
Enumerable.Where Method (IEnumerable, Func)
Filters a sequence of values based on a predicate.
Enumerable.Select Method (IEnumerable, Func)
Projects each element of a sequence into a new form.
Enumerable.Max Method
Returns the maximum value in a sequence of values.
Math.Max Method
Returns the larger of two specified numbers.
Comment from IFebles
It also can be done with this (segmentating the TextBoxs within
panels):
var values = panel1.Controls.Cast<Control>()
.Where(obj => obj is TextBox)
.Select(obj => int.Parse(obj.Text))
.Max();
knowing that it can throw a FormatException if any input can't be parsed. Not as neat as the given answer, but also good to know.
I'm new to programming and I have a problem. I have two buttons and a textbox. When I press the button, a number will show on the textbox, but when I press the second button the number in the textbox overwrites it and replaces it instead of adding to it in the textbox. How do I fix this? I want the values to add instead of replacing it.
public partial class Form1 : Form
{
int value1 = 0;
int value2 = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
value1++;
textBox1.Text = value1.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
value2 += 2;
textBox1.Text = value2.ToString();
}
}
}
If you want to add two integers and assign the result back to textBox1 you have to
Parse textBox1.Text to integer: int.Parse(textBox1.Text)
Sum up values: int.Parse(textBox1.Text) + value2
Convert the outcome back to string: (...).ToString()
Implementation:
private void button2_Click(object sender, EventArgs e) {
value2 += 2;
textBox1.Text = (int.Parse(textBox1.Text) + value2).ToString();
}
Edit: If there's a possibility that textBox1.Text doesn't contain a valid integer value (say, textBox1.Text is empty) you can use int.TryParse:
private void button2_Click(object sender, EventArgs e) {
if (int.TryParse(textBox1.Text, out var v)) {
value2 += 2;
textBox1.Text = (v + value2).ToString();
}
else {
//TODO: textBox1.Text is not a valid integer; put relevant code here
}
}
You're using two separate variables (value1 and value2 above) to store the results of each button click, depending in which button was clicked. Think of it like this:
On program start:
value1 = 0
value2 = 0
User clicks button 1, which executes button1_Click. This increments value1 (via value1++), so the two variables look like this:
value1 = 1
value2 = 0
User then clicks button 2, which executes button2_Click. This sets value2 to whatever was previously in value2 + 2. However, note that the value of value1 is unchanged:
value1 = 1
value2 = 2
By having separate variables, each button click is operating on a different value. I would modify your code so there is only one value variable that both _Click functions modify.
Add this line:
textBox1.Text = (int.parseInt(textBox1.Text) + value2).toString();
after
value2 += 2;
into your button2_click method:
I am beginner , am trying to create a calculator. the way of the code working is there is a method for summing and one for subtraction ETC.
when i call the subtraction method unwanted minus appears before the answer in the textbox ( i know my code could be using harder way to do the same purpose but i am just beginner trying to do some code )
double rat;
byte operations;
public void TheEqualMinus(double earlier) //Substraction Operation Method
{
double _minus;
_minus = Convert.ToDouble(result.Text);
double last = _minus - earlier;
result.Text = last.ToString();
}
private void button15_Click(object sender, EventArgs e)
{
//The Subtract Button
operations = 2;
rat = Convert.ToDouble(result.Text);
label1.Text = rat + " -";
result.Text = "";
}
private void button4_Click(object sender, EventArgs e)
{
// equal button
NewText = true; //boolean to newtext
switch (operations)
{
case (1): //addition
TheEqualSum(rat);
label1.Text = "";
break;
case (2): //substraction
TheEqualMinus(rat);
label1.Text = "";
break;
}
}
and the answer output becomes " - The Correct Answer i want "
ex. 9-6 = -3
so any ideas how to remove this minus ?
As per the comments above, this was fixed by simply changing this:
double last = _minus - earlier;
to this:
double last = earlier - _minus;
I am making a calculator to gain some experience with C#, atm i have one textbox ontop of one another, the lower one is called calculation; i want this one to show the sum being calculated. The text box on top is called result and i obviously want that to display the result; the result box works fine. I want the lower text box ( called calculation ) to display the + symbol which it wont let me do and at the moment i am only able to show the digits. I assume this is a data type problem. Any help/advice? thank you! (I'm sorting this out before moving onto the other symbols and eventually putting it into a switch case :) )
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double num1 = 0;
double num2 = 0;
private void Clearbtn_Click(object sender, EventArgs e)
{
Calculation.Clear();
Result.Clear();
}
private void Numericclick(object sender, EventArgs e)
{
Button button = (Button)sender;
Calculation.Text = Calculation.Text + button.Text;
}
private void Plusbtn_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(Calculation.Text);
Result.Show();
}
private void Equalsbtn_Click(object sender, EventArgs e)
{
num2 = num1 + double.Parse(Calculation.Text);
Result.Text = num2.ToString();
num1 = 0;
}
}
}
If you use the (+) operator with strings it concatenates them together.
This line Calculation.Text = Calculation.Text + button.Text;
In C# 6 will be this:
Calculation.Text = $"{Calculation.Text} + {button.Text}";
Lower than C# 6:
Calculation.Text = string.Format("{0} + {1}", Calculation.Text, button.Text);
String Concatenation Documentation: HERE
Example of difference between the operand + and as a string "+":
//+ operand concats string
var text = "abc";
var text2 = "def";
var result = text + text2;
//result -> "abcdef"
var result2 = text + "+" + text2;
//result -> "abc+def"
I have 4 numeric up down controls on a form. They are set to hexidecimal, maximum 255, so they'll each have values from 0 to FF. I'd like to concatenate these values into a string for a textbox.
You can do something like the following
textBox1.Text = string.Format("{0:X2}{1:X2}{2:X2}{3:X2}",
(int)numericUpDown1.Value,
(int)numericUpDown2.Value,
(int)numericUpDown3.Value,
(int)numericUpDown4.Value);
Assuming you gave the NUDs their default names:
private void button1_Click(object sender, EventArgs e) {
string txt = "";
for (int ix = 1; ix <= 4; ++ix) {
var nud = Controls["numericUpDown" + ix] as NumericUpDown;
int hex = (int)nud.Value;
txt += hex.ToString("X2");
}
textBox1.Text = txt;
}