2012-11-28 49 views
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); 
      } 
     } 
    } 
} 
+1

'公共Form1中(串FNAME){FILENAME = FNAME; .......' –

+0

的openToolStripMenuItem_Click是Form1类内部的事件? – Steve

+1

这里的一个问题是行'var FileName =(ofd.FileName);'这行声明了隐藏该字段的局部变量。另外,不要在构造函数中创建StreamReader;只要知道文件名是什么,就必须创建它,因此,在openToolStripMenuItem_Click方法的主体中。 – phoog

回答

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(','); 

     } 
+0

谢谢你的回应丹尼尔,但phoog提出了一个我将要使用的优点 – user1744093

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(','); 
      } 
     } 
    } 
} 
相关问题