2016-12-24 205 views
-1

我想用「Random rnd = new Random();」C#無法從'int'轉換爲'string'

public int dzien; 

private void generator_Tick(object sender, EventArgs e) 
{ 
Random rnd = new Random(); 

dzien = rnd.Next(1, 11);  
webBrowser1.Document.GetElementById("birthDateDay").SetAttribute("value", dzien); 
} 

當我想要運行的程序,我得到錯誤:

不能從「詮釋」到「字符串」

這符合「webBrowser1 ......」轉化的「dzien」 。

+2

你幾乎肯定不希望創建一個新的隨機每個刻度 – Plutonix

+0

請務必詢問未來的問題之前閱讀[MCVE]指導 - iesample代碼,這個問題應該是單行:'字符串valueForSetAttribute = 42 ;'(這樣做不會引起SO上的主題問題,因爲搜索帖子的確切標題或錯誤消息會給你一個答案 - https://www.bing.com/search?q=C%23+cannot + convert + from +%27int%27 + to +%27string%27) –

回答

3

變化dzien變爲dzien.ToString()SetAttribute方法接受一個字符串,並且您正試圖向其傳遞一個整數。

0

dzien.ToString()代替dziensetAttribute函數需要兩個字符串作爲參數,但是您已經給它一個字符串和一個整數。

+0

這就是'.ToString()'。 :) – negacao

+0

哎呀!謝謝 :) – twrightsman

0

發生這種情況是因爲setAttribute()方法需要字符串作爲參數,並且它不能將int隱式轉換爲字符串。簡單地用下面的代碼行代替你的代碼。

webBrowser1.Document.GetElementById("birthDateDay").SetAttribute("value", ""+dzien); 
相關問題