2016-04-29 4 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); 
     }      
    } 

Я ВЕ к Main_dir, Sub_dir и TargetPath строки, но метод кнопки «Открыть» не работает, пока я не нажму кнопку «Обзор».

Благодарим за помощь!

+0

«открытый способ кнопки не работает, пока не нажать кнопку просмотра» - Как вы предлагаете, чтобы открыть папку, если '' Main_dir', targetPath' и 'Sub_dir' еще не были определены через кнопка «просмотреть»? – Quantic

+0

Исправьте меня, если я ошибаюсь, но я думаю, что он не должен определять через openFiledialog. Main_dir уже определен как @ "C: \ также sub_dir из текстовых полей – NOGRP90

+0

Если я поместил весь код в событие открытой кнопки, а браузер перестанет работать. – NOGRP90

ответ

0

Установите основной каталог по умолчанию из конструктора формы. Затем он будет доступен для любых методов в форме. Sub и целевой путь являются просто функциями и могут быть помещены в методы 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