1

我正在尝试将从我的 openButton 获取的路径名发送到构造函数,以便我可以使用其中的信息。任何人都可以看到如何做到这一点?

namespace GPSCalculator
{
    public partial class Form1 : Form
    {
       private String[] items;
       int count = 0;
       string FileName;
       public Form1()
        {
            InitializeComponent();
            List<float> inputList = new List<float>();
            TextReader tr = new StreamReader(FileName);
            String input = Convert.ToString(tr.ReadToEnd());
            items = input.Split(',');

        }
private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Csv Files (*.csv)|*.csv|Text files (*.txt)|*.txt|All files (*.*)|*.*";
            if (ofd.ShowDialog(this).Equals(DialogResult.OK))
            {
                var FileName = (ofd.FileName);
            }
        }
    }
}
4

2 回答 2

0

你不能,表单上的按钮不能调用它自己的构造函数,所以你需要将构造函数中的一些操作移动到一个单独的方法中。

namespace GPSCalculator
{
    public partial class Form1 : Form
    {
        private string[] items;
        private int count = 0;
        private string fileName;

        public Form1()
        {
            InitializeComponent();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog();
            ofd.Filter = "Csv Files (*.csv)|*.csv|Text files (*.txt)|*.txt|All files (*.*)|*.*";
            if (ofd.ShowDialog(this).Equals(DialogResult.OK))
            {
                // I've changed this to refer to the field and removed un-necessary parenthesis
                this.fileName = ofd.FileName;
            }
        }

        private void ReadFileContents()
        {
            List<float> inputList = new List<float>(); // This doesn't get used?!

            // StreamReader is IDisposable so it should be used in a using statement
            using(TextReader tr = new StreamReader(this.fileName))
            {
                string input = Convert.ToString(tr.ReadToEnd());
                this.items = input.Split(',');
            }
        }
    }
}
于 2012-11-28T16:03:07.697 回答
0
       //add filename to the constructor
       public Form1(string filename)
        {
            InitializeComponent();
            List<float> inputList = new List<float>();
            //use the filename from the constructor to open the StreamReader
            TextReader tr = new StreamReader(filename);
            //set your FileName filename passed in
            FileName = filename;
            String input = Convert.ToString(tr.ReadToEnd());
            items = input.Split(',');

        }
于 2012-11-28T16:01:12.293 回答