2014-01-16 38 views
-1

我對C#來說很新,我一直在尋找一個小時左右的時間來找到我需要的,但找不到它。我正在試圖查看32個不同文本框的內容,使用for循環。 我此刻的代碼是:C#使用for循環來處理WinForm環境中的多個元素

private void btnCalculate_Click(object sender, EventArgs e) 
    { 
     string ElementString; 
     Control ElementControl; 
     double Num; 
     Boolean errorMsg = false; 

     for (int x = 1; x <= 4; x++) 
      for (int y = 1; y <= 4; y++) 
      { 
       ElementString = "txtA" + x.ToString() + y.ToString(); 
       ElementControl = this.Controls[ElementString]; 
       ElementString = ElementControl.Text.Trim(); 

       if (!double.TryParse(ElementString, out Num)) 
       { 
        errorMsg = true; 
        break; 
       } 
      } 

     if (errorMsg) 
      MessageBox.Show("Error Processing Input Matricies, invalid entries"); 
    } 

好的改變這一部分,很抱歉不能把更多的信息,但希望這會有所幫助。

單擊按鈕時程序崩潰。這條線時崩潰:

ElementString = ElementControl.Text.Trim(); 

並給出錯誤信息: Object reference not set to an instance of an object.

謝謝

+5

「它不工作」(原文如此)是*永遠*足夠的信息。請閱讀http://tinyurl.com/so-list –

+0

可能的重複[什麼是NullReferenceException,我該如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception -and-how-do-i-fix-it) –

回答

1

你需要做的第一件事是檢查是否ElementControl爲null。在調用引發異常的行之前就這樣做。

做到這一點的另一種方法是搜索容器中的所有TextBox控件,並以這種方式檢查它們。您可以使用以下方法來做到這一點:

foreach(Control c in this.Controls) 
{ 
    if (c is TextBox) 
    { 
     // Do whatever you want to do with your textbox. 
    } 
} 

這比試圖調用按名稱檢索控制變得更加富有活力。

0

把一個彷彿繞着它崩潰的部分語句:

if(ElementControl != null) 
{ 
    ElementString = ElementControl.Text.Trim(); 
} 
else 
{ 
//Handle error if element control is null 
} 
+0

謝謝你的幫助。我的代碼確實起作用,只是文本框位於groupbox內的事實。 – user3202809