Loz
Loz

Reputation: 41

Adding a Save As Function to a form using a listbox store of data

I am creating a Times table form in Visual Studio Express 2014 in C#.

I have created the whole form, it works to a full extent, even saving to a text file, however i wish to add a Savedialog in order for the user to choose where to save the file just like saving in word, etc.

Ive tried using File.WriteAllText(name, "test"); or variations of this however this does not work with a listbox

In my code the listbox is called results, here is my save button code what i have tried so far:

private void save_Click(object sender, EventArgs e)
{
    const string Path = "C:\\Users\\Loan\\save.txt";
    System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(Path);
    foreach (var item in results.Items)
    {
        SaveFile.WriteLine(item.ToString());
    }
    SaveFile.Close();

    MessageBox.Show("Programs saved!");

}

it works perfectly fine, however as i have aforementioned that

i wish to create a save as function for the user to browse where to save.

The form = http://gyazo.com/227d2aada349586cef60f2962456a71c

The full code = http://pastebin.com/7DwLpkhP

Upvotes: 0

Views: 76

Answers (1)

crthompson
crthompson

Reputation: 15875

Use the `Save file dialog' class

using (SaveFileDialog dialog = new SaveFileDialog())
{
    dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"  ;
    dialog.FilterIndex = 2 ;
    dialog.RestoreDirectory = true ;

    if (dialog.ShowDialog() == DialogResult.OK)
    {
        // Can use dialog.FileName
        string Path = dialog.FileName;
       ....

Upvotes: 1

Related Questions