how to copy the contents of text file into list box

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anjali31187
    New Member
    • Sep 2010
    • 1

    how to copy the contents of text file into list box

    i have a text file having employee id,name anb phone number seperated by :
    i want to bring all the employee ids into one listbox of windows form so that user can select one out of it. and when user selects one employee id out of it corresponding name and phone number should come in other two textboxes of the same form..how can i do this?
  • Christian Binder
    Recognized Expert New Member
    • Jan 2008
    • 218

    #2
    First create a data-structure which contains all employee's details.
    e.g.
    Code:
    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.ReadAllLin es() 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.
    Code:
    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 SelectedIndexCh anged-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.
    Code:
    if (listBox1.SelectedItem is Employee) {
      Employee emp = (Employee)listBox1.SelectedItem;
      textBox1.Text = emp.Name;
      textBox2.Text = emp.Phone;
    }
    Hope this helps :-)

    Comment

    Working...