2009-05-20 186 views
3

我需要我的代碼幫助。我想在我的文本框中只寫數字/整數,並希望在我的列表框中顯示。將字符串轉換爲整數

下面是我的代碼的順序嗎?這似乎給出了一個錯誤。

int yourInteger; 
    string newItem; 

    newItem = textBox1.Text.Trim(); 

    if (newItem == Convert.ToInt32(textBox1.Text)) 
    { 
     listBox1.Items.Add(newItem); 
    } 

==== 更新:

這是我的代碼看起來像現在。我的問題是,listBox可以處理數據類型「long」嗎?因爲當我輸入20,000,000的數字時,我只用了20分鐘的一小時玻璃杯。但是當我用控制檯嘗試這個時,我得到了答案。所以我不確定哪種元素可以處理數據類型「long」。

string newItem; 
    newItem = textBox1.Text.Trim(); 

    Int64 num = 0; 
    if(Int64.TryParse(textBox1.Text, out num)) 
    { 
     for (long i = 2; i <= num; i++) 
     { 
      //Controls if i is prime or not 
      if ((i % 2 != 0) || (i == 2)) 
      { 
       listBox1.Items.Add(i.ToString()); 
      } 

     } 
    } 


    private void btnClear_Click(object sender, EventArgs e) 
    { 
     listBox1.Items.Clear(); 
    } 

回答

3

使用此:

int yourInteger; 
    string newItem; 

    newItem = textBox1.Text.Trim(); 
    Int32 num = 0; 
    if (Int32.TryParse(textBox1.Text, out num)) 
    { 
     listBox1.Items.Add(newItem); 
    } 
    else 
    { 
     customValidator.IsValid = false; 
     customValidator.Text = "You have not specified a correct number"; 
    } 

這裏假設你有一個的CustomValidator。

14
int result = int.Parse(textBox1.Text.Trim()); 

如果你想檢查有效期:

int result; 
if (int.TryParse(textBox1.Text.Trim(), out result)) // it's valid integer... 
    // int is stored in `result` variable. 
else 
    // not a valid integer 
+0

喜邁赫達德,我不知道如何做到這一點我碼。也許你可以幫助我。謝謝 – tintincutes 2009-05-23 16:26:33

+0

這不是一個長期的問題。你正在做一個非常耗時和耗費內存的操作。寫入控制檯不需要用很多元素更新GUI對象。基本上,你在一個沒有任何實際用途的列表框中顯示數百萬個元素(誰可以在這麼長的列表中滾動?)並消耗大量資源。 – 2009-05-23 18:05:44

+0

嗨Mehrdad這只是一個學習的測試程序。感謝您的建議 – tintincutes 2009-05-24 20:17:23

1

使用int.TryParse()檢查是否字符串包含整數值。

-1

你在檢查一個空字符串嗎?

int yourInteger; 
string newItem; 
newItem = textBox1.Text.Trim(); 

if(newItem != string.Empty) 
{ 
    if (newItem == Convert.ToInt32(textBox1.Text)) 
    { 
     listBox1.Items.Add(newItem); 
    } 
} 
0

textBox1.Text可能不包含整數的有效字符串表示形式(或者只是一個空字符串)。要解決該問題,請使用Int32.TryParse()

0

你可以這樣做:

Convert.ToInt32(input); 

對於較長的功能使用這個你可以看看: http://msdn.microsoft.com/en-us/library/bb397679.aspx

基本上,它會檢查,如果字符串爲null,則它會調用int.Parse。這也可以在WindowsCE下工作,它沒有int.TryParse。

0

要具體說明爲什麼你的代碼編譯失敗,是因爲你正在比較一個字符串(newItem)和Convert.ToInt32的結果,這是一個整數,它不會讓你這樣做。 Convert.ToInt32也會引發一個異常,它傳入的字符串不是數字。

您可以嘗試使用int.TryParse,或者寫一個簡單的正則表達式來驗證您的輸入:

int i; 
bool isInteger = int.TryParse(textBox1.Text,out i); 

bool isInteger = System.Text.RegularExpressions.Regex.IsMatch("^\d+$", textBox1.Text);