开发者

using string in other method

i have the following code. i need to do this:

public void Window1()
{
   InitializeComponent();
   opendirectory();
}

public void opendirectory()
{
    Stream checkStream = null;
    Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();

     openFileDialog.Multiselect = false;    

     if ((bool)openFileDialog.ShowDialog())
     {
          try
          {
                if ((checkStream = openFileDialog.OpenFile()) != null)
                {
                    // i need the following code to be stored as a string
                    string antcbatchlocation = openFileDialog.FileName;                   
                }
  开发者_如何学编程         }
           catch (Exception ex)
                {
                        System.Windows.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
            else 
            {
                System.Windows.MessageBox.Show("Problem occured, try again later");
            }
        }

then i will use that string in a later button event:

public void BuildButton_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process runantc = new System.Diagnostics.Process();

            runantc.StartInfo.FileName = antcbatchlocation;
        }

Perhaps something is wrong with this string as a variable. Seems to be like string antcbatchlocation is declared local variable. If so how should i go about fixing it? Please help thanks!


You should declare your string as a private member of your Window1 class, rather than a local variable in your opendirectory method. Then, in your button click method, simply check to make sure your string is not null, so you know the user has gone through your dialog and selected a file first.


You need to use an instance variable. That means that it's a variable that is local to the class instance (in this case `Window1). This also means that it's accessible to any method inside that class instance.

Add this line of code in your class declreation, just above the public Window1(){} constructor.

private string _BatchLocation;

then inside the opendirectory() method, instead of creating a local string variable, set the openFileDialog.FileName to this instance variable.

_BatchLocation = openFileDialog.FileName;

you can then access this in the click event handler... thus your code will look like this:

runantc.StartInfo.FileName = _BatchLocation;

Have a look at this post for more information: http://www.codeguru.com/csharp/csharp/cs_syntax/anandctutorials/article.php/c5829

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜