如何在ListBox C#中显示数据对象?

时间:2017-08-10 16:25:45

标签: c# winforms c#-4.0

我有填充ListBox的函数:

private void fillWorkListBox()
{
    this.list = manager.works();
    this.listBox1.DisplayMember = "Название";
    this.listBox1.ValueMember = "ID";

    for (var i = 0; i < this.list.works.Count; i++)
    {
        string name = "№" + this.list.works[i].id + " - " + this.list.works[i].name;

        WorkModel work = new WorkModel();
        work.name = name;
        work.id = this.list.works[i].id;

        listBox1.Items.Add(work);

    }
}

模型是:

class WorkModel
{
    public string name { get; set; }
    public int id { get; set; }
}

当我运行项目时,我在ListBox中看到对象模型work的类型。取而代之的是name,密钥为id

如何解决?

2 个答案:

答案 0 :(得分:1)

而不是直接将工作对象添加到列表框中。

执行以下操作。 如果您想要显示ID,您也可以附加ID(您可能需要在追加之前转换为字符串)

listBox1.Items.Add("Name: " + work.name + "Key: " + Convert.ToString(work.id));

答案 1 :(得分:1)

private void fillWorkListBox()
        {
            IList<WorkModel> managerWorks = new List<WorkModel>
            {
                new WorkModel {name="fooNameOne",id=1 },
                new WorkModel {name="fooNameTwo",id=2 }
            };

            listBox1.DisplayMember = "Название";
            listBox1.ValueMember = "ID";

            WorkModel workModel = new WorkModel();

            for (var i = 0; i < managerWorks.Count; i++)
            {
                string name = "№" + managerWorks[i].id + " - " + managerWorks[i].name;

                workModel.name = name;
                workModel.id = managerWorks[i].id;
                listBox1.Items.Add("Name:" + workModel.name + "Id:" + workModel.id.ToString());
            }
        }