简体   繁体   English

C#WinForm设置值和DataTable中组合框项目的名称

[英]C# winform set value and name of combobox item from DataTable

I want to list fims inside winforms combobox. 我想在winforms组合框内列出fims。 So am trying to set combobox to have id like value and firm name like item name. 因此,我试图将组合框设置为具有id如值)和公司name如项目名称)。 Am getting list of firms from mysql database. 我正在从mysql数据库获取公司列表。

SELECT id, name FROM firms

So my code is here: 所以我的代码在这里:

private void FirmSelect_Load(object sender, EventArgs e)
{
    Firm firm = new Firm(); //db model
    DataTable data = firm.ListAlllFirm();
    FirmComboBox.DataSource = data;
    FirmComboBox.DisplayMember = "name";
}

This work good but i want to set firm id as item value! 这项工作很好,但我想将公司ID设置为商品价值! Does i need to interate DataTable with foreach and manually set it? 我需要将DataTableforeach进行交互并手动设置它吗? How can i do that? 我怎样才能做到这一点?

Or any other way to do this; 或任何其他方式执行此操作;

You don't want to Loop Through the collection to Set the ItemValue, 您不想遍历集合以设置ItemValue,

You can use the ValueMember property of the ComboBox 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. 您可以为此使用ComboBoxValueMember属性,这将允许您获取或设置该属性的路径以用作ListControl中各项的实际值。

This can be done by using the following code: 这可以通过使用以下代码来完成:

FirmComboBox.DisplayMember = "name";
FirmComboBox.ValueMember = "id";
FirmComboBox.DataSource = Data;

So that you can access the Value Field by using FirmComboBox.SelectedValue 这样您就可以使用FirmComboBox.SelectedValue访问“值”字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM