Search code examples
c#windowsdatagridviewreturnfill

C# fill DataGridView by return from other class


Hi I have a program to parse a CSV and fill it into a DataGridView.

When I'm doing it like this it works great:

        openFileDialog1.Filter = "CSV Files(*.csv)|*.csv";
        openFileDialog1.FilterIndex = 1;
        openFileDialog1.RestoreDirectory = true;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            txtCsvSource.Text = openFileDialog1.FileName;
            Encoding iso = Encoding.GetEncoding("ISO-8859-1");
            using (CachedCsvReader csv = new CachedCsvReader(new StreamReader(txtCsvSource.Text, iso), true))
            {
               csv.MissingFieldAction = MissingFieldAction.ReplaceByEmpty;
               dataGridView1.DataSource = csv;
            }
        }

But when Im doing it like this:

        openFileDialog1.Filter = "CSV Files(*.csv)|*.csv";
        openFileDialog1.FilterIndex = 1;
        openFileDialog1.RestoreDirectory = true;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            txtCsvSource.Text = openFileDialog1.FileName;
            dataGridView1.DataSource = QrFunctions.parsecsv(txtCsvSource.Text);
            dataGridView1.Update();
        }

with the QrFunctions.parsecsv being like:

public CachedCsvReader parsecsv(string csvpath)
    {
        Encoding iso = Encoding.GetEncoding("ISO-8859-1");
        using (CachedCsvReader csv = new CachedCsvReader(new StreamReader(csvpath, iso), true))
        {
            csv.MissingFieldAction = MissingFieldAction.ReplaceByEmpty;
            return csv;
        }
    }

the DataGridView is empty... why? I simply have no idea :-( I just wanted to use this function to parse in another Class, so I created the class QrFunctions.


Solution

  • Try this.

    public CachedCsvReader parsecsv(string csvpath)
        {   
            Encoding iso = Encoding.GetEncoding("ISO-8859-1");
            CachedCsvReader csv = new CachedCsvReader(new StreamReader(csvpath, iso), true)
            {
                csv.MissingFieldAction = MissingFieldAction.ReplaceByEmpty;
                return csv;
            }
        }
    

    Please remember to dispose of the object yourself, since I have removed the using statement or implement the IDisposable pattern

    Thanks to @MartiniMoe for constructive comments.