2017-10-15 21 views
2

我想創建一個讀取選定文件並將其顯示到文本框中的WinForm。我的問題是讓我的對象被其他事件處理程序訪問。我基本上希望我的文件名在單擊選擇後顯示在文本框中,但我希望文件內容在單擊打開按鈕後進入單獨的文本框。當我將對象放入選擇按鈕時顯示文件名,但當我嘗試將其放入打開按鈕時,我無法再次訪問該內容。你可以看到我所有的東西我註釋掉了,我試圖C#winforms如何在不同的事件處理程序中訪問同一個對象

public partial class xmlForm : Form 
{ 
    OpenFileDialog openFileDialog1 = new OpenFileDialog(); 

    public xmlForm() 
    { 
     InitializeComponent(); 
    } 

    public void btnSelect_Click(object sender, System.EventArgs e) 
    { 
     // Displays an OpenFileDialog so the user can select a Cursor. 
     // OpenFileDialog openFileDialog1 = new OpenFileDialog(); 
     openFileDialog1.Filter = "XML files|*.xml"; 
     openFileDialog1.Title = "Select a XML File"; 

     // Show the Dialog. 
     // If the user clicked OK in the dialog and 
     // a .xml file was selected, open it. 
     if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
     { 
      displayBox.Text = openFileDialog1.FileName; 
      var onlyFileName = System.IO.Path.GetFileName(openFileDialog1.FileName); 
      displayBox.Text = onlyFileName; 

      /* Button btn = sender as Button; 
      if (btn != null) 
      { 
       if (btn == opnButton) 
       { 
        string s = System.IO.File.ReadAllText(openFileDialog1.FileName); 
        fileBox.Text = s; 
       } 
      }*/ 
      /* if (opnButtonWasClicked) 
      { 
       string s = System.IO.File.ReadAllText(openFileDialog1.FileName); 
       fileBox.Text = s; 
       opnButtonWasClicked = false; 
      } */ 
     } 

     /*string s = System.IO.File.ReadAllText(openFileDialog1.FileName); 
     fileBox.Text = s; */ 
    } 

    public void opnButton_Click(object sender, EventArgs e) 
    { 
     string s = System.IO.File.ReadAllText(openFileDialog1.FileName); 
     fileBox.Text = s; 

     /*if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
     { 
      Button btn = sender as Button; 
      if (btn != null) 
      { 
       if (btn == opnButton) 
       { 
        string s = System.IO.File.ReadAllText(openFileDialog1.FileName); 
        fileBox.Text = s; 
       } 
       else { } 
      } 
     }*/ 
    } 
} 
+1

另外,你可以改變'System.IO.File.ReadAllText(openFileDialog1.FileName);''來System.IO.File.ReadAllText(displayBox.Text);' –

回答

1

既然你已經打開了的FileDialog的btnSelect_Click處理程序中;因此,在關閉此功能之前,您無法打開已打開的對話框。所以爲了再次打開對話框,你必須先關閉它。然後你也可以使用下面的語句:

string s=System.IO.File.ReadAllText(openFileDialog1.FileName); 
fileBox.Text = s; 

但在你的情況,爲您服務,不需要關閉後重新打開對話的目的。因此,只需將作爲ReadnllText方法參數的displayBox.Text作爲已包含文件名的文本字段傳遞給opnButton_Click處理程序。

string System.IO.File.ReadAllText(displayBox.Text); 
fileBox.Text = s; 

感謝

+0

謝謝您的幫助。 – Sayid

相關問題