Wednesday, 22 May 2013

C# Read From file using Form Application





save the project in name of the read file

1 include the handler of the using System.IO
2 create the buttons in the form respectively as in code
3 stream reader also include
4 save the file in the bin folder debugg of name phone.Text thnx
5 phone.txt must contains name and phone numbers
run the code and enjoy.....!!



//Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace ReadFile
{
    public partial class Form1 : Form
    {
        private StreamReader phoneStreamReader;

        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            phoneStreamReader.Close();
            this.Close();
        }

        private void DisplayRecord()
        {
            // read and display the next record
            if (phoneStreamReader.Peek() != -1)
            {
                NameTextBox.Text = phoneStreamReader.ReadLine();
                PhoneTextBox.Text = phoneStreamReader.ReadLine();
            }
            else
                MessageBox.Show("Please try again");


        }

        private void button1_Click(object sender, EventArgs e)
        {
            //read the next record
            DisplayRecord();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //open the file and display the first record

            try
            {
                phoneStreamReader = new StreamReader("Phone.txt");
                DisplayRecord();
            }
            catch
            {
                //file is not found
                MessageBox.Show("File does not exsist.");
            }
        }

    }
}

No comments:

Post a Comment