Reputation: 129
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
Upvotes: 2
Views: 4910
Reputation: 38875
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
Upvotes: 2
Reputation: 129
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; }
}
Upvotes: 0