2011-07-15 17 views
1

我一直在嘗試將年齡轉換爲從我的asp窗體中的輸入框中獲取的字符串並將其轉換爲整數。ASP.net將inputbox字符串轉換爲整數?

該整數變量將用於我已計劃的數據庫操作。

以下是我已經tryed:

string mytxtCHI = txtID.Text; 
      int @CHI = Convert.ToInt16(mytxtCHI); 

錯誤:

System.FormatException

事情我已經試過{ 「輸入字符串的不正確的格式。」}:

- string mytxtCHI = txtID.Text; 
      int myNewID=(Int32.Parse(txtID.Text)); 

謝謝你的時間:)

+2

看起來您在輸入框中沒有數字。什麼是文字? – BrokenGlass

+0

你的輸入如何看起來像 –

+0

查找'int.TryParse'。 –

回答

1

你的方法是正確的,但你應該做的,以避免錯誤

int myNewID = 0; 

    if(int.TryParse(txtID.Text, out myNewID)) 
    { 
     //your code here 
    } 
    else 
    { 
     //your error handling here 
    } 
+0

感謝開發人員,TryParse Worked – TerryTheTerminator

1

你應該使用的TryParse:

string mytxtCHI = txtID.Text; 
    int number; 
    bool result = Int32.TryParse(mytxtCHI , out number); 
    if (result) 
    { 
    Console.WriteLine("Converted '{0}' to {1}.", mytxtCHI , number);   
    } 
    else 
    { 
    if (value == null) value = ""; 
    Console.WriteLine("Attempted conversion of '{0}' failed.", mytxtCHI); 
    } 
0

您應該使用Int.TryParse,而當值不是一個有效的整數處理的情況。

string mytxtCHI = txtId.Text; 
int val; 
if (!int.TryParse(mytxtCHI, out val)) 
{ 
    // error here, value was not a valid integer. 
} 
// here, val contains the value, expressed as an integer. 
0

使用監視窗口或System.Diagnostics.Debug.WriteLine(mytxtCHI)檢查什麼是你正在傳遞的價值,是空白的?

1

在Visual Studio中放置一個斷點。在調試模式下,運行到斷點,然後將鼠標懸停在txtID.Text上以查看其中的內容。

當你在頁面生命週期中檢查這個值嗎?在頁面初始化後檢查它。檢查HttpRequest.Form以查看線路上發生了什麼。