Hey guys,
In my current project I can open and display a CSV file in a datagridview with the option to edit and save the file.
I am trying to create a button in the GUI that will convert the displayed CSV file into XML format with also the option to save it in the desired format.
Im super new to this and im not really sure were to start, so any help hints or feedback would be much appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnOpen_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
txtfilepath.Text = openFileDialog1.FileName;
BindDataCSV(txtfilepath.Text);
}
private void BindDataCSV(string filePath)
{
string[] lines = System.IO.File.ReadAllLines(filePath);
DataTable dt = GetDataTable(lines);
if (dt.Rows.Count > 0)
{
dataGridView1.DataSource = dt;
}
}
public DataTable GetDataTable(string[] lines)
{
DataTable dt = new DataTable();
if (lines.Length > 0)
{
string firstline = lines[0];
string[] headerLabels = firstline.Split(',');
foreach (string headerWord in headerLabels)
{
dt.Columns.Add(new DataColumn(headerWord));
}
for (int r = 1; r < lines.Length; r++)
{
string[] dataWords = lines[r].Split(',');
DataRow dr = dt.NewRow();
int columnIndex = 0;
foreach (string headerWord in headerLabels)
{
dr[headerWord] = dataWords[columnIndex++];
}
dt.Rows.Add(dr);
}
}
return dt;
}
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "|*.csv";
saveFileDialog1.Title = "Save CSV File";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
using (StreamWriter sw = new StreamWriter(saveFileDialog1.FileName))
{
WriteDataTable(dataGridView1.DataSource as DataTable, sw, true);
}
}
}
public static void WriteDataTable(DataTable sourceTable, TextWriter writer, bool includeHeaders)
{
if (includeHeaders)
{
List<string> headerValues = new List<string>();
foreach (DataColumn column in sourceTable.Columns)
{
headerValues.Add(QuoteValue(column.ColumnName));
}
writer.WriteLine(String.Join(",", headerValues.ToArray()));
}
string[] items = null;
foreach (DataRow row in sourceTable.Rows)
{
items = row.ItemArray.Select(o => QuoteValue(o.ToString())).ToArray();
writer.WriteLine(String.Join(",", items));
}
writer.Flush();
}
private static string QuoteValue(string value)
{
return String.Concat("\"", value.Replace("\"", "\"\""), "\"");
}
private void XML1_Click(object sender, EventArgs e)
{
}
}
}
What I have tried:
I have tried other methods but I cant seem to figure out were to start with converting the loaded file.