【问题标题】:WinForm ListBox - how to display text from an object?WinForm ListBox - 如何显示对象中的文本?
【发布时间】:2020-12-21 20:38:43
【问题描述】:

我正在编写一段由其他人开始编写的代码。他们创建了自定义对象(不是集合)并将这些对象动态插入到列表框中。但是,他们显然从未做过显示文本的部分。它只是在列表框中重复显示“收藏”。他们没有使用绑定,也没有提前创建这些对象的集合,所以我认为我不能使用 DisplayMember。如何告诉 WinForms 要显示的字段?

        foreach (DataRow row in dt.Rows) {

            Document doc = new Document();
            doc.DocumentID  = Guid.Parse (row ["ID"].ToString());
            doc.FileName    = row ["FileName"].ToString();

            // Now add the items to the listbox.  
            lstAttachedDocuments.Items.Add (doc);
        }

【问题讨论】:

  • 覆盖ToString in Document
  • 您可以控制Document 类吗?还是来自您使用的某个 API?
  • 是的,您可以设置DisplayMember。您还可以构建一个List<Document> 并将其用作数据源。或者使用 DataTable 作为 ListBox.DataSource。很多选择。
  • 有一个文档类,但它只有 3 个属性(DocumentID、FileName、FullPath)。
  • 有人可以提供一段简单的代码来解决我的问题吗?我为自定义类编写了一个简单的 ToString() 方法,但这并没有改变任何东西。

标签: c# winforms listbox


【解决方案1】:

如果您无法控制可以覆盖 ToString() 方法的 Document 类

public class Document{

//....        
public override string ToString()
            {
                //Add more properties here if needed 
                return $"{FileName}";
            }
}

然后只需将 lstAttachedDocuments 数据源设置为数据表

lstAttachedDocuments.DataSource = dt;

然后是 DisplayMember

lstAttachedDocuments.DisplayMember = "FileName";

【讨论】:

  • 谢谢!多么简单的解决方案。我喜欢它。它确实导致了一个问题,当我更新列表框时,旧的结果并没有消失,但这绝对是一个干净的开始。感谢您的帮助。
  • 等等,还有一个快速的问题......当一个项目被点击时,我如何从列表框中获取 DocumentID?
  • 文档 selectedDocument = (Document)lstAttachedDocuments.SelectedItem;现在您可以以任何方式或方法显示 selectedDocument 的属性
  • 我想我有。我刚刚将 ValueMember 分配给 DocumentID。我现在应该可以参考了。再次感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 2012-05-08
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多