I have created an application to show how we can import a set of record from a .csv file to a grid.
Here is the .csv file that I’m going to get data. I have entered some sample information.
And here is the business entities to map data from csv to a list.
I have added a OpenFileDialague to open the csv file location. You have to drag it from tool box and drop into your form.
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.
Here is the code for open the “Open file” dialogue and populate the csv file path to the text box.
Then you can see the selected file location in the text box.
if you sure that the file is in a correct format. then click “Load to grid” button to load data in the csv file.
here is the code for populate data to grid form csv.
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
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.
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.