Click here to Skip to main content
15,346,335 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have already a working code in WinForm but I want to write back in WPF but I cannot do it because I am new in WPF. Can you guys try to convert it to WPF?

if (myGrid.RowCount > 0)
{
    string value = "";
    DataGridViewRow dr = new DataGridViewRow();
    StreamWriter sWriter = new StreamWriter(fileLocation);

    //write header rows to csv
    for (int i = 0; i <= myGrid.Columns.Count - 1; i++)
    {
        if (i > 0)
        {
            sWriter.Write(",");
        }
        sWriter.Write(myGrid.Columns[i].HeaderText);
    }
    sWriter.WriteLine();

    //write DataGridView rows to csv
    for (int j = 0; j <= myGrid.Rows.Count - 1; j++)
    {
        if (j > 0)
        {
            sWriter.WriteLine();
        }

        dr = myGrid.Rows[j];

        for (int i = 0; i <= myGrid.Columns.Count - 1; i++)
        {
            if (i > 0)
            {
                sWriter.Write(",");
            }

            value = dr.Cells[i].Value.ToString();
            //replace comma's with spaces
            value = value.Replace(',', ' ');
            //replace embedded newlines with spaces
            value = value.Replace(Environment.NewLine, " ");

            sWriter.Write(value);
        }
    }
    sWriter.Close();
    MessageBox.Show("Exported succesfully.");
}


What I have tried:

..............................................................
Posted
Updated 12-May-22 19:48pm

1 solution

Don't work from a DataGridView directly - use it's data source instead, which is often a DataTable loaded from a DB or file. That way, you separate the presentation details from the data storage and get more reusable code.

And you can then use standard packages which can load / save data to CSV for you (or switch to XML / JSON for a more "modern" human readable data store when you decide to upgrade).
I use this: CsvHelper[^]
   
v2

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