OpenFileDialog.OpenFile方法()文件没有打开。 C#

时间:2016-04-23 16:04:45

标签: c# methods openfiledialog

我正在编写一个允许您打开保存在计算机上的文件的程序,我按照Microsoft提供的文档示例。 (https://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.openfile(v=vs.110).aspx)The问题是,它实际上是不会读取数据,当你打开文件时,它就会回到你刚刚打开程序的时候。我想知道我错过了什么,让它读起来文件。

这是我的表格

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

1 个答案:

答案 0 :(得分: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);

您将string分配给s,然后无法将其解析为double