none
How to save data from DataGridView RRS feed

  • Question


  • I have to make an agenda of contacts. I had saved my data in a DataGridView and I want to save my data from DataGridView in a txt file. Is it better to send them in a listBox first or to save them directly from DataGridView? I tried to send them in a listBox but there is not empty space between the context of textboxes. For example,I have the name: Andrianna,surname:Ts,phonenumber:12345678 and date of birth:15/07/2020 and the result in the txt file is AndriannaTs1234567815/07/2020 instead of  Andrianna Ts 12345678 15/07/2020. I tried also to put " " but it doesn't work.  How can I solve it?

    This is the code that I used:

    private void button4_Click(object sender, EventArgs e)
            {
                SaveFileDialog dlg = new SaveFileDialog();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    StreamWriter writer = new StreamWriter(dlg.FileName);

                    for (int i = 0; i < listBox1.Items.Count; i++)
                    {
                        writer.WriteLine((string)listBox1.Items[i]);
                    }
                    writer.Close();
                }
                dlg.Dispose();
            }

    Thank you in advance.

    Wednesday, May 8, 2019 6:48 AM

Answers

  • Hello,

    The following may appear to be a) overkill b) to complex but I would recommend trying it out. The benefits of this language extension method is it will work on any DataGridView where data is set without or with a DataSource, skips a new row if present, turns null values to an empty string.

    Add a new class to your project named DataGridViewExtensions.cs, copy the code below into the class followed by changing the namespace from WindowsFormsApp1 to your namespace of the project (it will be in your current form at the top too).

    using System;
    using System.Linq;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public static class DataGridViewExtensions
        {
            /// <summary>
            /// Creates a string array which represents each row in the DataGridView, skips
            /// a new row if present. Any cell values which are null are set to an empty string
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="delimiter">Optional column separator used to separate columns </param>
            /// <returns></returns>
            public static string[] CreateRowsArray(this DataGridView sender, string delimiter = ",")
            {
                return (
                    sender.Rows.Cast<DataGridViewRow>()
                        .Where(row => !row.IsNewRow)
                        .Select(row => new {row, RowItem = string.Join(delimiter, Array.ConvertAll(row
                            .Cells.Cast<DataGridViewCell>().ToArray(), cell => ((cell.Value == null) ? "" : cell.Value.ToString())))})
                        .Select(@t => @t.RowItem)).ToArray();
            }
        }
    }

    In the form with a button click event.

    using System;
    using System.IO;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void exportDataGridViewRowsToFileButton_Click(object sender, EventArgs e)
            {
                var dlg = new SaveFileDialog();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllLines(dlg.FileName, dataGridView1.CreateRowsArray());
                }
                
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by AndriannaTs Friday, May 10, 2019 8:50 PM
    Wednesday, May 8, 2019 9:36 AM
    Moderator

All replies

  • Hi AndriannaTs,

    To add the datagridview's items to listbox and separated by spaces, you can refer to the following code.

        string newitem = "";
    
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {
                if (dataGridView1.Rows[i].Cells[j].Value != null)
                {
                    if (j == 3)
                    {
                        newitem += ((DateTime)dataGridView1.Rows[i].Cells[j].Value).ToShortDateString() + " ";
                        continue;
                    }
                    newitem += dataGridView1.Rows[i].Cells[j].Value.ToString() + " ";
                }
            }
            listBox1.Items.Add(newitem);
            newitem = "";
        }

    After completing the addition of the item, you can use the code you wrote to create the txt file.

    Result:

    Regards,

    Kyle


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, May 8, 2019 7:17 AM
    Moderator
  • Hello,

    The following may appear to be a) overkill b) to complex but I would recommend trying it out. The benefits of this language extension method is it will work on any DataGridView where data is set without or with a DataSource, skips a new row if present, turns null values to an empty string.

    Add a new class to your project named DataGridViewExtensions.cs, copy the code below into the class followed by changing the namespace from WindowsFormsApp1 to your namespace of the project (it will be in your current form at the top too).

    using System;
    using System.Linq;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public static class DataGridViewExtensions
        {
            /// <summary>
            /// Creates a string array which represents each row in the DataGridView, skips
            /// a new row if present. Any cell values which are null are set to an empty string
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="delimiter">Optional column separator used to separate columns </param>
            /// <returns></returns>
            public static string[] CreateRowsArray(this DataGridView sender, string delimiter = ",")
            {
                return (
                    sender.Rows.Cast<DataGridViewRow>()
                        .Where(row => !row.IsNewRow)
                        .Select(row => new {row, RowItem = string.Join(delimiter, Array.ConvertAll(row
                            .Cells.Cast<DataGridViewCell>().ToArray(), cell => ((cell.Value == null) ? "" : cell.Value.ToString())))})
                        .Select(@t => @t.RowItem)).ToArray();
            }
        }
    }

    In the form with a button click event.

    using System;
    using System.IO;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void exportDataGridViewRowsToFileButton_Click(object sender, EventArgs e)
            {
                var dlg = new SaveFileDialog();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllLines(dlg.FileName, dataGridView1.CreateRowsArray());
                }
                
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by AndriannaTs Friday, May 10, 2019 8:50 PM
    Wednesday, May 8, 2019 9:36 AM
    Moderator
  • I did it and it appears the message :

    "exception unhandled" 

    System.InvalidCastException: 'Specified cast is not valid.'

    Wednesday, May 8, 2019 11:45 AM
  • Hi AndriannaTs,

    In my data table, I set the data type of birth to "DATE", so I need to convert it to the "DateTime" type to get the date. The T-SQL is shown as follows:

    CREATE TABLE [dbo].[Contacts ] (
        [name]    NVARCHAR (50) NOT NULL,
        [surname] NVARCHAR (50) NULL,
        [phone]   NVARCHAR (50) NULL,
        [birth]   DATE          NULL,
        PRIMARY KEY CLUSTERED ([name] ASC)
    );

    If you set the data type of birth to "NVARCHAR", then you can omit the following code:

        if (j == 3)
        {
            newitem += ((DateTime)dataGridView1.Rows[i].Cells[j].Value).ToShortDateString() + " ";
            continue;
        }

    Regards,

    Kyle


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, May 9, 2019 1:29 AM
    Moderator