在c#中将自定义类对象添加到列表框

时间:2023-01-17 13:53:30

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?

现在我想创建一个Process_Items []数组并显示多列列表框中的所有元素。这样第一列必须具有processName和2nd必须具有processID。我怎样才能在C#2.0中实现这一目标?

3 个解决方案

#1


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

您应该使用ListView控件并添加两列(ListBox只有一列)

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.

列表框具有向用户显示的单个ListItem(字符串)。

So you could override ToString() as

所以你可以覆盖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

如果这是针对winforms应用程序,请查看ListView控件或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):

你对列表使用什么样的控制?如果您使用ListView,那么您可以这样做(假设该实例是Process_Items - 其中btw是类IMO的奇怪名称 - 实例):

listView1.Items.Add(instance.ProcessName).SubItems.Add(instance.ProcessID.ToString());

#1


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

您应该使用ListView控件并添加两列(ListBox只有一列)

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.

列表框具有向用户显示的单个ListItem(字符串)。

So you could override ToString() as

所以你可以覆盖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

如果这是针对winforms应用程序,请查看ListView控件或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):

你对列表使用什么样的控制?如果您使用ListView,那么您可以这样做(假设该实例是Process_Items - 其中btw是类IMO的奇怪名称 - 实例):

listView1.Items.Add(instance.ProcessName).SubItems.Add(instance.ProcessID.ToString());