2012-04-02 50 views
2

我得到異常「輸入字符串格式不正確」。我想處理這個異常並添加我自己的錯誤。輸入應該是一個int。我應該在哪裏做這件事?我有一個使用listview的objectdatasource,我無法從後面的代碼中獲取textbox.text,所以我可以使用tryParse。輸入字符串格式不正確。處理異常

+0

這不是驗證。如果該值錯誤,則不應該像在代碼中那樣設置它。 – leppie 2012-04-02 11:39:51

+5

此屬性已經接受INT。你是什​​麼意思,通過「驗證」。 – Tigran 2012-04-02 11:40:21

+0

你認爲它可以是什麼?除了int – JleruOHeP 2012-04-02 11:40:45

回答

2

您的財產屬於Int32類型。除了有效整數以外,您無法將其他任何內容分配給此屬性。現在,如果您有一些用字符串形式表示的用戶輸入,然後您需要將其分配給整數屬性,則可以使用int.TryParse方法確保用戶輸入的值是有效整數。

例如:

string someValueEnteredByUser = ... 
int value; 
if (!int.TryParse(someValueEnteredByUser, out value)) 
{ 
    // the value entered by the user is not a valid integer 
} 
else 
{ 
    // the value is a valid integer => you can use the value variable here 
} 
+1

我*假設*它是關於*消極/非消極*的東西。但控制已經完成......呃。 – Tigran 2012-04-02 11:42:27

2

Number總是int,它被定義這樣...

你可能想驗證字符串的內容。最簡單的方法是將其解析爲一個int

int number; 

if(!int.TryParse(yourString, out number)) 
{ 
    Not an int! 
} 
+0

編輯我的問題 – 2012-04-02 12:30:05

1

「價值」將永遠是相同類型的變量。因此有:

private bool mabool = false; 

public bool MaBool 
{ 
    get { return mabool; } 
    set { mabool = value; } 
} 

不會崩潰。這是因爲,正如我所說,價值將是相同類型的變量。在這種情況下,值是一個布爾值。

與類嘗試:

public class Rotator 
{ 
    public Roll, Pitch, Yaw; 

    // Declarations here (...) 
} 

private Rotator rotation = new Rotator(); 
public Rotator Rotation 
{ 
    get { return rotation; } 
    set 
    { 
     // Since value is of the same type as our variable (Rotator) 
     // then we can access it's components. 
     if (value.Yaw > 180) // Limit yaw to a maximum of 180° 
      value.Yaw = 180; 
     else if (value.Yaw < -180) // Limit yaw to a minimum of -180° 
      value.Yaw = -180; 

     rotation = value; 
    } 
} 

正如所看到的在第二個例子中,值是一個旋轉器,從而我們可以訪問它的組件。