2013-04-29 50 views
-1

我有2個文本框,從中嘗試收集數據。 我正在循環它們,但是當程序要從它們那裏收集數據並且它們沒有任何值時,它們是空的,我得到一個格式異常:「輸入字符串格式不正確。」來自文本框的格式異常

if (this.Controls["txt_db0" + count].Text != null) 
{ 
    //if the value in the textbox is not null 
    int db = int.Parse((this.Controls["txt_db0" + count].Text)); 
    //set my "db" integer to the value of the textbox. 
} 

我把if語句有過濾掉,如果在他們沒有價值,甚至儘管我得到的格式異常,所以我必須做一些錯誤的。

+2

將斷點上' int db = ...'並檢查this.Controls [「txt_db0」+ count] .Text'的值。 – zimdanen 2013-04-29 15:28:26

+0

那麼取決於你在調試時發現了什麼:) – phadaphunk 2013-04-29 15:32:35

+0

'那麼在文本框中,編譯器不能分析/轉​​換爲Int的格式是什麼?我不知道,它可能是什麼? *你需要遍歷你的代碼,找出'int.Parse'失敗的值。你可能會在這個過程中回答你自己的問題,如果沒有,提供一些必要的信息,任何人都可以回答這個問題。 – tnw 2013-04-29 15:32:59

回答

1

來檢查你的工作,你可以做到這一點

int testInt; 
if (int.TryParse(this.Controls["txt_db0" + count].Text,out testInt)) 
{ 
    //if the value in the textbox is not null 
    int db = testInt; 
    //set my "db" integer to the value of the textbox. 
} 
else 
    MessageBox.Show(this.Controls["txt_db0" + count].Text + " Not an Int"); 
+1

控件的文本屬性(在.NET框架中)從不爲null。 – 2013-04-29 15:41:20

+0

@MartinMulder:yup :)你是對的,我編輯我的答案 – Akrem 2013-04-29 15:49:08

0

如果int.Parse會拋出異常:

  • 輸入字符串包含字母,或無法被識別爲其他特殊字符數。
  • 輸入字符串是一個空字符串。

如果你確信你輸入的字符串僅包含數字,請檢查您的字符串是空的轉換前先:

string input = this.Controls["txt_db0" + count].Text; 
int db = input == "" ? 0 : int.Parse(input); 

或者你可以使用:

int db; 
if (!int.TryParse(this.Controls["txt_db0" + count].Text, out db)) 
    // Do something else.