我想在 winforms 组合框中列出 fims。因此,我尝试将组合框设置为具有 id
之类的值和公司 name
之类的项目名称。我正在从 mysql
数据库中获取公司列表。
SELECT id, name FROM firms
所以我的代码在这里:
private void FirmSelect_Load(object sender, EventArgs e)
{
Firm firm = new Firm(); //db model
DataTable data = firm.ListAlllFirm();
FirmComboBox.DataSource = data;
FirmComboBox.DisplayMember = "name";
}
这项工作很好,但我想将公司 ID 设置为项目值!我是否需要将 DataTable
与 foreach
交互并手动设置它?我该怎么做?
或任何其他方式来做到这一点;
最佳答案
您不想循环遍历集合来设置 ItemValue,
You can use the
ValueMember
property of theComboBox
for this, Which will allows you to Gets or sets the path of the property to use as the actual value for the items in the ListControl.
这可以通过使用以下代码来完成:
FirmComboBox.DisplayMember = "name";
FirmComboBox.ValueMember = "id";
FirmComboBox.DataSource = Data;
以便您可以使用 FirmComboBox.SelectedValue
访问值字段
关于C# winform 从 DataTable 中设置组合框项的值和名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38366190/