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
double
and multiply themText
propertyThe 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 it 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.