索引超出数组的范围.捕获错误
本文关键字:错误 范围 数组 索引 | 更新日期: 2023-09-27 18:31:22
所以我的代码工作正常,一切正常。 但是当文本框 1 和文本框 2 中没有任何东西并且我点击提交按钮时,我收到错误索引超出了数组的范围。捕获错误。
但是,我尝试输入 else 来捕获错误并将标签更改为"找不到",而不是服务器错误,但它不起作用,为什么会这样?
这是我的代码:
protected void Button1_Click(object sender, EventArgs e)
{
string CustomerID = TextBox2.Text;
// 1off
WebReference.WebServiceTyped ws = new WebReference.WebServiceTyped();
WebReference.CheckPartStatus PQ = new WebReference.CheckPartStatus();
string Parts = "";
string PartNumber = Parts;
string PriceSum = null;
long QtySum = 0;
PartNumber = TextBox1.Text;
if (PartNumber == TextBox1.Text)
{
PQ = ws.CheckPartNumberStatus(PartNumber, CustomerID, "1,6,8,9,112", "", "", "");
PriceSum = String.Format(PQ.Parts[0].Cost.ToString(), "####.00");
Label1.Text = PriceSum;
}
else
{
Label1.Text = "Cannot Find";
}
}
}
你有这样一行:
PartNumber = TextBox1.Text;
紧接着是这个:
if (PartNumber == TextBox1.Text)
鉴于您只是将该值设置为 PartNumber
,这将始终是正确的。 因此,您将永远不会输入else
语句。
您应该做的是在使用之前检查PQ
中是否有任何东西:
if (PQ.Parts.Length>0)
{
PriceSum = String.Format(PQ.Parts[0].Cost.ToString(), "####.00");
Label1.Text = PriceSum;
}
else
{
Label1.Text = "Cannot Find";
}
这将解决许多问题:错误的客户ID或错误的部件号
也许当 CustomerId 中没有声明任何文本时,CheckPartNumberStatus 失败,请尝试像这样捕获空输入:
string CustomerID = TextBox2.Text;
if(CustomerId == string.Empty){
//error display
return;
}