I recently got stuck in my project as I have requirements that I need to fulfil, the need to perform addition in a single textbox.
I've view the most similar posts and it gave a good idea of it, Addition using a single TextBox.
Instead of int, I am required to use double like how it was done with int.
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);
}
}
Instead, what code should I use to create a similar things for double?
If you want to keep your code, just do this :
private int i = 0;
private double[] a = new double[2];
private void button1_Click(object sender, EventArgs e)
{
double b;
if (Double.TryParse(textBox1.Text, out b))
{
a[i] = b;
i++;
textBox1.Text = "";
}
else
{
MessageBox.Show(#"Incorrect number");
}
}
private void resultbutton2_Click(object sender, EventArgs e)
{
double sum = a[0] + a[1];
MessageBox.Show("Sum: " + sum);
}
But you can try this for adding more than 2 doubles :
private double result = 0.0;
private void button1_Click(object sender, EventArgs e)
{
double b;
if (Double.TryParse(textBox1.Text, out b))
{
result += b,
textBox1.Text = "";
}
else
{
MessageBox.Show(#"Incorrect number");
}
}
private void resultbutton2_Click(object sender, EventArgs e)
{
MessageBox.Show("Sum: " + result);
}
double b = 0;
try{
b = Convert.ToDouble(textBox1.Text);
}
catch(e){
// Error Handling
}
Docs: https://learn.microsoft.com/en-us/previous-versions/windows/apps/zh1hkw6k(v=vs.105)
you can try use something like:
Double.Parse("1.2");
some examples here:
https://msdn.microsoft.com/en-us/library/fd84bdyt(v=vs.110).aspx
Related
I have i wpf form with 3 textboxes there i should write how many tickets, then i want to multiply that number with a value
At the end i have another textbox there i want the sum from the 3 textboxes even if only 1 has value
i have tried this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
}
Cant get it to work
Please help
To convert a string value to an integer value you may use int.Parse method. On the other hand this method (also Convert.ToInt32) requires you making sure that string is always in a good format to get converted. If you are not sure and/or you know that the string may be not in correct format, you may use int.TryParse method, which returns true/false value, stating whether the convert was succesful also giving out required value if it was successful. If it fails you get default value - 0.
If all textboxes follow same procedure you may create only one TextChanged event and bind it to all of them.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int sum = 0;
if (!string.IsNullOrEmpty(textBox1.Text) && int.TryParse(textBox1.Text, out int gold_ticket_count))
{
sum += 120 * gold_ticket_count;
}
if (!string.IsNullOrEmpty(textBox2.Text) && int.TryParse(textBox2.Text, out int silver_ticket_count))
{
sum += 60 * silver_ticket_count;
}
if (!string.IsNullOrEmpty(textBox3.Text) && int.TryParse(textBox3.Text, out int big_show_ticket_count))
{
sum += 500 * big_show_ticket_count;
}
// do smth with the sum...
}
Check if I named textBoxes correctly. It is a good practise to give your controls a meaningful name.
int.Parse doc: https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse?view=net-6.0
int.TryParse doc: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-6.0
an ugly, quick and dirty but working solution:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private int sum1;
private int sum2;
private int sum3;
private int overallSum;
private void tb1_TextChanged(object sender, TextChangedEventArgs e)
{
if (int.TryParse(tb1.Text, out int tb1Value))
sum1 = tb1Value * 120;
else
sum1 = 0;
sum_1.Text = sum1.ToString();
RecalcOverallSum();
}
private void tb2_TextChanged(object sender, TextChangedEventArgs e)
{
if (int.TryParse(tb2.Text, out int tb1Value))
sum2 = tb1Value * 120;
else
sum2 = 0;
sum_2.Text = sum2.ToString();
RecalcOverallSum();
}
private void tb3_TextChanged(object sender, TextChangedEventArgs e)
{
if (int.TryParse(tb3.Text, out int tb1Value))
sum3 = tb1Value * 120;
else
sum3 = 0;
sum_3.Text = sum3.ToString();
RecalcOverallSum();
}
private void RecalcOverallSum()
{
overallSum = sum1 + sum2 + sum3;
overall_sum.Text = overallSum.ToString();
}
}
BTW: I would recommend using MVVM instead of code behind, but I know it wasn't the question
I created a basic calculator, but each time I enter the second value and press the equal button, I get no result back. Only the value I entered 2nd.
My methods for +-*/ are in a separate class. What will the best way be to resolve this problem? It is probably a simple error, but I can't find it. Can you also please give me an explanation on what I did wrong. Thanks in Advance.
public sealed partial class Calculator : Page
{
public double num01, num02;
int operater;
public Calculator()
{
this.InitializeComponent();
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text =txtcalcdisplay.Text+ "1";
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "2";
}
private void btn3_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "3";
}
private void btn4_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "4";
}
private void btn5_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "5";
}
private void btn6_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "6";
}
private void btn7_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "7";
}
private void btn8_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "8";
}
private void btn9_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "9";
}
private void Clear_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = string.Empty;
}
private void btnsubtract_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = '1';
}
private void btnadd_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = '2';
}
private void btnmultiply_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = '3';
}
private void btndivide_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = '4';
}
private void btnequals_Click(object sender, RoutedEventArgs e)
{
switch (operater)
{
case 1:
num02 = Convert.ToDouble(txtcalcdisplay.Text);
CalculationClass sub = new CalculationClass();
double answer= sub.Subtract(num01, num02);
txtcalcdisplay.Text = answer.ToString();
break;
case 2:
num02 = Convert.ToDouble(txtcalcdisplay.Text);
CalculationClass add = new CalculationClass();
answer= add.Addition(num01, num02);
txtcalcdisplay.Text = answer.ToString();
break;
case 3:
num02 = Convert.ToDouble(txtcalcdisplay.Text);
CalculationClass mult = new CalculationClass();
answer = mult.Multiply(num01, num02);
txtcalcdisplay.Text = answer.ToString();
break;
case 4:
num02 = Convert.ToDouble(txtcalcdisplay.Text);
CalculationClass div = new CalculationClass();
answer = div.Div(num01, num02);
txtcalcdisplay.Text = Convert.ToString(answer);
break;
}
}
private void btnback_Click(object sender, RoutedEventArgs e)
{
}
private void btnplusdivideminus_Click(object sender, RoutedEventArgs e)
{
}
private void btncomma_Click(object sender, RoutedEventArgs e)
{
}
private void btngallery_Click(object sender, RoutedEventArgs e)
{
}
private void btncontact_Click(object sender, RoutedEventArgs e)
{
}
private void num0_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text += "0";
num01 = Convert.ToDouble(txtcalcdisplay.Text);
}
}
class CalculationClass
{
double answer;
public double Addition(double x, double y)
{
answer = x + y;
return answer;
}
public double Subtract(double x, double y)
{
answer = x - y;
return answer;
}
public double Multiply(double x, double y)
{
answer = x * y;
return answer;
}
public double Div(double x, double y)
{
answer = x / y;
return answer;
}
}
I'm not 100% certain, but I'm fairly sure this has to do with the fact that your variable operater is an int but you're assigning a character to it (this works - characters can be assigned to ints) and then comparing it back to the integer (eg doing 1 == '1')
int x = '1';
Console.WriteLine(x); // outputs 49
Console.WriteLine(x == 1); // outputs false
So to fix it either use the characters in your switch:
switch(operater){
case '1': ...
}
Or assign the integer 1,2,3,4 rather than the character '1','2,'3','4'
private void btnadd_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = 2; // here
}
So in your operator click handlers (the ones for +,-,*,/ etc.) you are setting your operater variable to a character '1','2', etc. Well, your operater variable is an int. But wait, you shouldn't be able to assign a char to an int?! Well, the compiler does an implicit conversion here (language spec says it should).
So what ends up happening when you do operater = '1' is that operater gets assigned 49 ('1''s ASCII value). Then when you get to your equals button click handler it hits that switch statement. And guess what? You don't have a case for 49. So nothing happens and you keep seeing your second number as the text on screen.
So to fix it, remove the single quotes around your numbers you assign to operater in your operator handlers. IE:
private void btnsubtract_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = 1; // <-- change this line to be like this, removed the single quotes
}
I want to increase an int variable i whenever I click on a button. But what I get is only int value of 1 and it doesn't increase anymore.
Here is my code:
private int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i++;
lblStart.Text = i.ToString();
}
By each request (Clicking on the button), a new instance will be created.
So your non-static variable will be reset to 0.
You can define i as static:
private static int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i++;
lblStart.Text = i.ToString();
}
But please note that the i variable is shared between all the users.
To improve this issue, you can use Session.
Session is an ability to store data of each user in a session.
So you can use following property to change the i variable in each session:
private int i
{
get
{
if (Session["i"] == null)
return 0;
return (int)Session["i"];
// Instead of 3 lines in the above, you can use this one too as a short form.
// return (int?) Session["i"] ?? 0;
}
set
{
Session["i"] = value;
}
}
protected void btnStart_Click(object sender, EventArgs e)
{
i++;
lblStart.Text = i.ToString();
}
As you know other answer is correct i want add another answer
You must in webform save your variables in ViewState
Just define your variables like this
public int i
{
get { Convert.ToInt32( ViewState["i"] ); }
set { ViewState["i"] = value ; }
}
Convert lblStart.Text value to int every time and assign it to i. Then increase i.
private int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i = Int32.Parse(lblStart.Text);
i++;
lblStart.Text = i.ToString();
}
I have similar questions as yours and I believe the issue is because the event click did not store the value that has been increased before, therefore it could not be incremented the next time you clicked, so here's my code:
protected void btn_add_Click(object sender, EventArgs e)
{
string initial;
int increment;
int quantity;
initial = TextBoxQty.Text;
increment = Convert.ToInt16(initial);
increment++;
TextBoxQty.Text = increment.ToString();
quantity = increment;
}
You can use a hidden field, initialize them to 0.
private int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i = int.Parse(myHiddenField.Value);
i++;
myHiddenField.Value = i;
lblStart.Text = i.ToString();
}
protected static int a = 0;
protected void btnStart_Click(object sender, EventArgs e)
{
a = a+1;
lblStart.Text = i.ToString();
}
It Works for me but on page_load() it initiates the value from 1 again !
this is actually my first time doing this
int i = 0;
while (i>=0)
{
Console.WriteLine(i);
Console.ReadLine();
i++;
}
I'm having a problem printing out an array that I have created through a function.
All it says in the MessageBox is System.int32[], what have I done wrong?
private int[] sekunder(int tid)
{
int sekunder, minuter, timmar;
sekunder = tid;
minuter = sekunder / 60;
timmar = minuter / 60;
int[] beräknaTid = { sekunder, minuter, timmar };
return beräknaTid;
}
private void button1_Click(object sender, EventArgs e)
{
int tid;
tid = Convert.ToInt32(textBox1.Text);
MessageBox.Show(Convert.ToString(sekunder(tid)));
}
try this:
Array Contains Multiple Elements You Need to Iterate through them
private void button1_Click(object sender, EventArgs e)
{
int tid;
tid = Convert.ToInt32(textBox1.Text);
foreach (var item in sekunder(tid))
{
MessageBox.Show(Convert.ToString(item));
}
// for comma separated
//use this : MessageBox.Show(string.Join(",",sekunder(tid)))
}
you can also join all values in your array and show them
private void button1_Click(object sender, EventArgs e)
{
int tid;
tid = Convert.ToInt32(textBox1.Text);
MessageBox.Show(string.Join(", ",sekunder(tid)));
}
I cannot for the life of me figure out how to continuously show the input and then output of the numbers for this.
What do you do to store the numbers somewhere and then show them? I've gone in so many circles that I have confused myself to oblivion.
I know what needs to be done but not how or exactly where to do it?
public partial class Form1 : Form
{
char c;
double num1;
double num2;
public Form1()
{
InitializeComponent();
}
private void btn0_Click(object sender, EventArgs e)
{
txtBox.Text += 0;
}
private void btn1_Click(object sender, EventArgs e)
{
txtBox.Text += 1;
}
private void btn2_Click(object sender, EventArgs e)
{
txtBox.Text += 2;
}
private void btn3_Click(object sender, EventArgs e)
{
txtBox.Text += 3;
}
private void btn4_Click(object sender, EventArgs e)
{
txtBox.Text += 4;
}
private void btn5_Click(object sender, EventArgs e)
{
txtBox.Text += 5;
}
private void btn6_Click(object sender, EventArgs e)
{
txtBox.Text += 6;
}
private void btn7_Click(object sender, EventArgs e)
{
txtBox.Text += 7;
}
private void btn8_Click(object sender, EventArgs e)
{
txtBox.Text += 8;
}
private void btn9_Click(object sender, EventArgs e)
{
txtBox.Text += 9;
}
private void btnDecimal_Click(object sender, EventArgs e)
{
if (!txtBox.Text.Contains('.'))
txtBox.Text += '.';
}
private void btnAddition_Click(object sender, EventArgs e)
{
c = '+';
num1 = double.Parse(txtBox.Text);
txtBox.Text = string.Empty;
}
private void btnSubtraction_Click(object sender, EventArgs e)
{
c = '-';
num1 = double.Parse(txtBox.Text);
txtBox.Text = string.Empty;
}
private void btnMultiplication_Click(object sender, EventArgs e)
{
c = '*';
num1 = double.Parse(txtBox.Text);
txtBox.Text = string.Empty;
}
private void btnDivision_Click(object sender, EventArgs e)
{
c = '/';
num1 = double.Parse(txtBox.Text);
txtBox.Text = string.Empty;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtBox.Clear();
}
private void btnEqual_Click(object sender, EventArgs e)
{
num2 = double.Parse(txtBox.Text);
double result;
switch (c)
{
case '+':
result = num1 + num2;
txtBox.Text = result.ToString();
break;
case '-':
result = num1 - num2;
txtBox.Text = result.ToString();
break;
case '/':
if (num2 != 0)
{
result = num1 / num2;
txtBox.Text = result.ToString();
}
else
{
txtBox.Text = "You can't divide by zero... sign up for Math 100 please =)";
}
break;
case '*':
result = num1 * num2;
txtBox.Text = result.ToString();
break;
}
}
}
}
I'll let you wire this up, but here is what I threw together.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private string op;
private string num1;
private string num2;
private void handleNumberButtonClick(object sender, System.EventArgs e)
{
var num = Convert.ToInt16(((Button)sender).Tag);
if (op == null)
num1 += num;
else
num2 += num;
PrintEquation(num1, op, num2);
}
private void PrintEquation(string first, string oper = null, string second = null, string equals = null, string result = null)
{
txtBox.Text = first + oper + second + equals + result;
}
private void handleOperatorButtonClick(object sender, System.EventArgs e)
{
op = ((Button)sender).Tag.ToString();
PrintEquation(num1, op);
}
private void btnDecimal_Click(object sender, EventArgs e)
{
if (op == null && !num1.Contains(".")) num1 += ".";
if (op != null && !num2.Contains(".")) num2 += ".";
this.PrintEquation(num1, op, num2);
}
private void btnClear_Click(object sender, EventArgs e)
{
txtBox.Clear();
op = null;
num1 = null;
num2 = null;
}
private void btnEqual_Click(object sender, EventArgs e)
{
double result = 0;
var first = Convert.ToDouble(num1);
var second = Convert.ToDouble(num2);
switch (op)
{
case "+":
result = first + second;
break;
case "-":
result = first - second;
break;
case "/":
if (second != 0)
{
result = first / second;
}
else
{
errorLbl.Text = "You can't divide by zero... sign up for Math 100 please =)";
}
break;
case "*":
result = first * second;
break;
}
this.PrintEquation(num1, op, num2, "=", result.ToString());
}
}
To give you a clue on how things go together, this is what the button should look like in the .designer.cs file:
this.btn0.Location = new System.Drawing.Point(12, 60);
this.btn0.Name = "btn0";
this.btn0.Size = new System.Drawing.Size(75, 23);
this.btn0.TabIndex = 1;
this.btn0.Tag = "0";
this.btn0.Text = "btn0";
this.btn0.UseVisualStyleBackColor = true;
this.btn0.Click += new System.EventHandler(this.handleNumberButtonClick);
Notice the .Tag value and the eventhandler.
The Operators should look like this(this is add, notice the tag and the Click Event handler):
this.addButton.Location = new System.Drawing.Point(178, 60);
this.addButton.Name = "addButton";
this.addButton.Size = new System.Drawing.Size(75, 23);
this.addButton.TabIndex = 11;
this.addButton.Tag = "+";
this.addButton.Text = "add";
this.addButton.UseVisualStyleBackColor = true;
this.addButton.Click += new System.EventHandler(this.handleOperatorButtonClick);
And the decimal, like this:
this.button4.Location = new System.Drawing.Point(178, 176);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(75, 23);
this.button4.TabIndex = 15;
this.button4.Tag = ".";
this.button4.Text = "decimal";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.btnDecimal_Click);
Oh, and throw this in your clear button definition
this.button5.Click += new System.EventHandler(this.btnClear_Click);
Special thanks to #Mark Hall and #Martin James for their insights