Solved

C# DataGridView export to a text file

Posted on 2008-10-23
1
5,795 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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
SQL Exceptions 3 46
MediaHelp 4 23
Switching Visual Studio 2015 to normal debug display 3 28
How to make a Gridview column hidden (visibility false) in the HTML code? 2 16
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

803 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