繁体   English   中英

WinForm ListBox - 如何显示对象中的文本?

[英]WinForm ListBox - how to display text from an object?

我有一段代码正在处理,是别人开始的。 他们创建了自定义对象(不是集合)并将这些对象即时插入列表框。 但是,他们显然从未做过显示文本的部分。 它只是在列表框中重复显示“集合”。 他们没有使用绑定,也没有预先创建这些对象的集合,所以我认为我不能使用 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() 方法的 Document 类

public class Document{

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

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

lstAttachedDocuments.DataSource = dt;

然后是 DisplayMember

lstAttachedDocuments.DisplayMember = "FileName";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM