views:

100

answers:

1

I have a function to which an array has a large sum of CSV imported split data. I currently have it set as the code below however I'm having some issues getting the data to go into the separate columns than into a single one. What I would like to achieve is a non-redundant means of supplying a function a string array of any size, and define how many columns across the data must be read before adding it as a row into the DataGrid.

    private string csvtogrid(string input, columns)
    {
        input = input.Replace("\r", ",").Substring(2).TrimEnd(',').Trim().Replace("\n", ",").Replace(",,,", ",").Replace(",,",",");
        string[] repack = input.Split(',');
        string[] cell = new string[columns];
        int rcell = 0;
        for (int counter = 1; counter < repack.Length; counter++)
        {
            if (rcell < columns)
            {
                cell[rcell] = repack[counter];
                rcell++;
            }
            //MessageBox.Show(cell[0] + cell[1] + cell[2]);
            procgrid.Rows.Add(cell[0], cell[1], cell[2]);
            rcell = 0;
        }
        return null;
    }
A: 

The most reliable and easy method i have ever found to read in csv files is the TextFieldParser class. It's in the Microsoft.VisualBasic.FileIO namespace so it is probably not referenced by defaukt if you use c# but it's should be in the gac foryou to reference.

Ben Robinson
Well, my trouble is actually not in terms of importing a CSV file, but that the data I'm retrieving is put into a CSV format and stored in a string. What I want to accomplish is to pass a string to a function and tell it how many columns a particular datagrid has. All the function would do is just fill the cells on the row then move to the next. For example, column names "fname, lname, address". If I tell the function that there's 3 columns, I'd like it to fill out each row with the data from a CSV formatted string / array as they're ordered in that way.
MWC