none
Export data from txt file to datagridview RRS feed

Answers

  • Hi Andrianna,

    You need one more thing ... since you are attempting to add a DataRow when you're reading from the File, you'll need to actually set the gridSource.DataSource to a DataTable that has those columns defined already. Something like this:

     public void readfile()
     {
    
         int counter = 0;
         string line;
         System.IO.StreamReader file =
             new System.IO.StreamReader(@"C:\Users\tsoum\source\repos\final_project_1\final_project_1\bin\Debug\contacts.txt");
             
         // You may want to put this new part elsewhere, like maybe in the constructor
         DataTable dtTest = new DataTable();
         dtTest.Columns.Add("Name");
         dtTest.Columns.Add("Surname");
         dtTest.Columns.Add("PhoneNumber");while ((line = file.ReadLine()) != null)
         dtTest.Columns.Add("Email");{
         dtTest.Columns.Add("DateOfBirth"); // you might want to make this a DateTime
         gridSource.DataSource = dtTest;
         // -------------------
    
         DataRow dr = (DataRow)((DataRowView)gridSource.AddNew()).Row;
         dr["Name"] = line.Split(' ')[0];
         dr["Surname"] = line.Split(' ')[1];
         dr["PhoneNumber"] = line.Split(' ')[2];
         dr["Email"] = line.Split(' ')[3];
         dr["DateOfBirth"] = line.Split(' ')[4];
    
         counter++;
         }
         file.Close();
    
     }
    


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    • Marked as answer by AndriannaTs Wednesday, May 29, 2019 8:11 AM
    Tuesday, May 21, 2019 12:47 AM

All replies

  • The first Google link gives the answer from Kareninstructor at :

    Trying to read from text file and put into a dataGridView

    Monday, May 13, 2019 3:56 PM
  • Hi AndriannaTs,

    Here is a simple demo that export data from txt to DataGridView you can refer to:

        private void btExport_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            string line;
            System.IO.StreamReader file =
                new System.IO.StreamReader(@"d:\test.txt");
            while ((line = file.ReadLine()) != null)
            {
                int index = this.dataGridView1.Rows.Add();
                this.dataGridView1.Rows[index].Cells[0].Value = line.Split(',')[0];
                this.dataGridView1.Rows[index].Cells[1].Value = line.Split(',')[1];
            }
            file.Close();
        }

    The txt file:

    1, Bob
    2, Kyle
    3, Lily

    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.

    Tuesday, May 14, 2019 1:55 AM
    Moderator
  • Thank you, it was very helpful to understand how it works but it appears a message Exception Unhandled: System.InvalidOperationException: 'Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.' . How can I solve this problem?
    Tuesday, May 14, 2019 12:10 PM
  • Hi AndriannaTs,

    Please check if you have used a datatable as the DataGridView's data source. If so, please refer to the following code.

        // Use a datatable as data source
        using (SqlConnection conn = new SqlConnection("connection string"))
        {
            SqlDataAdapter sda = new SqlDataAdapter("Select * From Stu", conn);
            DataSet Ds = new DataSet();
            sda.Fill(Ds, "T_Class");
            this.dataGridView1.DataSource = Ds.Tables["T_Class"];
            dt = Ds.Tables["T_Class"];
        }
    
    
        string line;
        System.IO.StreamReader file =
            new System.IO.StreamReader(@"d:\test.txt");
        while ((line = file.ReadLine()) != null)
        {
            DataRow dr = dt.NewRow();
            dr["Id"] = line.Split(',')[0];
            dr["Name"] = line.Split(',')[1];
            dt.Rows.Add(dr);
        }
        file.Close();

    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 15, 2019 1:28 AM
    Moderator
  • Is this the only way? I have use Binding Source to encapsulate my data from datagridview.I would not prefer to use SQL. How can I continue with it?
    Wednesday, May 15, 2019 7:05 PM
  • Hi AndriannaTs,

    In the case of using "Binding Source", you can refer to the following code.

        private void btExport_Click(object sender, EventArgs e)
        {
            string line;
            System.IO.StreamReader file =
                new System.IO.StreamReader(@"d:\test.txt");
            while ((line = file.ReadLine()) != null)
            {
                DataRow dr = (DataRow)((DataRowView)stuBindingSource.AddNew()).Row;
                dr["Id"] = line.Split(',')[0];
                dr["Name"] = line.Split(',')[1];
            }
            file.Close();
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'testDataSet1.Stu' table. You can move, or remove it, as needed.
            this.stuTableAdapter.Fill(this.testDataSet1.Stu);
        }

    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 16, 2019 2:07 AM
    Moderator
  • Hi Andrianna,

    Can you show us your code: the code you used to setup your BindingSource and DataSource for your DatGridView?


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, May 19, 2019 1:29 AM
  • Hello,

    The following code sample (on Microsoft OneDrive) was created in VS2017, should work with VS2019 too.

    A comma delimited text file is presented in a DataTable using TextFieldParser class into a concrete class which is then converted to a DataTable. If you don't want a DataTable change the following 

    using System;
    using System.Collections.Generic;
    using System.Data;
    using Microsoft.VisualBasic.FileIO;
    
    namespace ImportTextFileIntoDataGridView.Classes
    {
        public class FileOperations
        {
            public DataTable ReadCustomers(string pFileName)
            {
                var customers = new List<Customers>();
    
                using (var parser = new TextFieldParser(pFileName))
                {
                    parser.Delimiters = new[] { "," };
    
                    while (true)
                    {
                        var line = parser.ReadFields();
    
                        if (line == null)
                        {
                            break;
                        }
    
                        customers.Add(new Customers()
                        {
                            Id = Convert.ToInt32(line[0]),
                            Company = line[1],
                            ContactName = line[2],
                            ContactTitle = line[3],
                            Country = line[4]
                        });
    
                    }
                }
      
                return customers.ToDataTable();
            }
        }
    }

    To

    using System;
    using System.Collections.Generic;
    using Microsoft.VisualBasic.FileIO;
    
    namespace ImportTextFileIntoDataGridView.Classes
    {
        public class FileOperations
        {
            public List<Customers> ReadCustomers(string pFileName)
            {
                var customers = new List<Customers>();
    
                using (var parser = new TextFieldParser(pFileName))
                {
                    parser.Delimiters = new[] { "," };
    
                    while (true)
                    {
                        var line = parser.ReadFields();
    
                        if (line == null)
                        {
                            break;
                        }
    
                        customers.Add(new Customers()
                        {
                            Id = Convert.ToInt32(line[0]),
                            Company = line[1],
                            ContactName = line[2],
                            ContactTitle = line[3],
                            Country = line[4]
                        });
    
                    }
                }
      
                return customers;
            }
        }
    }

    Then if using the class list rather than the DataTable replace the single button click event code with the following.

    if (_bsCustomersBindingSource.Current != null)
    {
        var row = ((Customers)_bsCustomersBindingSource.Current);
        MessageBox.Show($"Id: {row.Id} Company name: {row.Company}");
    }
    Ending comment, you could replace TextFieldParser code reading the lines one by one and using split to get at each field.


    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


    Sunday, May 19, 2019 4:53 PM
    Moderator
  •   Here is my code, it still doesn't work.

        public partial class Form2 : Form
        {

            BindingSource listSource = new BindingSource();
            BindingSource gridSource = new BindingSource();
            List<contacts> list = new List<contacts>();
            BindingSource bs = new BindingSource();

            public Form2()
            {
                InitializeComponent();

                this.AutoSize = true;
                this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
                listBox1.DataSource = listSource;
                dataGridView1.DataSource = gridSource;

            }

          

     public void readfile()
            {

                int counter = 0;
                string line;
                System.IO.StreamReader file =
                    new System.IO.StreamReader(@"C:\Users\tsoum\source\repos\final_project_1\final_project_1\bin\Debug\contacts.txt");
                while ((line = file.ReadLine()) != null)
                {
                    DataRow dr = (DataRow)((DataRowView)gridSource.AddNew()).Row;
                    dr["Name"] = line.Split(' ')[0];
                    dr["Surname"] = line.Split(' ')[1];
                    dr["PhoneNumber"] = line.Split(' ')[2];
                    dr["Email"] = line.Split(' ')[3];
                    dr["DateOfBirth"] = line.Split(' ')[4];

                    counter++;
                }
                file.Close();

            }

     private void button6_Click(object sender, EventArgs e)
            {
                readfile();
            }

            
    Monday, May 20, 2019 10:56 AM
  • Hi Andrianna,

    You need one more thing ... since you are attempting to add a DataRow when you're reading from the File, you'll need to actually set the gridSource.DataSource to a DataTable that has those columns defined already. Something like this:

     public void readfile()
     {
    
         int counter = 0;
         string line;
         System.IO.StreamReader file =
             new System.IO.StreamReader(@"C:\Users\tsoum\source\repos\final_project_1\final_project_1\bin\Debug\contacts.txt");
             
         // You may want to put this new part elsewhere, like maybe in the constructor
         DataTable dtTest = new DataTable();
         dtTest.Columns.Add("Name");
         dtTest.Columns.Add("Surname");
         dtTest.Columns.Add("PhoneNumber");while ((line = file.ReadLine()) != null)
         dtTest.Columns.Add("Email");{
         dtTest.Columns.Add("DateOfBirth"); // you might want to make this a DateTime
         gridSource.DataSource = dtTest;
         // -------------------
    
         DataRow dr = (DataRow)((DataRowView)gridSource.AddNew()).Row;
         dr["Name"] = line.Split(' ')[0];
         dr["Surname"] = line.Split(' ')[1];
         dr["PhoneNumber"] = line.Split(' ')[2];
         dr["Email"] = line.Split(' ')[3];
         dr["DateOfBirth"] = line.Split(' ')[4];
    
         counter++;
         }
         file.Close();
    
     }
    


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    • Marked as answer by AndriannaTs Wednesday, May 29, 2019 8:11 AM
    Tuesday, May 21, 2019 12:47 AM
  • Thank you very much. It was really helpful to understand my mistake. Thank you for your time.
    Wednesday, May 29, 2019 8:11 AM
  • You're welcome, Andrianna! Glad I could help!  =0)

    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Wednesday, May 29, 2019 1:59 PM