在表单中显示更新列表

时间:2014-02-06 10:38:13

标签: c# winforms list streamwriter

我正在设计一个数据库来保存正在从文本文件中读取的员工列表。 我有两种形式,第一种形式(frmManager)作为一个视图来浏览列表,我有下一个和前一个按钮,我滚动列表中的员工。另一种形式(frmAdd)可以将新员工添加到列表中。我的问题是,当我更新List<>时,如何在frmManager中更新它?当我添加一个新员工时,theiir属性被写入文本文件但我必须重建项目以显示更新列表。 添加员工的文件:

public class EmployeeDB
{
    public List<Employee> employees;

    public static EmployeeDB instance;

    public static EmployeeDB Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new EmployeeDB();
                instance.populate();
            }
            return instance;
        }
    }

    public EmployeeDB()
    {
        employees = new List<Employee>();
    }

    public void populate()
    {
        string[] parts;
        foreach (string line in File.ReadAllLines("StaffList.txt"))
        {
            parts = line.Split(',');
            employees.Add(new Employee(parts[0], parts[1], parts[2], parts[3], int.Parse(parts[4]), int.Parse(parts[5])));

        }
    }
}

employee类只包含一个构造函数来添加它们的详细信息。 添加新员工的表格

public partial class frmAdd : Form
{

    EmployeeDB employee;
    int grade;

    public frmAddEmployee()
    {
        employee = EmployeeDB.Instance;
        InitializeComponent();
    }

    private void btnCreate_Click(object sender, EventArgs e)
    {
        System.IO.StreamWriter file = new System.IO.StreamWriter("StaffList.txt", true);

        foreach (Employee em in employee.employees) //To avoid username clashes
        {
            if (em.username == txtUsername.Text)
            {
                file.WriteLine(txtFName.Text + "," + txtLName.Text + "," + txtUsername.Text + employee.employees.Count()
                               + "," + txtPassword.Text + "," + checkedButton().ToString() + ","
                              + 0.ToString(), Environment.NewLine);
            }
            else
            {
                file.WriteLine(txtFName.Text + "," + txtLName.Text + "," + txtUsername.Text
                                        + "," + txtPassword.Text + "," + checkedButton().ToString() + ","
                                       + 0.ToString(), Environment.NewLine);
            }

            file.Close();
            MessageBox.Show("Employee successfully added");
            return;
        }

我已经尝试过调用EmployeeDB文件,希望它会重新填充无济于事。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您没有在任何地方将新员工添加到列表中。从您包含的代码中,您只能通过populate()填充列表。

我会在点击按钮时将新员工添加到EmployeeDB。这将使列表保持最新。然后我会在EmployeeDB类中添加一个写入文件的方法。

private void btnCreate_Click(object sender, EventArgs e)
{
    string username = txtUsername.Text;
    int i = employee.employees.Count();
    while (employee.AsEnumerable().Select(r => r.username == username).Count() > 0)
    {
        username = txtUserName.Text + i++;  //Makes sure you have no common usernames
    }
    employee.employees.Add(new Employee(){...});
    employee.SaveFile(); //New method  
}

我假设您在Employee类中有一个名为username的字符串,因此r =&gt; r.username以上