Reputation: 51
In my app, the user can browse and select a text file. I'm saving the path like this:
private void nacitanie_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Otvoriť Textový súbor.";
dialog.Filter = "TXT files|*.txt";
dialog.InitialDirectory = @"C:\";
if (dialog.ShowDialog() == DialogResult.OK)
{
string path = dialog.FileName;
}
}
Then I need to work with that path in other buttons. How can I return the path of the text file from the button handler method?
Upvotes: 3
Views: 57
Reputation: 12201
You should create path
outside nacitanie_Click
:
class SomeClass
{
private string path;
.....
private void nacitanie_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Otvoriť Textový súbor.";
dialog.Filter = "TXT files|*.txt";
dialog.InitialDirectory = @"C:\";
if (dialog.ShowDialog() == DialogResult.OK)
{
path = dialog.FileName;
}
}
....
}
and the use it in another methods/handlers.
Upvotes: 1
Reputation: 53700
You need to declare a variable outside of the button handler method:
private string path = string.Empty;
private void nacitanie_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Otvoriť Textový súbor.";
dialog.Filter = "TXT files|*.txt";
dialog.InitialDirectory = @"C:\";
if (dialog.ShowDialog() == DialogResult.OK)
{
path = dialog.FileName;
}
}
That way, you'll be able to access the variable from other button handlers.
Upvotes: 0