【问题标题】:C# - How to list listbox objects by nameC# - 如何按名称列出列表框对象
【发布时间】:2022-11-27 02:41:04
【问题描述】:

我有一个 Employee 类,当我填写文本字段并单击添加按钮时,它会填充一个列表框。当项目被添加到列表中时,它会显示对象属性,我需要弄清楚如何将对象存储在列表中,但还要按名称列出它。

这是我的员工班级:

class Employee
    {
        public string Name;
        public string Position;
        public DateTime BirthDate;
        public DateTime StartDate;
        public decimal Wage;

        public Employee(string name, string position, DateTime birthDate, DateTime startDate, decimal wage)
        {
            Name = name;
            Position = position;
            BirthDate = birthDate;
            StartDate = startDate;
            Wage = wage;
        }
    }

这是我的按钮点击事件:(我填充列表的地方)

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            var employees = new List<Employee>();
            var name = txtName.Text;
            var position = txtPosition.Text;
            DateTime birthDate = dpBirthDate.Date.DateTime;
            DateTime startDate = dpStartDate.Date.DateTime;
            var wageValue = txtWage.Text;
            decimal wage = Decimal.Parse(wageValue);
            employees.Add(new Employee(name, position, birthDate, startDate, wage));
            foreach(Employee employee in employees)
            {
                lbEmployee.Items.Add(employee);
            }

        }

对于每个循环中的按钮单击事件,我尝试通过这样做列出对象

foreach(Employee employee in employees)
    {
       lbEmployee.Items.Add(employee.Name);
    }

这按名称列出但不添加整个对象,因此它破坏了下面的功能

private void lbEmployee_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
        {
            Employee employee = (Employee)lbEmployee.SelectedItem;
            if (employee != null)
            {
                txtName.Text = employee.Name;
                txtPosition.Text = employee.Position;
                dpBirthDate.Date = employee.BirthDate;
                dpStartDate.Date = employee.StartDate;
                txtWage.Text = Convert.ToString(employee.Wage);
            }
        }

【问题讨论】:

  • 打破功能是什么意思?

标签: c# listbox


【解决方案1】:

你必须设置

lbEmployee.DisplayMember = "Name";

在设计器中,然后您可以在项目中添加员工,避免破坏您的功能

【讨论】:

    猜你喜欢
    • 2019-06-26
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多