【问题标题】:Displaying information to 2 different listboxes - using trees向 2 个不同的列表框显示信息 - 使用树
【发布时间】:2013-03-20 16:04:55
【问题描述】:

我目前正在用 C# 设计一个表单,我正在尝试将信息显示到两个单独的文本框中。正如您所看到的,当我单击“添加艺术家”时,它会将艺术家和艺术家数量添加到同一个框中。我不希望它这样做。

我知道'listBox2.Items.Add(artist);'这一行导致这种情况,但是我不知道将其更改为什么,以便仅显示成员数。我的艺术家班级如下:

我认为我需要在第一个 return 语句中分隔名称和成员,以便我可以使用 listBox2.Items.Add(artist.members); 单独显示它们或表单类中的类似内容,但我不确定。

感谢任何帮助!谢谢:)

【问题讨论】:

    标签: c# forms list linked-list


    【解决方案1】:

    创建时的样子

    List<string> ListBoxItems = new List<string>();,您正在保存艺术家的ToString 返回的内容,即:

    (name + members);
    

    您可以做几件事,您可以将ListBoxItems 隐含为List<Artist>,然后您可以使用以下内容构建您的列表:

    foreach (string artist in ListBoxItems)
    {
        listBox1.Items.Add(artist.Name);
        listBox2.Items.Add(artist.Members);
    }
    

    或者,您可以制作 2 个列表。说ListBoxNamesListBoxMembers,并用各自的字段填充它们。我个人更喜欢第一种方法。

    或者,如果 ArtistTree 暗示 IEnumerable(突出显示并按 f12 进行检查),那么您可以从中提取

    foreach (Artist artist in ArtistTree)
    {
        listBox1.Items.Add(artist.Name);
        listBox2.Items.Add(artist.Members);
    }
    

    【讨论】:

    • 感谢 sam 的回复 :) 我当时试过了,但我收到了有关 Artist.Members speedcap.net/sharing/screen.php?id=files/b8/de/… 中的成员的错误。
    • @user2058186 我明白了,ListBoxItemsstring 的列表,您可能希望将其实现为Artist 的列表
    • 感谢您的回复,我会接受这个答案并自己尝试:)
    • @user2058186 是什么类型的ArtistTree
    • @user2058186 是内置数据类型,还是你定义的?
    【解决方案2】:

    listBox2.Items.Add(artist.Members);

    【讨论】:

    • 感谢您的回复 :) 我认为如果我使用的是数据字典,这会起作用,但是我使用的是树:/
    【解决方案3】:

    您需要将列表框的 DisplayMember 属性设置为您要显示的 Artist 类的公共属性。

    您可以在表单中包含以下代码以实现您的目标:

    listBox1.DisplayMember = "Name";
    listBox2.DisplayMember = "Members";
    

    【讨论】:

    • 我刚刚尝试过,它没有向任何一个列表框显示任何输出,我通过添加 listBox1.DisplayMember = "Name" + name; 玩了一下。最后但仍然没有成功
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 2012-04-29
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多