本文介绍了组合框按ID选择项目,但显示名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数据库获取数据来填充我的组合框,所以让我说这样的数据:

I am getting data from database to populate my combo box, so lets say i have data like this:

|Column ID | Column Name |
|        1 |       Item1 |
|        2 |       Item2 |
|        3 |       Item3 |

所以现在我得到列名并填充组合框与它,但现在从一些其他功能我改变组合框所选项目,我想要是在填充组合框从数据库分配ID,所以当我说将组合框选择项目更改为ID 3,它更改为项目3

So for now i am getting Column Name and populating combo box with it but now from some other function i am changing combo box selected item and what i want is while populating combo box to assign ID from database so when i say to change combobox selected item to ID 3, it change to Item 3

推荐答案

您不需要类或从数据库数据创建列表。 DataTable 将正常工作:

You dont need a class or to create a List from db data. A DataTable will work just fine:

string sql = "SELECT Id, Descr FROM ccolor";

using (MySqlConnection dbcon = new MySqlConnection(MySQLConnStr))
using (MySqlCommand cmd = new MySqlCommand(sql, dbcon))
{
    DataTable dt = new DataTable();
    dbcon.Open();

    // fill the datatable
    dt.Load(cmd.ExecuteReader());

    // set up cbo
    cboColor.DisplayMember = "Descr";
    cboColor.ValueMember = "Id";
    cboColor.DataSource = dt;
}

它甚至不需要是持久表。然后,响应 SelectedValueChanged 事件:

It doesnt even need to be a persistent table. Then, respond to the SelectedValueChanged event:

Console.WriteLine("The value of {0} is {1}", cboColor.Text, cboColor.SelectedValue);



这篇关于组合框按ID选择项目,但显示名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 16:39