c# - 如何在 C# 中的组合框显示成员中附加两个字段值

标签 c# winforms combobox

在我的表中,我有一个firstnamelastname的字段,现在我想要的是设置firstnamelastname 作为组合框中的 displaymember,但我不知道该怎么做。

像这样

cmbEmployees.DataSource = GetEmployees();
//something like below line which doesn't work
cmbEmployees.DisplayMember = "lastname, first_name";     
cmbEmployees.ValueMember = "id";

我怎样才能做到这一点?这样 lastnamefirstname 都会显示在 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/

相关文章:

c# - 如何使用 linq 解析字典列表 (List<Dictionary<string, string>>)

C# ADO.NET IBM DB2 命名参数具有相同的名称抛出没有足够的参数指定异常

c# - 将对象中的 Json 数组发送到 API

vb.net - 如何设置DataGridView行标签

c# - UI线程如何知道另一个线程上的数据?

c# - 绑定(bind)组合框 - 处理外键

java - 将项目添加到在 FXML 中创建的 ComboBox(在 JavaFX 应用程序的 Controller 类内)

c# - 包含组合框窗口窗体的组合框项

C# 浏览器缩放

wpf - 带有 AutoGenerateColumns 的 WPF DataGrid 中枚举值的描述​​属性