2013-10-28 57 views
1

我有一個船停泊預訂計劃,目前,它的工作方式是,在你輸入你的名字並點擊一個按鈕後,該計劃將爲你提供下一個可用停泊系統,每個碼頭有6個碼頭和5個停泊處。如何向用戶顯示此代碼的消息?

因此,在所有的繫泊和碼頭用完之後,程序崩潰了,因爲它沒有任何可去的地方,我怎麼能讓它使用戶得到一個消息框告訴他們,沒有更多的斑點可用?

這是我的代碼:

按鈕點擊:

private void button1_Click(object sender, EventArgs e) 
{ 
    var req = new BoatRequest(); 
    req.Name = txtName.Text; 
    var client = new BoatReserveSoapClient(); 
    BoatResponse response = client.ReserveMooring(req); 

    if (req != null) 
    { 
     Pierlbl.Text = response.Pier.ToString(); 
     Mooringlbl.Text = response.Mooring.ToString(); 
     Pierlbl.Visible = true; 
     Mooringlbl.Visible = true; 
    } 
    else 
    { 
     Pierlbl.Text = "Error Occured, please try again"; 
     Mooringlbl.Text = "Error Occured, please try again"; 
    } 
} 

Web方法:

//Setting the max value for Piers and Moorings 
public const int maxPiers = 6; 
public const int maxMoorings = 30; 
private static bool[,] reserveMooring = new bool[maxPiers, maxMoorings]; 

[WebMethod] 
public BoatResponse ReserveMooring(BoatRequest req) 
{ 
    var res = new BoatResponse(); 

    //if pierCalc set to 0, if smaller than maxPiers increment 
    for (int pierCalc = 0; pierCalc < maxPiers; pierCalc++) 
    { 
     //if mooringCalc set to 0, if smaller than maxMoorings increment 
     for (int mooringCalc = 0; mooringCalc < maxMoorings/maxPiers; mooringCalc++) 
     { 
      if (!reserveMooring[pierCalc, mooringCalc]) 
      { 
       reserveMooring[pierCalc, mooringCalc] = true; 
       res.Pier = (Pier)pierCalc; 
       res.Mooring = (Mooring)mooringCalc; 
       return res; 
      } 
     } 
    } 
    return null; 
} 

這是它崩潰了:

Pierlbl.Text = response.Pier.ToString(); 
+1

但是你構造這一點,請不要告訴他們再次嘗試 - 告訴他們,有沒有可用的繫泊,如果可能的話,告訴他們,當一個可能是可用未來。 – LindaCamillo

回答

2

檢查response不爲空,這樣的:

if (response != null) 
{ 
    Pierlbl.Text = response.Pier.ToString(); 
    Mooringlbl.Text = response.Mooring.ToString(); 
    Pierlbl.Visible = true; 
    Mooringlbl.Visible = true; 
} 
else 
{ 
    Pierlbl.Text = "Error Occured, please try again"; 
    Mooringlbl.Text = "Error Occured, please try again"; 
} 
+0

+1檢查請求的響應,而不是請求本身。 –

0

你應該只檢查響應!= null,如果是這種情況,請向用戶顯示一條消息。

+0

不知道我是否做錯了,但它不適合我 – user2469932

0

在這個例子中,REQ是永遠不會等於響應對象正在從您的Web服務接收返回值,因此將檢查if語句中的空值。

像這樣:

if (response != null) 
     { 
      //Logic for success 
     } 
     else 
     { 
      //Logic for failure 
     } 
相關問題