2011-09-24 52 views
1

我需要創建一個簡單的c#應用程序來添加一些季度數字。我使用數組來「存儲」數據,然後將其放置在文本框中。我的「計算」怎麼會不起作用?

無論如何,我的計算部分有一些問題。我在它周圍添加了評論標籤,以便您可以輕鬆找到它。該地區的作品,但它需要兩次點擊,並將其添加到上面的行。我一直在看相同的幾行約一個小時,似乎無法弄清楚這一點。那裏有任何想法?

//Global 
    int lastIndexUsed = -1; 
    int[,] quarters = new int[10, 5]; 
    string[] Branch = new string[10]; 

    public FrmSales() 
    { 
     InitializeComponent(); 
    } 

    private void txtBranch_TextChanged(object sender, EventArgs e) 
    { 

    } 

    private void btnCalc_Click(object sender, EventArgs e) 
    { 
     int Q1; 
     int Q2; 
     int Q3; 
     int Q4; 


     Q1 = int.Parse(txtQ1.Text); 
     Q2 = int.Parse(txtQ2.Text); 
     Q3 = int.Parse(txtQ3.Text); 
     Q4 = int.Parse(txtQ4.Text); 

     lastIndexUsed = lastIndexUsed + 1; 
     quarters[lastIndexUsed, 0] = Q1; 
     quarters[lastIndexUsed, 1] = Q2; 
     quarters[lastIndexUsed, 2] = Q3; 
     quarters[lastIndexUsed, 3] = Q4; 
     Branch[lastIndexUsed] = txtBranch.Text; 








     //Display Results 

     int ctr; 
     int ctr2; 
     string outLine; 
     string tempName; 

     int row; 
     int col; 
     int accum; 


     txtInfo.Text = ""; 

     outLine =   " Branch  Q1   Q2   Q3   Q4  Total " + "\r\n"; 
     outLine = outLine + "========== ========== ========== ========== ========== ==========" + "\r\n"; 

     txtInfo.Text = outLine; 


     for (ctr = 0; ctr <= lastIndexUsed; ctr++) 
     { 

      outLine = ""; 

      tempName = Branch[ctr].PadLeft(10); 
      outLine = outLine + tempName + " "; 

      for (ctr2 = 0; ctr2 <= 4; ctr2 = ctr2 + 1) 

      { 


       outLine = outLine + quarters[ctr, ctr2].ToString().PadLeft(10) + " "; 

      } 

      txtInfo.Text = txtInfo.Text + outLine + "\r\n"; 


     } 

     //Calculate ########################################################### 

     for (row = 0; row <= lastIndexUsed; row++) 
     { 

      accum = 0; 


      for (col = 0; col <= 3; col++) 
      { 

       accum = accum + quarters[row, col]; 

      } 
      quarters[row, 4] = accum; 
     } 




     //End Calculate ######################################################### 

    } 

    private void btnClear_Click(object sender, EventArgs e) 
    { 
     txtBranch.Text = ""; 
     txtQ1.Text = ""; 
     txtQ2.Text = ""; 
     txtQ3.Text = ""; 
     txtQ4.Text = ""; 
     txtInfo.Text = ""; 

    } 

    private void btnExit_Click(object sender, EventArgs e) 
    { 
     Close(); 
    } 
+1

爲了必要的多少代碼的是證明問題? –

+0

我只是想完整的代碼,所以可以分析,人們可以得到一個完整的理解。 (也許錯誤是在不同的位置?) – Brandon

+2

我會很容易與該空白。 – Blender

回答

5

問題很簡單:在實際計算它的值之前使用quarters數組。將「calculate」循環移到第一個循環的上方。

另外(除其他外):

  • 太多空行和空白;使其難以閱讀
  • 不要嘗試使用文本進行格式化報告;如果您單擊按鈕足夠的時間只使用一個DataGridView或類似
  • ,你將有一個數組索引越界異常,因爲lastIndexUsed會高於10
+0

我同意,一些細節有點粗略,但我按照要求做。最後,我必須添加驗證,以便在輸入10以上時不會出錯。使用文本框製作格式化報告的想法非常奇怪並且很難實現。感謝您的幫助,解決了問題! – Brandon