Ganewt
Ganewt

Reputation: 19

Windows Forms input /save to FilePath issue using excel

I have a simple windows form with person details input.I am using a filepath to save entry (mydocuments/.csv file) My display on WF is a label

Issue: each entry I make is saved to csv/excel doc in one continous line and also on the label when i click "show data" I want each entry line to be seperated in label display Any help would be much appreciated ,new to this game. Thanks G My code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

 namespace StringFilePath
 {
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
   string FilePath = Environment.GetFolderPath      (Environment.SpecialFolder.MyDocuments) +    Path.DirectorySeparatorChar+ "mestring.csv";
    private void btnAdd_Click(object sender, EventArgs e)
    {
        int id = int.Parse(txtID.Text);
        string fname = TXTfNAME.Text;
        string lname = txtLname.Text;
        string phone = txtPhone.Text;
        string email = txtEmail.Text;


        StreamWriter sw = File.AppendText(FilePath);
        sw.Write(id + ",");
        sw.Write(fname + ",");
        sw.Write(lname + ",");
        sw.Write(phone + ",");
        sw.Write(email + ",");

        sw.Close();


        txtID.Clear();
        TXTfNAME.Clear();
        txtLname.Clear();
        txtPhone.Clear();
        txtEmail.Clear();

    }

    private void isplay_Click(object sender, EventArgs e)
    {
        string content = File.ReadAllText(FilePath);
        lblDisplay.Text = content;
    }

Upvotes: 0

Views: 31

Answers (1)

Steve
Steve

Reputation: 216333

You need to add an Environment.NewLine to your text. You can do that explicitly or just using sw.WriteLine on the last input

string line = $"{id},{fname},{lname},{phone},{email}";
using(StreamWriter sw = new StreamWriter(FilePath))
   sw.WriteLine(line);

Or more concise with

string line = $"{id},{fname},{lname},{phone},{email}{Environment.NewLine}";
File.AppendAllText(FilePath, line);

For the label you should be able to set simply its text with the data loaded from the file, but, of course, the label should have enough Height to show the lines loaded

Upvotes: 1

Related Questions