Friday, May 22, 2009

Read & Write ListBox Item into File: Windows Application

Normally some projects will have very small requirement of storing data, so going to have database and storing small amount of data into database is not suitable answer, you can go for storing data into XML or txt file, in following example I am trying to read and write Listbox items into txt file.
I am using Form_Load method to read data from the txt file and on closing the form I am reading all items in the list box and saving them into a txt file with , separator.
Let start building the example.
Create a windows forms applciation and add a List Box, a Text Box and 2 buttons.
Please refer the screen shot : Design.jpg.

design


Make sure that you have created data.txt in c:\logs folder, here I am using C:\logs path you can create any where in the system and change page in the code.
Once you are ready with design and creating txt file, we will add code to read all the items in the text file in Form_Load and also in Form_Closing we will ad code to store all the items in to text file back please refer the code below in screen shot FomLoadUnload.JPG

FomLoadUnload

Once we have added code to read and write to text file now we will add code to add and remove items in the list box, we are using Button2 for removing the items and Button1 for adding the items, please add Click event of Button 1 and 2 to the code, you can refer below code in screen shot AddRemoveItems.JPG

AddRemoveItems

Now we are ready with code just build, run and test

Output


hope this helps.

No comments:

Post a Comment