Adding custom class objects to listbox in c#

Adding custom class objects to listbox in c#

惜醉颜 发布于 2021-11-26 字数 633 浏览 813 回复 3 原文

i have a class which looks like this

public class Process_Items
{
    String Process_Name;
    int Process_ID;
    //String Process_Title;
    public string ProcessName
    {
        get { return Process_Name; }
        set { this.Process_Name = value; }
    }
    public int ProcessID
    {
        get { return Process_ID; }
        set { this.Process_ID = value; }
    }
}

now i want to create a Process_Items[] Array and display all the elements in a multi column listbox. Such that first column must have the processName and 2nd must have the processID. How can i achieve this in C# 2.0?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

-黛色若梦 2022-06-07 3 楼

What kind of control do you use for the list? If you use a ListView, then you can do like this (assuming that instance is a Process_Items - which btw is a strange name for a class IMO - instance):

listView1.Items.Add(instance.ProcessName).SubItems.Add(instance.ProcessID.ToString());
剪不断理还乱 2022-06-07 2 楼

A list box has a single ListItem (string) displayed to the user.

So you could override ToString() as

public override string ToString()
{
    return string.Format("{0} [ProcID: {1}]", this.Process_Name , this.ProcessID);
}

If this is for a winforms app, have a look at the ListView Control or a DataGridView

云裳 2022-06-07 1 楼

You should use a ListView control and add two columns (ListBox only has one column)

Process_Items[] items = new Process_Items[] // Initialize array

foreach(Process_Items p in items) {
    listView.Items.Add(p.ProcessName).Subitems.Add(p.ProcessID.ToString());
}