2016-04-23 57 views
-1

我正在編寫一個程序,該程序將允許您打開保存在您計算機上的文件,我遵循了Microsoft對其文檔的示例。 (https://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.openfile(v=vs.110).aspx)The問題出現,是它不會真正讀取數據,當您打開文件時,它只會回到您剛纔打開的程序,我想知道我錯過了什麼,使它讀取文件。OpenFileDialog.OpenFile方法()文件沒有開啓。 C#

這裏是我的形式

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.IO; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace Lab12 
{ 
    public partial class Form1 : Form 
    { 
     //ref the class and create an array. 
     private EmployeesClass[] Employee = new EmployeesClass[SIZE]; 
     //state any constants 
     const int SIZE = 10; 
     const int ZERO = 0; 
     const int ONE = 1; 
     private int counter = ZERO; 
     private int numEmployees = ZERO; 
     public Form1() 
     { 
      InitializeComponent(); 

     } 
     //Exit Program 
     //Purpose: To Exit the program. 
     //Perameters: The sending objcet and event arguments. 
     //Returns: none 
     private void exitToolStripMenuItem1_Click(object sender, EventArgs e) 
     { 
      //closes the program 
      this.Close(); 
     } 
     //Display about 
     //Purpose: To show detail about the program. 
     //Parameters: The sending objcet and event arguemts. 
     //Returns: Info about the program. 
     private void aboutToolStripMenuItem_Click(object sender, EventArgs e) 
     { 
      //This is display about info program 
      MessageBox.Show("Devin\nCS1400\nProjects #12"); 
     } 
     //Emplyee info method 
     //Purpose: To return employee info saved on a file on the computer. 
     //Parameters: The sending objcet and event arguemts. 
     //Returns: Employee info 
     private void openToolStripMenuItem_Click(object sender, EventArgs e) 
     { 

      Stream myStream; 

      OpenFileDialog payRollFile = new OpenFileDialog(); 

      payRollFile.InitialDirectory = "c:\\Documents"; 

      payRollFile.Filter = "txt files (*.txt) | *.txt|All files (*.*)|*.*"; 
      payRollFile.FilterIndex = 2; 

      payRollFile.RestoreDirectory = true; 

      if (payRollFile.ShowDialog() == DialogResult.OK) 
      { 
       try 
       { 

        if ((payRollFile.ShowDialog() != DialogResult.OK || (myStream = payRollFile.OpenFile()) != null)) 
         return; 
        { 

         using (myStream) 
         { 

          StreamReader streamReader = new StreamReader(myStream); 
          string s = "test"; 
          double employeeNumber = double.Parse(s); 

          string employeeName = streamReader.ReadLine(); 
          string employeeAddress = streamReader.ReadLine(); 

          s = streamReader.ReadLine(); 
          string[] strArray = s.Split(); 

          double hourlyWage = double.Parse(strArray[0]); 
          double hoursWorked = double.Parse(strArray[1]); 
          Employee[counter++] = new EmployeesClass(employeeNumber, employeeName, employeeAddress, hoursWorked, hourlyWage); 


          nextButton.Enabled = true; 
          numEmployees = this.counter; 
          counter = 0; 
          nameTxtBox.Text = Employee[counter].GetName(); 
          addressTxtBox.Text = Employee[counter].GetAddress(); 
          netPayTxtBox.Text = string.Format("{0:C}", Employee[counter].netPay()); 
         } 
        } 

       } 
       catch (Exception ex) 
       { 
        MessageBox.Show("Error: Could not read file from disk. Original error:" + ex.Message); 
       } 
      } 


     } 
     // Next Button method 
     //Purpose: allows user to move forward through all of the data on the file. 
     //Parameters: Sender Objects , and event arguements. 
     //returns: The ablility to move forward through the data 
     private void nextButton_Click(object sender, EventArgs e) 
     { 
      //create a counter. 
      //counter++; 
      //create an if state ment that will let you click the button to move to the next item from the file 
      //as long as the counter is less then the number of the employees. 
      if (counter < numEmployees - ONE) 
      { 
       counter += ONE; 
       //get the names from the class, and display them in the name text box 
       nameTxtBox.Text = Employee[counter].GetName(); 
       //get the Addresses from the class, and display them in the address text box 
       addressTxtBox.Text = Employee[counter].GetAddress(); 
       //get the Total amount that the employee will take from the class, and display them in the pay text box 
       //convert the double to string 
       netPayTxtBox.Text = string.Format("{0:C}", Employee[counter].netPay()); 
      } 
      else 
      { 
       //if there are no more items, have the button become disabled. 
       //then clear all of the boxes once it runs out of data. 
       nextButton.Enabled = true; 

      } 
     } 
     // Back Button method 
     //Purpose: allows user to move backwords through all of the data on the file. 
     //Parameters: Sender Objects , and event arguements. 
     //returns: The ablility to move backwards through the data 
     private void backButton_Click(object sender, EventArgs e) 
     { 
      //create a counter. 
      // counter--; 
      //create an if state ment that will let you click the button to move to the next item from the file 
      //as long as the counter is less then the number of the employees. 
      if (counter > ZERO) 
      { 
       counter -= ONE; 
       //get the names from the class, and display them in the name text box 
       nameTxtBox.Text = Employee[counter].GetName(); 
       //get the Addresses from the class, and display them in the address text box 
       addressTxtBox.Text = Employee[counter].GetAddress(); 
       //get the Total amount that the employee will take from the class, and display them in the pay text box 
       //convert the double to string 
       netPayTxtBox.Text = string.Format("{0:C}", Employee[counter].netPay()); 
      } 
      else 
      { 
       //if there are no more items, have the button become disabled.     
       nextButton.Enabled = true; 

      } 
     } 
     //clear button method 
     //Purpose: Allows user to clear the text boxes manueley 
     //Returns Nothing. 
     private void clearButton_Click(object sender, EventArgs e) 
     { 
      nameTxtBox.Clear(); 
      addressTxtBox.Clear(); 
      netPayTxtBox.Clear(); 
     } 
    } 
} 

這裏是我的類

//EmplyeesClass 
    //Purpose: To determin how much an employee is payed, how much they have to pay in taxes, their address, and name, and employee number 
    //returns. Name, Address, How much they make after taxes. 
    class EmployeesClass 
    { 
     //stat any constants that will be used in this program 
     // such as full time hours, overtime payment, state tax percent, and Fedreal tax rate. 
     const int FULLTIME = 40; 
     const double OVERTIME = 0.5; 
     const double FEDTAXRATE = 0.075; 
     const double STATETAXRATE = 0.2;   
     const double ZERO = 0; 
     //set any variables that will be used in this class. 
     private double employeeNumber; 
     private string employeeName; 
     private string employeeAddress; 
     private double hourlyWage; 
     private double hoursWorked; 
     //create the Employees class that can be accessed in the open tool method. 
     public EmployeesClass(double employeeNumber, string employeeName, string employeeAddress, double hoursWorked, double hourlyWage) 
     { 
      this.employeeNumber = employeeNumber; 
      this.employeeName = employeeName; 
      this.employeeAddress = employeeAddress; 
      this.hoursWorked = hoursWorked; 
      this.hourlyWage = hourlyWage; 
     } 
     //create the method for payment of the employee 
     public double netPay() 
     { 
      //get the gross pay by mulitplying how many hours they work by what they make an hour. 
      double gross = hoursWorked * hourlyWage; 
      //if the employee worked more than 40 hours get them overtime 
      double overtime = hoursWorked - FULLTIME; 
      //take there gross and subrtract the state tax 
      double stateTax = gross * STATETAXRATE; 
      //take their gross and subtract the fedrual tax 
      double fedTax = gross * FEDTAXRATE; 

      //set up an if statement to determin if they get overtime pay 

      if (overtime > ZERO) 
       gross += overtime * (hourlyWage * OVERTIME); 

      //return the the amount of they have earned with overtime. 
      return gross - stateTax - fedTax; 
     } 
     //return the hours the employees have worked. 
     public double GetHours() 
     { 
      return hoursWorked; 
     } 
     //return the amount of money they have made the employees have worked. 
     public double NetWage() 
     { 
      return hourlyWage; 
     } 
     //return the the employees address. 
     public string GetAddress() 
     { 
      return employeeAddress; 
     } 
     //return the employees name. 
     public string GetName() 
     { 
      return employeeName; 
     } 

    } 
} 

下面是基本的信息,你可以保存到一個txt文件在您的計算機上。

1 
John MerryWeather 
123 West Main Street 
5.00 30 
2 
Andrew Buttons 
17 East Riverview Drive 
12.00 40 
3 
Martha Washington 
1 Mount Vernon Lane 
7.25 20 
4 
Harry Skilling 
786 No. Rodeo Drive 
8.00 45 
5 
Ann Mindbender 
192 Wizard Street 
9.00 40 
6 
Carl Zabriskie 
42 No. State Street 
10.50 42 
+0

您應該再次考慮您的評論做法! – dotctor

+2

我看到你會在代碼中彈出兩次對話框,這是多餘的'payRollFile.ShowDialog()' –

+1

您是否使用調試器來查看哪些事件被觸發以及邏輯如何流動? –

回答

0

這個錯誤是因爲下面一行:

if ((payRollFile.ShowDialog() != DialogResult.OK || (myStream = payRollFile.OpenFile()) != null)) 
    return; 

第一個測試不應該在那裏,你已經測試過,對話框將出現兩次。其次,如果(myStream = payRollFile.OpenFile())成功,它將爲NOT null並返回,因此當事情正常時,您的方法會簡單地返回。

它應該是這樣的:

if (myStream = payRollFile.OpenFile()) == null)) 
    return; 

其次,這條線將導致異常:

string s = "test"; 
double employeeNumber = double.Parse(s); 

您分配一個strings那麼它就不能被解析爲double