gpt4 book ai didi

c# 如何将一个对象添加到我的列表框但显示一个字符串

转载 作者:太空宇宙 更新时间:2023-11-03 19:51:24 25 4
gpt4 key购买 nike

我知道我的问题可能已经有人问过,但没有任何答案适合我。我有一个名为“Item”的类,我想将项目添加到我的列表框中,但字符串显示为 myItem.name。我在这个问题上尝试了建议的解决方案 c# add object to listbox and show string of object in it这是:

listBox.DisplayMember = myItem.name;
listBox.ValueMember = myItem.id;
listBox.Items.Add(myItem);

但它一直显示 namespace.Item 而不是项目的名称。

我还在 MouseClick 上添加了 MouseEventHandler,如何在 listBox_MouseClick 函数中获取选中的项目请有任何想法!!!

我的类(class)代码:

class Item
{
public string name;
public Item parent;
public List<Item> sons = new List<Item>();
public int depth = 0;
public int id = 0;

private static int nextID = 0;

public Item()
{

}

public Item(string Path)
{
this.name = Path;
this.parent = null;
this.sons.Clear();
this.depth = 0;
this.id = nextID;
nextID++;
}

public Item(Item Parent, string Path, int Depth)
{
this.parent = Parent;
this.name = Path;
this.sons.Clear();
this.depth = Depth;
this.id = nextID;
nextID++;
}

public bool isRoot()
{
bool root = false;
if (this.parent == null)
root = true;
return root;
}

public bool isFile()
{
bool file = false;
if (this.sons.Count == 0)
file = true;
return file;
}
}

最佳答案

您必须重写Item 类中的ToString 方法才能使ListBox 显示您想要的内容。因为它使用显示您所见内容的类的默认 ToString 方法。

试试这个:

public override string ToString()
{
// choose any format that suits you and display what you like
return String.Format("Name: {0}", this.name);
}

并使用你的常规方法

或使用绑定(bind)将您的项目放入ListBox。您需要一个包含您的项目的 List

List<Item> itemList = new List<Item>();
// populate it with you items and in the end
// bind it to the data source
this.listBox1.DataSource = itemList;

在任何情况下,您都必须重写 ToString 方法。

如果你想改变你的itemList不要忘记刷新ListBox:

listBox1.Refresh();
listBox1.Update();

关于c# 如何将一个对象添加到我的列表框但显示一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38922075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com