Basically I have a class
and a form
. In my class
, I wrote the variables per below. These variables are where I saved my data in my form
:
Save.cs
namespace CSV
{
public partial class Save
{
public static string people = string.Empty;
public static List<string> mileage_list = new List<string>();
}
}
Then in my form
, I made an event and called the event through FormClosed
. Edited: Each time I click button, textbox1
will clear and I can add in new values. All these values are being saved in the list
Form1.cs
public void Savetocsv()
{
Type s = typeof(Save);
FieldInfo[] fields = s.GetFields(BindingFlags.Public | BindingFlags.Static);
StringBuilder csvdata = new StringBuilder();
string header = String.Join("|", fields.Select(f => f.Name).ToArray());
csvdata.AppendLine(header);
string first = Save.people;
string newLine = string.Format("{0}", first);
csvdata.AppendLine(newLine);
string mileage = String.Join("|", Save.mileage_list.ToArray());
csvdata.AppendLine(mileage);
string filepath = @"C:\Vehicles.csv";
File.WriteAllText(filepath, csvdata.ToString());
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Save.people = Combobox1.SelectedItem.ToString();
Save.mileage_list.Add(Textbox1.Text);
Savetocsv();
}
private void button1_Click(object sender, EventArgs e)
{
Save.people = Combobox1.SelectedItem.ToString();
Save.mileage_list.Add(Textbox1.Text);
TBmileage.Text = "";
}
When I opened the Vehicles.csv file, the string from Save.people
was correct but the string from Save.mileage_list
was written as System.Collections.Generic.List1[System.String]. Hence, may I know how do I rewrite the code to export both the string values properly.
Edited
Previously, the values are wrong but exported in their respective headers. See Image 1. However, with this code, the values are correct but not exported in their respective headers. Image 2. I know I might need to do a Dictionary
or a for
loop but I do not know how.