0

How can I pass file directory between two button click method?

  1. I'm selecting csv file and put the CSV name to TextBox

    private void Button_Click(object sender, RoutedEventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "CSV|*.csv"; ofd.ShowDialog(); csvName.Text = ofd.SafeFileName; } 
  2. Second button should start reading CSV file selected into first step

    private void Button_Click_1(object sender, RoutedEventArgs e) { //string path = ; StreamReader srd = new StreamReader(); } 
6
  • Create a form level variable and store the directory path in it in button1 click and use it in button2 click. Commented Dec 6, 2017 at 8:35
  • Sidenote: Don't do (synchronous) file I/O on the GUI thread. It will make your App appear unresponsive. Commented Dec 6, 2017 at 8:55
  • 1
    Read up on MVVM. Doing "button_Click" on WPF is painful to see because it's painful to program. You are resisting WPF if you go against it's design patterns. Commented Dec 6, 2017 at 8:56
  • To add to nvoigt's comment. The MVVM-alternative would be using Commands. Commented Dec 6, 2017 at 8:57
  • thanks, but I need to do it in very simple way Commented Dec 6, 2017 at 9:02

2 Answers 2

1

csvName.Text = ofd.SafeFileName; SafeFileName doesn't return the full path it just returns the filename, which is not enough for the button(Button_Click_1) the start reading . Instead use ofd.FileName; this give the complete path. Assuming csvName as TextBox.

declare global variable

public string FullFileName{get;set;} private void Button_Click(object sender, RoutedEventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "CSV|*.csv"; ofd.ShowDialog(); csvName.Text = ofd.SafeFileName; 

FullFileName=ofd.FileName; }

private void Button_Click_1(object sender, RoutedEventArgs e) { using(var reader = new StreamReader(FullFileName)) { // do your action here } } 
Sign up to request clarification or add additional context in comments.

2 Comments

that's correct, but I want to display just file name inside the TextBox
add a global variable to hold to file full path and use it . modified the code check it
0

you can read the text of csvName in the button2_click event.

string path = csvName.Text;

or you can use a variable to save the value of the textbox and use that too.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.