If I understand you correctly, then, as a first approximation, you need to display the contents of a CSV
on a DataGridView
. This task can be divided into two stages:
- Read the file and parse it into an object (s) convenient for further work.
- Display the result on the
DataGridView
.
In the simplest case, this does not require a separate class; it suffices to render the processing of the source file into a separate method. Moreover, this method should not know anything about how the result of its work will be displayed, or about where the file came from. In addition, we need a class to represent a single row of CSV
. You can do without it, but later you will see why it is needed. Because I do not know (and you did not indicate in the question) the structure of the original CSV
, we will assume that it is guaranteed to have two columns. Then the class for representing the string might look like this:
public class CsvRow { public string FirstField { get; set; } public string SecondField { get; set; } }
Now select from your fragment the reading and parsing into a separate method that will return List<CsvRow>
as the result of processing:
private List<CsvRow>ParseCsv(string fileName) { var result = new List<CsvRow>(); foreach(var line in File.ReadLines(fileName)) { var values = line.Split(';'); var row = new CsvRow() { FirstField = values[0], SecondField = values[1] } result.Add(row); } return result; }
And we put the resulting method in the code of the form or a separate class with helpers. With the parser finished - display the result. Suppose we have a button, when clicking on which, the user selects a file for display.
private void button1_Click(object sender, EventArgs args) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { dataGridView1.DataSource = ParseCsv(openFileDialog1.FileName); } }
That's all for it.
But I promised to tell you why you need a class for data. The fact is that DataGridView
does not know how to work with fields - only with properties. For each public property, a separate column will be created and one row of the grid will contain the property values ββin the corresponding cells. Otherwise, it is necessary to fill the grid with your hands.
Alternatives
Implement the INotifyPropertyChanged
interface in Form1
, create a public field of type List<T>
trigger the PropertyChanged
event when writing values ββto it and, in the event handler, load the sheet into the DataSource
grid. It is a bit more complicated, but in some cases it is very convenient.
It is not recommended to set the public
access level to the public
level and work with it directly. This option breaks encapsulation, I cite it only because it is also possible, but it is never recommended for practical use.
PS: The above code intends to omit the checks when working with the file and some others, in order not to overload the code and bring the main idea.