Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views2 pages

Read File

Uploaded by

Bá Việt Lê
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Read File

Uploaded by

Bá Việt Lê
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

namespace ReadFileFromWindownForm1

{
public partial class Form1 : Form
{
List<Student> students;
public Form1()
{
students = new List<Student>();
InitializeComponent();
}

DataTable table = new DataTable();


private void Form1_Load(object sender, EventArgs e)
{
cbMajor.SelectedIndex = 0;
}
private void btOpenfile_Click(object sender, EventArgs e)

{
loadFile();
}

private void loadFile()


{
dgvStudents.Rows.Clear();
String filename = @"D:\Student.txt";
string[] lines = File.ReadAllLines(filename);
if(lines.Length > 0)
{
tbOpenfile.Text = filename;
string[] values;
for (int i = 0; i < lines.Length; i++)
{
values = lines[i].ToString().Split('|');
string[] row = new string[values.Length];
for (int j = 0; j < values.Length; j++)
{
row[j] = values[j].Trim();
}

dgvStudents.Rows.Add(row);
Student student = new Student(row[0], row[1],
Boolean.Parse(row[2]), row[3]);

students.Add(student);

}
dgvStudents.AllowUserToAddRows = false;
}
}

private void btAdd_Click(object sender, EventArgs e)


{
String filename = @"D:\Student.txt";
String studentID = tbStudentID.Text;
if (studentID == null || studentID.Trim().Length== 0)
{
MessageBox.Show("StudentID must not empty!");
}
else
{
String studentName = tbStudentName.Text;
Boolean male;
if (rbFemale.Checked == true)
{
male = false;
}
else
{
male = true;
}
String major = cbMajor.Text;
Student newStudent = new Student(studentID, studentName, male,
major);
students.Add(newStudent);

try
{
StreamWriter streamWriter = new StreamWriter(filename);
using (streamWriter)
{
foreach (Student s in students)
{
streamWriter.WriteLine(s.StudentID + '|' +
s.StudentName + '|' + s.Male + '|' + s.Major);

}
}
loadFile();
MessageBox.Show("Add successful!");
}
catch (Exception ex)
{

}
}

}
}

You might also like