2017-06-06 81 views
0

我是C#的新手,剛開始學習如何編寫代碼。我試圖轉換和總結一個標籤中顯示的幾個項目的金額,然後顯示在另一個標籤中的總和。我使用parse將值轉換爲double,但我經常收到一條錯誤消息,說「不能隱式轉換int類型到string.Here是我的代碼示例。如何將文本從標籤轉換爲雙重文件

int Cost; 

double total = 0; 
costLabel.Text = Convert.ToInt32(priceLabel2.Text); 
Cost = int.Parse(priceLabel2.Text); 
total += double.Parse(priceLabel2.Text); 
costLabel.Text = total.ToString("c"); 

任何一個可以幫我解決這個問題呢?

+6

刪除此行'costLabel.Text = Convert.ToInt32( priceLabel2.Text);'除了創建這個錯誤之外別無其他 - –

+0

[Convert int to string?]的可能重複(https://stackoverflow.com/questions/3081916/convert-int-to-string) – DomeTune

+0

如上所述:[string myString = myInt.ToString();](https://stackoverflow.com/a/3081919/7137009) – DomeTune

回答

0

的問題是在該行costLabel.Text = Convert.ToInt32(priceLabel2.Text);。你有很多不必要的代碼,所以它可以全部簡化爲以下內容:

double total = double.Parse(priceLabel2.Text); 
costLabel.Text = total.ToString("c"); 
0

您正在將整數分配給字符串,這是行不通的。您也在同一輸入上執行多個操作。對於貨幣,您必須使用decimal,因爲這是更安全(更精確)的數據類型。

decimal total = 0; 
... 

decimal price = Convert.ToDecimal(priceLabel2.Text); 
total += price; 

costLabel.Text = total.ToString("c"); 

如果你想先驗證輸入,你應該使用decimal.TryParse

if (decimal.TryParse(priceLabel2.Text, out decimal price)) 
{ 
    total += price; 
} 
else 
{ 
    MessageBox.Show("Input is not a valid decimal."); 
} 
+0

我嘗試了上面提到的代碼,但我仍然收到錯誤消息:decimal price = Convert.ToDecimal(priceLabel2.Text);錯誤消息說:將字符串轉換爲日期/時間時,在將每個變量放入日期時間對象之前解析字符串以獲取日期 –

+0

現在可以嘗試我了,但我認爲德米特里非常清楚。您的示例代碼中沒有日期/時間。我敢肯定,我們的代碼不會出現這種錯誤。 –

1

請記類型;你的代碼修改爲:

// Are you sure that price is integer? What about 4.95$? 
// More natural choice is double (decimal is the best for the currency) 
double Cost; 

// Let's preserve double (but decimal is a better choice) 
double total = 0; 

// string assigned to string; no Convert.ToInt32 
// It's useless line, however, since costLabel.Text = total.ToString("c"); 
// will rewrite the label 
costLabel.Text = priceLabel2.Text; 

// Since cost is not an integer value 
Cost = double.Parse(priceLabel2.Text); 

// You don't want to parse twice 
total += Cost; 
costLabel.Text = total.ToString("c"); 

一個更好的選擇是使用decimal貨幣:

decimal total = 0m; 

//TODO: it seem's that you want to add some logic here; otherwise total == cost 

decimal cost = decimal.Parse(priceLabel2.Text); 
total += cost; 

costLabel.Text = total.ToString("c"); 
+1

更好的選擇是'decimal'。 –

+0

我編輯了我的代碼,但是我仍然收到錯誤消息:Cost = double.parse(priceLabel2.Text);該錯誤消息表示:將字符串轉換爲日期/時間時,請在將每個變量放入Date Time對象之前解析字符串以獲取日期。 –

+0

@S。R:代碼中有其他地方存在錯誤:「將字符串轉換爲**日期/時間**時,在將每個變量放入**日期時間**對象之前解析字符串以獲取日期」 - 我們在片段 –

0

costLabel.Text屬性類型爲字符串。

costLabel.Text = priceLabel2.Text; 
+1

中沒有任何'DateTime'爲什麼不是'costLabel.Text = priceLabel2.Text'而不是您的建議? –

+0

這看起來不太有用。爲什麼不立即分配字符串值? –

+0

轉換爲int並且回到字符串:P – EpicKip

0

costlLabel.Text是一個字符串,並嘗試給它一個整數值:

costLabel.Text = Convert.ToInt32(priceLabel2.Text); 

用這個代替:

costLabel.Text = priceLabel2.Text;