[英]How to multiply the number of two labels in C#
so i have 2 labels.所以我有 2 个标签。 one of them is a fixed number and doesn't change but the other one changes every 5 seconds.
其中一个是固定数字,不会改变,但另一个每 5 秒改变一次。 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.您有带有
Text
属性的标签。 That property is of type string
.该属性的类型为
string
。 C# is a strongly typed language: strings can not be multiplied like that. C# 是一种强类型语言:字符串不能像那样相乘。 In the end, a label can be empty, or the user could input any random string.
最后,标签可以为空,或者用户可以输入任何随机字符串。 What would be the result of
"foo" * "bar"
? "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
.此外,当您由于某种乘法而得到一个
double
,您希望在另一个label.Text
向用户显示它。 Here you have the inverse issue: C#/.Net does not convert the variable of type double
implicitly to a string.这里有一个相反的问题:C#/.Net 不会将
double
类型的变量隐式转换为字符串。
So you will have to所以你将不得不
double
and multiply themdouble
并相乘Text
propertyText
属性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 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.