Csharp/C#教程:如何在C#中的combobox显示成员中追加两个字段值分享


如何在C#中的combobox显示成员中追加两个字段值

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

像这样的东西

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

我怎样才能做到这一点? 这样lastnamefirstname都将显示在combobox

假设你有这样一个类:

 class Person { public string FirstName { get; set; } public string LastName { get; set; } public string FullName { get { return LastName + ", " + FirstName; } } public Person(string firstname, string lastname) { FirstName = firstname; LastName = lastname; } } 

如果您没有FullName属性,只需以您希望显示名称的格式创建一个。 然后将DisplayMember设置为FullName

此示例将指导您如何在不修改基类的情况下执行此操作。

首先,你可以让你的DisplayMember有一个属性,让我们说:

 cmbEmployees.DisplayMember = "lastname"; 

现在,在[Design]模式下转到表单,右键单击ComboBox – > Properties。

在“属性”窗口的顶部,单击“事件”(闪电图标),

在下面的事件列表中查找格式(在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; } 

而已 ;)

您的查询在GetEmployees()函数中应该是这样的。

 "SELECT id,(lastname + ' ' + first_name) AS NAME FROM TABLE" cmbEmployees.DataSource = GetEmployees(); cmbEmployees.DisplayMember = "NAME"; cmbEmployees.ValueMember = "id"; 

尝试以下方法之一:

在C#6中,在Employee类中创建只读属性

 public string FullName=>$"{lastname} {firstname}"; 

然后

上述就是C#学习教程:如何在C#中的combobox显示成员中追加两个字段值分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1041783.html

(0)
上一篇 2022年1月29日
下一篇 2022年1月29日

精彩推荐