Click here to Skip to main content
15,889,876 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
C#
mmuSaveAs_Click
and

My Settings form containing the data grid view.

C#
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;
            //Populate_grid_View_with_dummy_data();
        }

        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.

C#
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)
        {     
            //READ
            if (_dt == null)
            {
                 populateControlWithCSVData(filePath);
            }            

            //WRITE
            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))//I'm using this guy's class. http://www.blackbeltcoder.com/Articles/files/reading-and-writing-csv-files-in-c
                {
                    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))//I'm using this guy's class. http://www.blackbeltcoder.com/Articles/files/reading-and-writing-csv-files-in-c
            {
                _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.
Posted
Updated 4-May-19 21:19pm
Comments
Christian Graus 5-May-19 2:25am    
Why on earth are people using ASP.NET?

1 solution

You fill your control from a data source. If the data isn't changed, why not work with the source, not the control?
 
Share this answer
 
Comments
Jordan Nash 5-May-19 6:29am    
Because I want to map all the values in the "Data" column to rename a bunch of filenames in a drag drop box form. The values would would be written to all of the files. I wanted to have the user create csv files at the touch of a button and read their contents to the gridview and print it to the filename. The Description header is just a meta data column should they be creating several files and forget what all the data is for.

Is there something wrong with my approach there and if so how can I optimise it?
Christian Graus 5-May-19 18:19pm    
I'll be honest, I am confused as to where you're stuck.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900