简体   繁体   中英

Combo box select item by Id but displayed names

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 |

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

I figured it it. Here is the answer:

divizija.DisplayMember = "Column Name";
divizija.ValueMember = "Column Id";

List<Items> items = new List<Items>();
FbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
    items.Add(new Items { Id = (int)dr[0], Name = (string)dr[1]});
}    
divizija.DataSource = items;
divizija.SelectedValue = divizijaDokumenta;

And for items list i need class and here it is

public class Items
{
    public int Id { get; set; }
    public string Name { get; set; }
}

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;
}

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);

The value of orange is 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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