在C#中,将空项添加到自定义对象的下拉列表中,可以通过以下步骤实现:
public class CustomObject
{
public int Id { get; set; }
public string Name { get; set; }
}
List<CustomObject> customObjects = new List<CustomObject>
{
new CustomObject { Id = 0, Name = "" },
new CustomObject { Id = 1, Name = "Object 1" },
new CustomObject { Id = 2, Name = "Object 2" },
new CustomObject { Id = 3, Name = "Object 3" }
};
// 使用WinForms
comboBox.DataSource = customObjects;
comboBox.DisplayMember = "Name";
comboBox.ValueMember = "Id";
// 使用WPF
comboBox.ItemsSource = customObjects;
comboBox.DisplayMemberPath = "Name";
comboBox.SelectedValuePath = "Id";
这样,在下拉列表中就会显示一个空项,以及自定义对象的名称。
领取专属 10元无门槛券
手把手带您无忧上云