I am trying to get the string text out of a data grid view and store it in a data table so i can save the data table to a csv file. I have got 2 unbound columns that I have been able to read data to in the csv file. One is Description. The other is Data. Problem is when I debug I notice the datatable stays null no matter what I do. I've tried everything.
Does anyone know how I can fix it? I have a mutator method called ProcessSettingFileCMD and I realize I am overiding the data table with it so it will never get actual grid view rows or null data. You want to see
mmuSaveAs_Click
and
My Settings form containing the data grid view.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
public partial class frmSettings : Form
{
#region Declarations
protected string FileName;
protected bool Modified;
Setting _objSetting = new Setting();
OpenFileDialog openFD = new OpenFileDialog();
SaveFileDialog saveFD = new SaveFileDialog();
DataTable _dt = new DataTable();
#endregion
#region Initializers
public frmSettings()
{
InitializeComponent();
lblMessage.Text = "Please create or open a setting file.";
gvSettings.DataSource = _dt;
}
private void Populate_grid_View_with_dummy_data()
{
string[] row0 = {"Address", "76 Douglas St Wakecorn"};
string[] row1 = {"Property name", "Wakecorn University"};
string[] row2 = {"Building", "C Block"};
string[] row3 = { "Room", "C2.18"};
gvSettings.Rows.Add(row0);
gvSettings.Rows.Add(row1);
gvSettings.Rows.Add(row2);
gvSettings.Rows.Add(row3);
}
#endregion
#region Buttons
private void mnuQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnClose_Click(object sender, EventArgs e)
{
if (SaveIfModified())
Close();
}
#endregion Buttons
#region File menu strip actions
private void mmuSaveAs_Click(object sender, EventArgs e)
{
Cursor = Cursors.WaitCursor;
saveFD.FileName = FileName;
try
{
saveFD.Title = "Save a CSV File as desired.";
saveFD.Filter = "CSV|*.csv";
saveFD.FileName = "default";
txtFilePath.Text = openFD.FileName;
if (saveFD.ShowDialog(this) == DialogResult.OK)
_dt = _objSetting.ProcessSettingFileCMD(saveFD.FileName);
}
catch (Exception ex)
{
Debug.WriteLine(String.Format("Error writing to {0}.\r\n\r\n{1}", FileName, ex.Message));
}
finally
{
Cursor = Cursors.Default;
}
}
My Settings class where the data table is passed back and forth through to the CRUD methods.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using CsvFile;
using System.Diagnostics;
public class Setting
{
#region Variables
private int[] _intArrRow;
private int _intCsvRow = 4;
private DataTable _dt;
DataColumn _dclColumnDescription = new DataColumn("Description", typeof(string));
DataColumn _dclColumnData = new DataColumn("Data", typeof(string));
#endregion
#region Mutator Methods
public DataTable ProcessSettingFileCMD(string filePath)
{
if (_dt == null)
{
populateControlWithCSVData(filePath);
}
else if (_dt != null)
{
if (_dt.Rows.Count > 0)
{
WriteFile(filePath);
}
}
return _dt;
}
#endregion
#region CRUD Methods
private int GetTotalColumnsInTable()
{
int maxColumn = 0;
foreach (DataRow row in _dt.Rows)
{
if (_dt.Columns.Contains("{0}") || _dt.Columns.Contains("{1}"))
{
for(int col = row.ItemArray.Length -1; col >= 0; col--)
{
if(row.ItemArray.GetValue(col) != null)
{
if (maxColumn < (col + 1))
maxColumn = (col + 1);
continue;
}
}
}
}
return maxColumn;
}
private void WriteFile(string filename)
{
int numColumns = GetTotalColumnsInTable();
using (var writer = new CsvFileWriter(filename))
{
foreach (DataRow row in _dt.Rows)
{
if (row != _dt.Rows[0])
{
List<string> columns = new List<string>();
for (int col = 0; col < numColumns; col++)
columns.Add((string)row.ItemArray.GetValue(col) ?? String.Empty);
writer.WriteRow(columns);
}
}
}
}
private void populateControlWithCSVData(string filePath)
{
_dt = new DataTable();
List<string> columns = new List<string>();
using (var reader = new CsvFileReader(filePath))
{
_dt.Columns.Add(_dclColumnDescription);
_dt.Columns.Add(_dclColumnData);
while (reader.ReadRow(columns))
{
_dt.Rows.Add(columns.ToArray());
}
}
}
#endregion
}
What I have tried:
I'm using this guy's library and project
http://www.blackbeltcoder.com/Articles/files/reading-and-writing-csv-files-in-c#. I'm trying to abstract it and integrate it into mine because I need the data table globally accessible for the application. It was easy with reading data from csv as I am only really refactoring the code but now that I am trying to write to a csv, it's getting messy.