开发者

C# in Visual Studio: How to display a list in a DataGridView? Getting weird stuff

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 displayin开发者_JAVA百科g. 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!


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.


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜