我有一个船泊位预订计划,目前,它的工作方式是,在您输入您的名字并单击按钮后,该程序为您提供下一个可用的系泊设备,每个码头有6个码头和5个系泊设备。 / p>
因此,在所有系泊设备和码头用完后,程序崩溃了,因为它无处可去,我怎样才能让用户得到一个消息框告诉他们,没有更多可用的点?
这是我的代码:
按钮点击:
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";
}
}
网络方法:
//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();
答案 0 :(得分: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";
}
答案 1 :(得分:0)
您应该检查是否响应!= null,如果是这种情况,请向用户显示一条消息。
答案 2 :(得分:0)
在此示例中, req 永远不会等于 null 。 响应对象正在从Web服务接收返回值,因此将在if语句中检查空值。
像这样:
if (response != null)
{
//Logic for success
}
else
{
//Logic for failure
}