2016-04-29 75 views
1

我想知道如何從其他方法調用/使用字符串。如何在不同的事件中使用字符串變量?

public partial class PPAP_Edit : Form 
    { 
    string Main_dir { get; set; } 
    string Sub_dir { get; set; } 
    string targetPath { get; set; } 

...等等,我不想複製所有

private void button_browse_Click(object sender, EventArgs e) 
    { 
     if (od.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
     { 
      try 
      { 
       Main_dir = @"C:\Users\h109536\Documents\PPAP\"; 
       Sub_dir = text_PSW_ID.Text + "_" + text_Partnumber.Text + "_" + text_Partrev.Text + @"\"; 
       targetPath = System.IO.Path.Combine(Main_dir, Sub_dir); 
       { 
        if (!System.IO.Directory.Exists(targetPath)) 
        { 
         System.IO.Directory.CreateDirectory(targetPath); 
         MessageBox.Show("Folder has been created!"); 
        } 
        foreach (string fileName in od.FileNames) 

         System.IO.File.Copy(fileName, targetPath + System.IO.Path.GetFileName(fileName), true); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("An error has occurred: " + ex.Message); 
      } 
        } 
private void button_open_Click(object sender, EventArgs e) 
    {    
     if (!Directory.Exists(targetPath)) 
     { 
      MessageBox.Show("Folder is not added to the database!"); 
      System.Diagnostics.Process.Start("explorer.exe", Main_dir);     
     } 
     else 
     { 
      System.Diagnostics.Process.Start("explorer.exe", Main_dir + Sub_dir); 
     }      
    } 

我reffering到Main_dirSub_dirTARGETPATH字符串,但直到我單擊瀏覽按鈕時,打開按鈕方法才起作用。

非常感謝您的幫助!

+0

「打開按鈕方法不起作用,直到我單擊瀏覽按鈕」 - 你打算如何打開,如果'Main_dir','targetPath'和'Sub_dir'尚未通過定義文件夾「瀏覽」按鈕? – Quantic

+0

糾正我如果我錯了,但我認爲它不應該通過openFiledialog定義。 Main_dir已被定義爲@「C:\也是文本框中的sub_dir – NOGRP90

+0

如果我把整個代碼放到打開的按鈕事件中而不是瀏覽器方法停止工作 – NOGRP90

回答

0

從窗體的構造函數中設置主目錄的默認值。它隨後可用於表單中的任何方法。子路徑和目標路徑只是函數,可以放在屬性getter方法中。

public partial class PPAP_Edit : Form 
{ 
    // set this from constructor 
    public string MainDir { get; set; } 

    // can't set this in constructor as it requires access to form controls, but can just use the getter 
    public string SubDir 
    { 
     get 
     { 
      return text_PSW_ID.Text + "_" + text_Partnumber.Text + "_" + text_Partrev.Text + @"\"; 
     } 
    } 

    // again just use the getter 
    public string TargetPath 
    { 
     get 
     { 
      return Path.Combine(MainDir, SubDir); 
     } 
    } 

    // set defaults in constructor 
    public PPAP_Edit() 
    { 
     MainDir = @"C:\Users\h109536\Documents\PPAP\"; 
    } 
} 
+0

完美運行!非常感謝! – NOGRP90

+0

沒問題:-) – Erresen

相關問題