2015-12-18 30 views
-1

我得到的最奇怪的#1異常的代碼的最後一行:C#形式未知StackOverflowException

inputPrice是的NumericUpDown

private void inputPreis_ValueChanged(object sender, EventArgs e) 
    { 
     if (checkBoxUnlock.Checked == false) 
     { 
      if (oldInputPreisValue == 0) 
      { 
       inputPreis.Value = 5; 
      } 

      else if (oldInputPreisValue == 5) 
      { 
       if (inputPreis.Value > oldInputPreisValue) 
        inputPreis.Value = 8; 
       else if (inputPreis.Value < oldInputPreisValue) 
        inputPreis.Value = 5; 
      } 

      else if (oldInputPreisValue == 8) 
      { 
       if (inputPreis.Value > oldInputPreisValue) 
        inputPreis.Value = 10; 
       else if (inputPreis.Value < oldInputPreisValue) 
        inputPreis.Value = 5; 
      } 
      //etc... 

     } 

     oldInputPreisValue = Convert.ToInt32(inputPreis.Value); 
    } 

的腳本應該讓用戶改變的值numericUpDown(inputPrice)爲固定值。通過檢查checkBoxUnlock checkBox,用戶可以自由設置值。

這是怎麼回事嗎?

+0

它已經是一個整數:oldInputPreisValue = inputPreis.Value; – jdweng

+0

當你設置'inputPreis'的值時,這可能觸發一個事件處理程序嗎?當你調試這個時,你看到這個方法被調用了多少次? – David

+0

該方法一遍又一遍地被調用,但inputPreis的值不會一遍又一遍地被重新設置。只有一次。 –

回答

1

我假定,當你做這樣的事情:

inputPreis.Value = 5; 

,那麼這將隨後致電inputPreis_ValueChanged事件,那麼這將再次設置的值,然後再一次又一次調用事件,直到你達到堆棧溢出異常。

我建議將該值存儲在本地屬性中,並設置該值而不是重置控件中的值。

+0

這正是我爲什麼要檢查「oldInputPreisValue」的原因。如果價格是5,則不會嘗試將價格設置爲5,因爲它只檢查大於或小於5的數字。 –

+0

您是否嘗試過追蹤以確切確定它的位置?這個錯誤告訴我,這正是我上面提到的。 – Andrew

+1

@Azul你錯誤地使用了'ValueChanged'事件。您應該使用'Validating'事件並取消更改,如果值== xy。映射你想要做的值將不可避免地導致一團糟。 – bokibeg