-3

I am trying to do a 'save file' browser. I want the selected Filename input by user to be displayed in a label instead of a textbox. I did a similar one for my 'open file' browser and it worked well. Please show me where I went wrong, thanks!

private void button5_Click(object sender, EventArgs e)
    {
        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        saveFileDialog1.Title = "Save File";
        saveFileDialog1.Filter = "Text files (*.txt)|*.txt| CONF(*.conf)|*.conf|All files (*.*)|*.*";
        saveFileDialog1.FilterIndex = 1;
        saveFileDialog1.ShowDialog();

        if (saveFileDialog1.FileName != "")
        {
            System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();

            switch (saveFileDialog1.FilterIndex)
            {
                case 1:
                    saveFileDialog1.FileName = saveFileDialog1.FileName + ".txt";
                    break;
                case 2:
                    saveFileDialog1.FileName = saveFileDialog1.FileName + ".conf";
                    break;
            }

            fs.Close();
        }
    }

private void label2_Click(object sender, EventArgs e)
    {
        this.label2.Text = saveFileDialog1.FileName;
    }
Firzanah
  • 43
  • 2
  • 12
  • 3
    You are trying to set your label's value by clicking on it? – SᴇM Sep 22 '17 at 10:05
  • shouldn't you write `this.label2.Text = saveFileDialog1.FileName;` in `button5_Click` ? – Chetan Sep 22 '17 at 10:37
  • `FileName` returns full path with extension, do you add *another* extension on purpose? E.g. if `1.txt` was chosen you want to use `1.txt.txt` file, right? As for the problem, you can't access local variable in another method. Make it a `private` field for this. Though I agree with @ChetanRanpariya, more likely you want to set label text in button click event handler. – Sinatr Sep 22 '17 at 11:52

1 Answers1

0

The bottom three lines of code shows what happens when label2 is clicked. So what you have done for updating the label is correct which is : this.label2.Text = saveFileDialog1.FileName; . The problem is when you are updating this label, with your code you have made it so after user clicks on the label your updating the label text.

Easiest thing to do is double click the item in design view and it will automatically take you to the code which fires up when clicking that item when the program is running.

So for example you have a button in designer view, if you double click on that in designer view in VS it will jump to code block which is the code block that will run when the button is clicked.

Tantrix1
  • 73
  • 11