简体   繁体   中英

Exporting winform data to .txt file

I have a winform with two data grids, and multiple text boxes. I want to give the user the option to export this data to a text document in a location of their choice on their drive. I also want the text document to be pre-formatted, and the values from the text boxes and datagrids to be plugged in.

Is it possible to pre-format a txt document using StreamWriter? And how to I go about giving the user the option of where to save this exported file?

You will have to format the string you want to write throught the StreamWriter.

using(StreamWriter sw = new StreamWriter(filePath)) {
    string firstLine = string.Concat("\n", string.Format(@"Customer number: {0}, Customer name: {1}", textBox1.Text, textBox2.Text));
    string secondLine = string.Format(@"Address: {0}", textBox3.Text);

    sw.WriteLine(firstLine);
    sw.WriteLine(secondLine);

    // Loop through your DataGridView.Rows or Cells and do the same.

    sw.Flush();
    sw.Close();
}

Output to file

Customer number: [12345678] Customer name: [customer name]
Address: [address]

Where the information between square brackets is the information input by the user through the TextBoxes.

I'm not entirely sure what you mean by pre-format a text document. The StreamWriter can be used to write out in whatever format you specify the data. Its really going to come down to how you provide the data to the StreamWriter. For example if you want your grid rows to appear as csv's write each one out item, add a comma (except for the last element) and then after the last element write a new line, repeat for all rows. If I'm missing something please let me know.

As far as how to give the user the option of where to save you should use the SaveFileDialog control (it should be in your toolbox in Visual Studio). That will open the explorer view that will allow the user to select the location and name). See the linked documentation for details on how to actually use the class. It is fairly straight forward

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM