views:

46

answers:

2

Hi Everybody -

Been a while and I've volunteered to teach myself Windows programming at my company. Started writing vbs scripts and suddenly realized how incredibly useful this programming thing is ;-)

Anyway, I'm a total newbie at C# AND Visual Studio, I kind of get how it works, you drag and drop interface pieces in the design side then wire them together in the back/program side.

I'm trying to write a program that will (ultimately) read in a (very specific kind of) csv file and give the user a friendlier way to edit and sort through it than Excel. Should be simple stuff, and I'm excited about it.

I started this morning and, with the help of the internet, got as far as reading in and parsing the CSV (which is actually a TSV, since they use tabs not commas but hey).

I've been trying to figure out the best way to display the information, and, for now at least, I'm using a DataGridView. But the data isn't displaying. Instead, I'm seeing a long grid of values with column headers of Length, LongLength, Rank, SyncRoot, IsReadOnly, IsFixedSize, and IsSynchronized.

I don't know what any of these mean or where they come from, and unfortunately I don't know how change them either. Maybe somebody can help?

Here is my code:

using System;

using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO;

namespace readInCSV { public partial class readInCSV : Form { public readInCSV() { InitializeComponent(); }

    public List<string[]> parseCSV(string path)
    {
        List<string[]> parsedData = new List<string[]>();
        try
        {
            using (StreamReader readfile = new StreamReader(path))
            {
                string line;
                string[] row;
                while ((line = readfile.ReadLine()) != null)
                {
                    row = line.Split('\t');
                    parsedData.Add(row);
                }
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }

        return parsedData;
    }

    //PRIVATE METHODS FROM HERE ON DOWN

    private void btnLoadIn_Click(object sender, EventArgs e)
    {
        int size = -1;
        DialogResult csvResult = openCSVDialog.ShowDialog();

        if (csvResult == DialogResult.OK)
        {
            string file = openCSVDialog.FileName;
            try
            {
                string text = File.ReadAllText(file);
                size = text.Length;
            }
            catch (IOException)
            {
            }
        }
        dgView.Dock = DockStyle.Top;
        dgView.EditMode = DataGridViewEditMode.EditOnEnter;
        dgView.AutoGenerateColumns = true;
        dgView.DataSource = parseCSV(openCSVDialog.FileName);
    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void openCSVDialog_FileOk(object sender, CancelEventArgs e)
    {

    }
}

}

Thanks in advance!

+3  A: 

The DataGridView tries to display the Properties of your string-Array. You should set AutoGenerateColumns = false and create the columns by yourself.

Would the first line of the CSV/TSV contain the column names? Is so, you shouldn't pass them as DataSource.

dgView.AutoGenerateColumns = false;
foreach(string name in columnNames)
{
    dgView.Columns.Add(name, name);
}
Hinek
Sorry! for some reason this didn't work. The program doesn't understand what "columnNames" is. Thanks for helping though!
StormShadow
Yes, you have to declare columnNames ... as I said, you shouldn't pass the names of your columns in the DataSource. Put them in an string-Array or -List and name it columnNames (eg. string[] columnNames or List<string> columnNames).
Hinek
+2  A: 

What's happening here is that the DataGridView is trying to display all the information for each of the string arrays in your parsedData List.

When you set a DataGridView's DataSource as a List of objects, it attempts to interpret each of the objects as a row to display. parsedData is a List of string array objects, so the grid is showing you all the displayable properties for an array object.

What we can do is parse each TSV row into a custom class (call it TsvRow) which has all the relevant data exposed. The TsvRow objects are then placed in a List and passed to the DataGridView. An example of this approach is explained in this article.

For example:

public class TsvRow
{
    // Properties to hold column data
    public string Column1 { get; set; }
    public string Column2 { get; set; }
}

...

public List<TsvRow> parseCSV(string path)
{
    List<TsvRow> parsedData = new List<TsvRow>();

    try
    {
        using (StreamReader readfile = new StreamReader(path))
        {
            string line;
            string[] row;

            while ((line = readfile.ReadLine()) != null)
            {
                row = line.Split('\t');

                // Here we assume we know the order of the columns in the TSV
                // And we populate the object
                TsvRow tsvRow = new TsvRow();
                tsvRow.Column1 = row[0];
                tsvRow.Column2 = row[1];

                parsedData.Add(myObject);
            }
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }

    return parsedData;
}

Since all your column data is exposed as properties (i.e. "Column1" and "Column2"), they should be reflected in the DataGridView automatically.

Hope that helps! Please let me know if this needs clarification.

TeeBasins
This is great. The DataGridView is now quite happily displaying the first two columns of the csv. So I imagine that all I would have to do to display all of them is repeat the process out for all columns, right?One of the things I don't quite understand is what you're doing with the lines that say "public string xxx { get; set; }"Are you creating default getter and setter methods for the strings? And if so, this means that they are not really strings, but properties of the TsvRow class, right?
StormShadow
Glad it worked for you! Yep, you can repeat the process for as many columns as you need. You're absolutely right, the "get; set;" piece of code is a C# property (http://msdn.microsoft.com/en-us/library/x9fsa0sw(VS.80).aspx for extra info) which is the C# equivalent of having get and set methods for a class variable. In this case, "string" is the type of object we're getting/setting. The "get; set;" nomenclature is just a shortcut :)
TeeBasins