2014-11-21 112 views
-2

所以我的代碼工作正常,一切。但是,當沒有任何東西放入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"; 
    } 
} 

} 
+0

'PartNumber = TextBox1.Text; if(PartNumber == TextBox1.Text) {'...當然這是毫無意義的。您將'TextBox1.Text'分配給'PartNumber',然後立即檢查它們是否相等? – 2014-11-21 19:46:36

+0

你應該更清楚地說明你的意思是「它不工作」。也就是說,你永遠不會進入'else'子句,因爲'if'表達式只是簡單地比較一個變量和一個剛剛用來分配給變量的屬性。它保證他們永遠是平等的。 – 2014-11-21 19:46:50

+0

最簡單的事情是檢查文本框的值查找如何使用'string.IsNullOrEmpty'函數,你可以節省自己很多頭痛,而不必添加'如果條件'檢查你的主要代碼塊是否先檢查..或更好的添加一些消息框,如果兩個文本框的長度都爲'= 0',則會彈出錯誤消息框,開始使用調試器並擺脫舊的'Code and Go'方法 – MethodMan 2014-11-21 19:59:33

回答

0

你有這樣一行:

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或壞的零件編號

+0

謝謝!這工作:) – 2014-11-21 19:55:15

+0

如果他的答案工作,然後請將其標記爲可接受的答案 – MethodMan 2014-11-21 20:00:35

0

也許當無文本在CustomerId中聲明,CheckPartNumberStatus失敗,請嘗試捕獲像這樣的空輸入:

string CustomerID = TextBox2.Text; 
if(CustomerId == string.Empty){ 
    //error display 
    return; 
} 
+0

這工作非常感謝。 – 2014-11-21 19:53:55