将自定义类对象添加到 C# 中的列表框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/794163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding custom class objects to listbox in c#
提问by Anirudh Goel
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,第二列必须有 processID。我如何在 C# 2.0 中实现这一点?
采纳答案by James Couvares
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());
}
回答by Eoin Campbell
A list box has a single ListItem (string) displayed to the user.
列表框具有向用户显示的单个 ListItem(字符串)。
So you could override ToString() as
所以你可以将 ToString() 覆盖为
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 Control 或 DataGridView
回答by Fredrik M?rk
What kind of control do you use for the list? If you use a ListView, then you can do like this (assuming that instanceis a Process_Items - which btw is a strange name for a class IMO - instance):
您对列表使用哪种控件?如果您使用 ListView,那么您可以这样做(假设该实例是 Process_Items - 顺便说一句,对于 IMO 类来说,这是一个奇怪的名称 - 实例):
listView1.Items.Add(instance.ProcessName).SubItems.Add(instance.ProcessID.ToString());