所以我的代碼工作正常,一切。但是,當沒有任何東西放入textbox1和textbox2並且我點擊提交按鈕時,我收到錯誤索引超出了數組邊界。抓住一個錯誤。索引超出了數組的範圍。捕獲一個錯誤
但是我試着輸入一個else來捕獲錯誤並將標籤更改爲Can not Find,而不是服務器錯誤,但它不工作,爲什麼?
這裏是我的代碼:
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) {'...當然這是毫無意義的。您將'TextBox1.Text'分配給'PartNumber',然後立即檢查它們是否相等? – 2014-11-21 19:46:36
你應該更清楚地說明你的意思是「它不工作」。也就是說,你永遠不會進入'else'子句,因爲'if'表達式只是簡單地比較一個變量和一個剛剛用來分配給變量的屬性。它保證他們永遠是平等的。 – 2014-11-21 19:46:50
最簡單的事情是檢查文本框的值查找如何使用'string.IsNullOrEmpty'函數,你可以節省自己很多頭痛,而不必添加'如果條件'檢查你的主要代碼塊是否先檢查..或更好的添加一些消息框,如果兩個文本框的長度都爲'= 0',則會彈出錯誤消息框,開始使用調試器並擺脫舊的'Code and Go'方法 – MethodMan 2014-11-21 19:59:33