Adding custom class objects to listbox in c#

三世轮回 提交于 2019-12-10 19:26:16

问题


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?


回答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());
}



回答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




回答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());


来源:https://stackoverflow.com/questions/794163/adding-custom-class-objects-to-listbox-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!