簡體   English   中英

C#多次嘗試並捕獲文本框值

[英]c# multiple try and catch for textbox values

我試圖分組嘗試並抓住6個文本框值之一。 在課堂上,我描述了類似的6種方法:

public void Setpajamos(int newValue)
{
    if (newValue >= 0 && newValue <= 30)
        pajamos = newValue;
    else
        throw new Exception("Patikrinkite duomenis");
}

在主表單中,我嘗試捕獲代碼:

try
{
    BustoKreditas.Setvaikusk(newvaikusk);
    BustoKreditas.Setpajamos(newpajamos);
    BustoKreditas.Setisipareigojimai(newisipareigojimai);
    BustoKreditas.SetPaskolosSuma(newpaskolosSuma);
    BustoKreditas.Setlaikotarpis(newlaikotarpis);
    BustoKreditas.Setpastatoamzius(newpastatoamzius);

}
catch 
{
    MessageBox.Show("value to big");    
}

問題是try and catch僅在第一個文本框上起作用。 對於其他所有人,我都可以輸入我想要的任何數字,並且它不會顯示任何消息。

我假設您正在嘗試收集所有錯誤。
(在您的代碼中,第一個異常將導致代碼跳轉到catch ,因此不調用任何其他方法。)

在這種情況下,您可以嘗試執行以下操作:

public void Setpajamos(int newValue, List<string> errors)
{
   if (newValue >= 0 && newValue <= 30)
   {
      pajamos = newValue;
   }
   else
   {
      errors.Add("Patikrinkite duomenis");
   }
}

在您的主要形式中:

var errors = new List<string>()
BustoKreditas.Setvaikusk(newvaikusk, errors);
BustoKreditas.Setpajamos(newpajamos, errors);
BustoKreditas.Setisipareigojimai(newisipareigojimai, errors);
BustoKreditas.SetPaskolosSuma(newpaskolosSuma, errors);
BustoKreditas.Setlaikotarpis(newlaikotarpis, errors);
BustoKreditas.Setpastatoamzius(newpastatoamzius, errors);
if (errors.Count > 0)
{
   MessageBox.Show(string.Join(Environment.NewLine, errors));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM