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



我有一段代码是别人开始编写的。他们创建了自定义对象(而不是集合(,并将这些对象动态插入列表框。然而,他们显然从未做过显示文本的部分。它只是显示了";集合";在列表框中重复。他们没有使用绑定,也没有提前创建这些对象的集合,所以我认为我不能使用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);
}

如果您不能控制Document类,则可以覆盖ToString((方法

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

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

lstAttachedDocuments.DataSource = dt;

然后显示成员

lstAttachedDocuments.DisplayMember = "FileName";

相关内容

最新更新