在我的表中,我有一个firstname
和lastname
的字段,现在我想要的是设置firstname
和lastname
作为组合框中的 displaymember
,但我不知道该怎么做。
像这样
cmbEmployees.DataSource = GetEmployees();
//something like below line which doesn't work
cmbEmployees.DisplayMember = "lastname, first_name";
cmbEmployees.ValueMember = "id";
我怎样才能做到这一点?这样 lastname
和 firstname
都会显示在 combobox
最佳答案
此示例将指导您如何在不修改基类的情况下执行此操作。
首先,您可以为 DisplayMember 保留一个属性,比方说:
cmbEmployees.DisplayMember = "lastname";
现在,在 [设计] 模式下转到您的表单, 右键单击组合框 -> 属性。
在“属性”窗口的顶部,单击“事件”(闪电图标),
在下面的事件列表中查找 Format(在 Property Changed 下)并在其中键入一些事件名称,比方说:ComboBoxFormat,然后按 Enter。你会看到这个:
private void ComboBoxFormat(object sender, ListControlConvertEventArgs e)
{
}
现在在里面写下以下几行:
private void ComboBoxFormat(object sender, ListControlConvertEventArgs e)
{
// Assuming your class called Employee , and Firstname & Lastname are the fields
string lastname = ((Employee)e.ListItem).Firstname;
string firstname = ((Employee)e.ListItem).Lastname;
e.Value = lastname + " " + firstname;
}
就是这样;)
关于c# - 如何在 C# 中的组合框显示成员中附加两个字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14679253/