First create a data-structure which contains all employee's details.
e.g.
-
public class Employee {
-
public string Id { get; set; }
-
public string Name { get; set; }
-
public string Phone { get; set; }
-
}
-
then I'd create a buffer containing the file's content.
I'd use a List<Employee>.
The third step would be reading the file into the buffer.
File.ReadAllLines() will return an array where each entry represents a line in the file. Iterate over this array and use string.Split to separete by ':'
Then store the results in the buffer.
-
public void Read() {
-
List<Employee> employees = new List<Employee>();
-
foreach (string line in File.ReadAllLines(@"C:\emps.txt")) {
-
string[] details = line.Split(':');
-
if (details.Length >= 3) {
-
Employee emp = new Employee() {
-
Id = details[0],
-
Name = details[1],
-
Phone = details[2]
-
};
-
employees.Add(emp);
-
}
-
}
-
// assign buffer to list box
-
listBox1.DataSource = employees;
-
listBox1.DisplayMember = "Id";
-
}
-
The listbox is now filled with the values of employees and the Id-property will be displayed.
If the selection in the listbox changes, we want to display the selected employee's details.
So we use the SelectedIndexChanged-event of the ListBox. As the items of the ListBox are of type Employee, we cast the selected item and display its details.
E.g.
-
if (listBox1.SelectedItem is Employee) {
-
Employee emp = (Employee)listBox1.SelectedItem;
-
textBox1.Text = emp.Name;
-
textBox2.Text = emp.Phone;
-
}
-
Hope this helps :-)