How to multiply the number of two labels in C# - c#

so i have 2 labels. one of them is a fixed number and doesn't change but the other one changes every 5 seconds. Now i want to multiply them automatically and show them in another label as Results.
what should i do? what am i doing wrong?
i tried this code but it says "operator * cannot be applied to string and string".
label1.Text = BTC_A.Text * BTCPrice_Label.Text;
then i tried
double txt1 = Convert.ToDouble(BTC_A.Text);
double txt2 = Convert.ToDouble(BTCPrice_Label.Text);
double sum = txt1 * txt2;
label1.Text = sum.ToString();
but it says "Input string was not in a correct format"

Think it through step by step.
You have labels with a Text property. That property is of type string. C# is a strongly typed language: strings can not be multiplied like that. In the end, a label can be empty, or the user could input any random string. What would be the result of "foo" * "bar"?
Also, when you do have a double as a result of some multiplication, you want to show it to the user in another label.Text. Here you have the inverse issue: C#/.Net does not convert the variable of type double implicitly to a string.
So you will have to
check if the strings entered by the user is actually a valid double
if they are, convert those strings to double and multiply them
convert the result to a string, and assign it to the labels Text property
if the strings are not valid numbers, leave the label empty, or show some other message
The logic to achieve this would be something like this:
var validPrice = int.TryParse(BTCPrice_Label.Text, out double price);
var validAmount = int.TryParse(BTCA_Label.Text, out double amount);
if (validPrice && validAmount)
{
var result = price * amount;
label1.Text = result.ToString();
}
else
{
label1.Text = "something is wrong";
}

so the problem was a dollar sign ( $ ) that i put before the numbers.
i just deleted the sign and this is what the code looks like now:
double AA;
if (!double.TryParse(BTC_A.Text, out AA))
{
MessageBox.Show($"Unable to convert the BTC_A \"{BTC_A.Text}\" to a floating point number");
return;
}
double btcA;
if (!double.TryParse(BTCPrice_Label.Text, out btcA))
{
MessageBox.Show($"Unable to convert the price \"{BTCPrice_Label.Text}\" to a floating point number");
return;
}
label1.Text = (AA * btcA).ToString();

Related

How to sum only one textbox value and show result in label in c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
The question could be duplicate but my problem is totally different.
I have a one textbox and one label.
Example: label text is already exist with number like 450 Now I want to add number in textbox and the textbox value should be sum in 450 + 30 = 480 where 30 is textbox value.
what I have tried:
lbl_TotalAmount.Text = lbl_TotalAmount.Text + txt_DeliveryCharges.Text;
The above Result is: 45030
Another Code I Have tried:
double total = Convert.ToDouble(lbl_TotalAmount.Text);
double charges = Convert.ToDouble(txt_DeliveryCharges.Text);
double sum = total + charges;
lbl_TotalAmount.Text = String.Format(sum.ToString("0.00"));
The above code is going to sum every value that I put in the textbox and also when I remove one word the number is sum every time.
Please give me best solution I tried many solution to solve this but unable to do this.
Sorry for bad English.
The above code is going to sum every value that I put in the textbox and also when I remove one word the number is sum every time.
That's most likely because you're calling your code inside the TextChanged or the KeyPress events of the textbox; this means that every time you modify anything in your textbox, your code will fire and make the sum.
Instead, add a button and put your code inside its Click event, or if you want the sum to respond to every keypress while respecting your original value, save your value in a variable and use it to calculate the sum.
'Declare a variable at form level
Dim originalValue as Double
'Code where you put your value in a label, put it also in a variable
lbl_TotalAmount.text = 450
originalValue = 450
'Modify your code to use the original value instead of the label
double charges = Convert.ToDouble(txt_DeliveryCharges.Text);
double sum = originalValue + charges;
lbl_TotalAmount.Text = String.Format(sum.ToString("0.00"));
Your strings need to be converted (parsed) to doubles (since they are representing monetary values), but you need to be sure that you're not trying to parse something that can't be converted. TryParse() evaluates to true (or false if the parse fails), so you can avoid a possible exception.
Additionally, you've stated in comments that you want this to update as the text box is updated, so you'll need a variable that is out of scope to keep the total separated from the calculation. I'm going to work from the assumption that this is a shopping cart, or something like that. In that case, a List<> would be an obvious way to store the values of the items in the cart.
Try this:
using System;
using System.Collections.Generic; //required for List<>
namespace WidowsFormsApplication
{
public class ShoppingCart
{
List<double> shoppingCart = new List<double>();
protected void AddItemToCart()
{
shoppingCart.Add(450);
}
protected void UpdateShoppingCart()
{
double total = 0;
foreach (double item in shoppingCart) //calculate total of shoppingCart
{
total += item;
}
if (Double.TryParse(txt_DeliveryCharges.Text, out double charges))
{
total += charges; //add charges without altering shoppingCart
lbl_TotalAmount.Text = String.Format("{0:0.00}", total);
}
}
}
}
lbl_TotalAmount.Text = lbl_TotalAmount.Text + txt_DeliveryCharges.Text;
lbl_TotalAmount.Text and txt_DeliveryCharges.Text are text fields. You cannot do arithmetic on text fields. You have to convert to number, do the arithmetic then convert back
var charge = Int32.Parse(txt_DeliveryCharges.Text);
var total = Int32.Parse(lbl_TotalAmount.Text);
var newTotal = charge + total;
lbl_TotalAmount.Text = newTotal.ToString();
what you are doing is string concatenation
Not a sum of two numbers, You have to convert your strings to int first
here is how you can do that
int x = 0, y = 0;
if (Int32.TryParse(lbl_TotalAmount.Text out x) && Int32.TryParse(txt_DeliveryCharges.Text, out y))
{
// you know that the parsing attempt
// was successful
lbl_TotalAmount.Text = x + y;
}
yourlabel.Text = ""+ (Int32.Parse(yourlabel.Text)+Int.Parse(your textbox.Text));
or
yourlabel.Text = ""+(Double.Parse(yourlabel.Text)+Double.Parse(yourtextbox.Text));
are you using a double? only need that for decimal numbers that are super precise. whole numbers, use int... if you're using it to do money you want to use Decimal, but it depends on the situation.

Comparing a text box's input to a variable

My program requires users to input answers into a text box to randomly generated questions. The questions have calculated answers which are stored in variables. Comparing the text box's input with that variable doesn't work properly, hence why I'm here.
enum elements { lithium, beryllium, sodium, magnesium };
public void Moles()
{
string elementName;
int elementsLength = Enum.GetNames(typeof(elements)).Length;
double moles, mass, roundedMoles, Mr = 0;
Random random = new Random();
elementName = (Enum.GetNames(typeof(elements))[random.Next(0, elementsLength)]);
mass = random.Next(1, 100);
switch (elementName)
{
case "lithium":
Mr = 7;
break;
case "beryllium":
Mr = 9;
break;
case "sodium":
Mr = 23;
break;
case "magnesium":
Mr = 24;
break;
}
moles = mass / Mr;
roundedMoles = Math.Round(moles);
label1.Text = ("How many moles in " + mass + "g" + " of " + elementName + "?");
string input = textBox1.Text.ToString();
if (input == roundedMoles.ToString())
{
MessageBox.Show("Good");
textBox1.Clear();
}
else
{
MessageBox.Show("Bad");
textBox1.Clear();
}
private void button1_Click(object sender, EventArgs e)
{
Moles();
}
As you can see, the program will calculate a number of moles and round it to the nearest whole number. It's then stored in a variable, 'roundedMoles' - this variable is what's compared with the text box's input.
However, the message box will randomly show 'Good' or 'Bad' regardless of whether the input is correct or not. Bear in mind that this code works fine in a console application, so I don't know whether it's something I'm doing wrong or if it just doesn't want to work.
Sorry if this code isn't of a high standard. I'm not that good at programming.
You have two problems.
Don't compare strings as numbers
When comparing numeric values, never compare string to string. Always convert to a numeric variable. Otherwise, "0.00" will not equal "0" and "1234 " (with a space at the end) won't equal "1234" (with no space). Also, you will run into serious trouble if you're working with a culture that uses , as the decimal point.
So, instead of this:
string input = textBox1.Text.ToString();
if (input == roundedMoles.ToString())
{
MessageBox.Show("Good");
textBox1.Clear();
Use something like this:
string input = textBox1.Text;
double inputAsDouble;
bool ok = double.tryParse(out inputAsDouble);
if (!ok)
{
MessageBox.Show("Please enter a numeric value.");
return;
}
if (inputAsDouble == roundedMoles)
{
MessageBox.Show("Good");
textBox1.Clear();
Don't compare floating point values as exact
When comparing floating point values, don't use ==. Instead, compute the difference and make sure it is below a certain tolerance. You have to do this because floating point variables are only approximations.
So instead of
if (inputAsDouble == roundedMoles)
use
const double Tolerance = 0.00001;
if (inputAsDouble - roundedMoles < Tolerance)
Ok so here is the answer...
The reason the console works is that you write to the console to ask the question. You then do console.Readline() this captures the input of the answer after they have seen the question.
On the forms version. You set the label to the question and immediately capture the text box value. The user has not had a chance to enter the answer, or its still the answer from the last time (hence why it randomly goes from "Good" to "Bad" because sometimes the answer is the same).
One simple way is make your variables at the top of the Moles() method, class variables on the form and then have 2 buttons with 2 methods one that gets the questions and sets your answer variables and then a second button then the user can press when they've entered their answer.
Check out this code paste https://www.pastebucket.com/564406
(You'll need button2 added to your form for this to work obviously)
edit: I've done a quick cut and paste of code there. You shouldn't just copy this and use it. Look what I've done and apply it properly and try and understand why it works
It seems that you might have a culture related problem down there. Always be careful when comparing Double values converted to String. The framework might be converting '1,5' to '1.5' depending on your regional settings.
The first thing I would recomend you is not to compare as String but do it as Double. And if you do that, ensure that you will replace dots with comma or other way.
if (Convert.ToDouble(input) == roundedMoles)
{
MessageBox.Show("Good");
textBox1.Clear();
}
else
{
MessageBox.Show("Bad");
textBox1.Clear();
}

Unable to cast object of type 'system.windows.forms.textbox' to type 'System.IConvertible' error for c# form

I have this code here but I keep getting the same error. Can someone tell me what I did wrong?
private void button1_Click(object sender, EventArgs e)
{
double gallonsToBuy;//for equation
double WALL_LENGTH; //holds wall length
double WALL_HEIGHT; //holds wall height
int NUM_DOORS; //holds number of doors
int NUM_WINDOWS; //holds number of windows
int NUM_COATS; //holds number of coats of paint
const double GALLON_SF = 350; //one gallon covers 350 square feet
//allows user to input their numbers
WALL_LENGTH = Convert.ToDouble(textBox1);
WALL_HEIGHT = Convert.ToDouble(textBox2);
NUM_DOORS = Convert.ToInt32(textBox3);
NUM_WINDOWS = Convert.ToInt32(textBox4);
NUM_COATS = Convert.ToInt32(textBox5);
//Equation
gallonsToBuy = ((((WALL_LENGTH * WALL_HEIGHT) - (20 * NUM_DOORS) - (15 * NUM_WINDOWS)) * NUM_COATS) /350);
label7.Text = "Gallons to buy =" +gallonsToBuy;
}
Your error comes from trying to convert a TextBox to a double.
WALL_LENGTH = Convert.ToDouble(textBox1);
TextBox is a .NET object type, and you cannot do a meaningful conversion to a double. What you must do is convert the value of TextBox.Text property to a double.
WALL_LENGTH = Convert.ToDouble(textBox1.Text);
But this alone would still be problematic and error prone, if the user enters text that cannot be converted to a double.
So you should, in addition, use proper methods for conversion such as int.TryParse() and double.TryParse().
For instance,
double WALL_LENGTH;
double.TryParse(textBox1.Text, out WALL_LENGTH);
If all such conversions succeed, then proceed with the calculation.
Looking at your code I believe textBox1,textBox1 etc. are TextBox control. You cannot covert control type to data type. you need to use the property .text to access the value within the control.
WALL_LENGTH = Convert.ToDouble(textBox1.Text);
WALL_HEIGHT = Convert.ToDouble(textBox2.Text);
NUM_DOORS = Convert.ToInt32(textBox3.Text);
NUM_WINDOWS = Convert.ToInt32(textBox4.Text);
NUM_COATS = Convert.ToInt32(textBox5.Text);
Make sure you have a value to the input fields otherwise it will through cast error trying to convert it from string.empty.

Show result of an operation (multiplication) in textblock

I have a textblock, a button and a textbox.
What I want is the user enter data in a textbox (only numbers - whole numbers or decimals) and press the button appears on the textblock the result of an operation (multiplication) based on the value that the user entered.
For exemple (Button Click Event)
int num = TextBox.Text;
TextBlock.Text = num * 0.02;
What I want is: the user enters in the TextBox a decimal or integer (eg 50), when you press the button want to appear in the TextBlock the value that the user entered * 0.02. The result to appear is 1
First, you will need to parse the string
you can use the int num = Int.Parse(TextBox.Text) method
Just don't forget to validate the TextBox so it contains only numbers
C# is a type safe language, so you can't calculate "hello" (string) * 1 (int).
So you have to parse the string into the correct type. Because you not only need whole numbers, you have to choose between decimal and double.
Also the user can enter an invalid number, so better to check the Input.
This will look like:
const decimal multiplicator = 0.02;
double number;
if (Double.TryParse(TextBox.Text, out number))
{
var result = number * multiplicator;
//do what you want with the result ;)
}else
{
//TextBox.Text is not a valid number!
}

Why do I get an error if I didn't enter value? [duplicate]

This question already has answers here:
Empty String to Double C#
(5 answers)
Closed 6 years ago.
My program lets you choose the product, number of items from a combobox and lets you write the price in a textbox and it will calculate the amount (number of items * price), the 30% discount and the price after discount.
If every box is filled it won't show error, but if I leave the number of items combobox and/or price empty I get this error:
Exception thrown: 'System.FormatException' in mscorlib.dll
Additional information: Input string was not in a correct format.
And it will highlight this line: price = double.Parse(textBox1.Text);
private void button1_Click(object sender, EventArgs e)
{
double amount, price, dis,
itemnum = double.Parse(comboBox2.Text),
disrate = 30.0, totalafterdis;
price = double.Parse(textBox1.Text);
amount = price * itemnum;
dis = amount * (disrate / 100);
totalafterdis = amount - dis;
textBox2.Text = amount.ToString();
textBox3.Text = dis.ToString();
textBox4.Text = totalafterdis.ToString();
}
I am not really familiar with C#, so I'm not sure if it's a rookie mistake or not.
If you left the textBox1 empty, you would get this error. This exception is basically telling you that, the value you have entered, is not in a suitable format for parsing to type double.
Here is an example. You will not/can not be able to parse, for instance, the value "hello", to a type double. Your program at the moment is trying to parse an empty/null value to a double, which is not valid.
You should make use of the TryParse function, as below:
double result = 0;
bool isValidDouble = double.TryParse(textBox1.Text, out result);
//logical code here to check value of result
This will not throw an exception if your value of your textBox1 is invalid for parsing.
If you don't insert anything then it presents an empty string, which cannot be converted to an integer so try this:
double temp;
if(double.TryParse(textBox1.Text, out temp)){
price = double.Parse(textBox1.Text);
}

Categories

Resources