Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a simple windows form with a datagridview and one csv file with 4 rows, the first being the headers.
The csv file looks like this:

Name,Age,Phone,Street
Dan,23,888765,Street1
Daisy,40,556432,Street2
Jake,12,876324155,Street3

I have read the code to populate the DataGridView1 from csv, and my code looks like this:

C#
private DataSet ds = new DataSet();
private void button4_Click(object sender, EventArgs e)
        {
            ds = new DataSet();
            ds.Tables.Add();
            dataGridView1.DataSource = ds.Tables[0].DefaultView;
            //ds.AcceptChanges();

            String[] all_text = File.ReadAllText(@"c:\adataFile.csv").Split('\n');
            int count_row = 0;
            foreach (string row in all_text)
            {
                //MessageBox.Show(line);
                string[] data = row.Split(',');
                if (count_row == 0)
                {
                    foreach (string header in data)
                    {
                        ds.Tables[0].Columns.Add(header);
                    }
                }
                else
                {
                    ds.Tables[0].Rows.Add(data);
                }
                count_row++;
            }
        }


I have tried to add another button and add ds.AcceptChanges(); but this does not work.

I know that when getting the data from SQL table I use sqlcommandbuilder, but i cannt seem to find any builder for CSV.

Please tell me how to commit the changes made in the DataGrid back to the csv file.

Thank you.
Posted
Comments
ZurdoDev 8-May-14 16:36pm    
Just like you read the data in with ReadAllText, you'll need to write it out too. Use the File object as well.
Danut D 8-May-14 17:20pm    
can you be a little more specific, please?
ZurdoDev 8-May-14 17:36pm    
http://msdn.microsoft.com/en-us/library/system.io.file.aspx
Danut D 8-May-14 17:41pm    
All the methods there that are "writing" are creating a new file. I am sorry but I still cannot figure out what to do.
ZurdoDev 8-May-14 17:44pm    
Most only create a new file if one does not exist.
Do you understand the code you currently have? You basically just need to go the other way.

Loop through your DataGrid building up a string of values and then write it to a text file.

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