Import data from .CSV file to a Grid

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.

0 csv.PNG

Image : 2

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

2 be to mapping.PNG

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.

3 of dialg.PNG

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.

4 import file.PNG

Image : 5

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

5 sekect  file.PNG

Image : 6 – code for open the csv file

Then you can see the selected file location in the text box.

6 selected file show.PNG

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.

7 show data in the grid.PNG

Image : 8

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

8 call to load data meth.PNG

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.

9 code for load data.PNG

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.

10 error in conversion.PNG

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.

You can download the solution using this link.
Thanks !
have a nice day… 🙂