2012-11-28 90 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(','); 
      } 
     } 
    } 
} 
相關問題