Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all articles
Browse latest Browse all 2535

How can I transfer data from data grid view to datatable?

$
0
0

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 what I might be doing wrong and how I can fix it? Could it be something is wrong in the data source. It's saying it's null in the debugger as well.

My Settings form containing the data grid view.

    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.

    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
        ///Methods. Note may have to use LINQ.

        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
	}

   



Viewing all articles
Browse latest Browse all 2535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>