I have created an application to show how we can import a set of record from a .csv file to a grid.

image : 1
Here is the .csv file that I’m going to get data. I have entered some sample information.

Image : 2
And here is the business entities to map data from csv to a list.

Image : 3
I have added a OpenFileDialague to open the csv file location. You have to drag it from tool box and drop into your form.

Image : 4
this will show in the bottom of the form.
when you click on “Open csv” button, it’ll show you the below dialague and you can select the csv file which has created according to a specific format. Then click “ok”. after that the selected file location will show on the text box.

Image : 5
Here is the code for open the “Open file” dialogue and populate the csv file path to the text box.

Image : 6 – code for open the csv file
Then you can see the selected file location in the text box.

Image : 7
if you sure that the file is in a correct format. then click “Load to grid” button to load data in the csv file.

Image : 8
here is the code for populate data to grid form csv.

Image : 9 – Call to LoadItemsFromCSV() method
When you click the “Load to grid” button. the event calls to the “LoadItemsFromCSV()” method. the method contains the code for map data in csv file to the business entity object.
Image : 10 – LoadItemsFromCSV() method
Note :
In that code it get all the lines in the csv file to a string array.
after that using a for loop i’m splitting every line by “,” and map them to the business entity.
Item Id, Price and Quantity are integers. so i have convert them to integers when I’m mapping them to business entity class.
If i remove the Convert.ToInt32() , it’ll provide an error. ;( and the program will not compile.

Image : 11 – Error occurring when compiling
Reason : The error occurring because the ItemId in the business entity is an integer. but the record in the csv file is a string. so string cannot map to a integer. so prevent the error, we have to convert the data in the csv file according to the data in business entity.