Solved

C# DataGridView export to a text file

Posted on 2008-10-23
1
5,751 Views
Last Modified: 2010-10-05
Hi im just brand new here and already im highly impressed with the site.

Just a simple question (hopefully), i am trying to do something exactly the same as shown here http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_23263374.html?sfQueryTermInfo=1+c+datagridview+export

But my DataGridView is made up of all text. So how would i modify this function to work accordingly?

And then how would i call it?   ExportGridData(List<string>);     ???


I have included the code snipits used to populate the datagridview if that heklps explain what i am trying to do.

Basically i want to export the data once modified to comma separated file.
private void ImportCSV()

{

    List<string[]> testParse =

          parseCSV(txtInputPath.Text);

    

    DataTable newTable = new DataTable();

            foreach (string column in testParse[0])

            {

                newTable.Columns.Add();

            }

  

    foreach (string[] row in testParse)

    {

        newTable.Rows.Add(row);

    }

        DataGrid.DataSource = newTable;

}
 

public List<string[]> parseCSV(string path)

        {

            List<string[]> parsedData = new List<string[]>();

            using (StreamReader readFile = new StreamReader(path))

            {

                string line;

                string[] row;
 

                while ((line = readFile.ReadLine()) != null)

                {

                    row = line.Split(',');

                    parsedData.Add(row);

                }

            }
 

            return parsedData;
 

        }

Open in new window

0
Comment
Question by:A_Kardas
1 Comment
 
LVL 18

Accepted Solution

by:
Priest04 earned 50 total points
ID: 22798816
The code should work fine with your datagridview. What confuses you is the parameter List<int>. As I understood at a quick view at code, its an array of RowIndeces that you want to avoid exporting to txt file. for example, if your datagridview contains 10 rows, and you want to avoid exporting rows with index 2, 4 and 7, then you would do this

List<int> list = new List<int>();
list.Add(2);
list.Add(4);
list.Add(7);

// and then call the function
ExportGridData(list);

What I dont like about this function is that it is hardcoded to a particular datagridview name. DataGRidView should be passed as a parameter to this function, so I would rewrite it in the bellow way

to call the function
ExportGridData(MyDataGridView, null, @"C:\test.txt");
private void ExportGridData(DataGridView dgv, List<int> omitIndices, string filePath)

{

    StreamWriter writer = new StreamWriter(filePath);

 

    if (dgv.Rows.Count > 0)

    {

        foreach (DataGridViewColumn col in dgv.Columns)

        {

            if (col.Index == dgv.Columns.Count - 1)

            {

                writer.WriteLine(col.HeaderText);

            }

            else

            {

                writer.Write(string.Concat(col.HeaderText, ","));

            }

        }

 

        foreach (DataGridViewRow row in dgv.Rows)

        {

            if (omitIndices == null || !omitIndices.Contains(row.Index))

            {

                foreach (DataGridViewCell cell in row.Cells)

                {

                    if (cell.OwningColumn.Index == dgv.Columns.Count - 1)

                    {

                        if (cell.Value != null)

                            writer.WriteLine(cell.Value.ToString());

                        else

                            writer.WriteLine("");

                    }

                    else

                    {

                        if (cell.Value != null)

                            writer.Write(string.Concat(cell.Value.ToString(), ","));

                        else

                            writer.Write(string.Concat("", ","));

                    }

                }

            }

        }

    }

 

    writer.Close();

}

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to LOAD up a .NET Framework website with data? 2 40
Memory Usage 2 50
c# string handling 1 27
Angular JS Route 3 47
Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now