views:

35

answers:

4

I have table - custom id (like 1.10,1.20) and name (string where values can repeat). And my problem is to set it to winForms control like combobox. But I want to that user in field will see only name and id will not visible but subconsciously should be connect to names in control that when user select item in combobox I can get this id.

any idea that it's possible?

+1  A: 

Use the DisplayMember property to set what will be shown and use ValueMember to set what it actually links to.

e.g. in your case, set DataSource to the table, DisplayMember to name and ValueMember to Id.

Raze2dust
+1  A: 

Bind to a list:

Items:

class MyItem
{
    public int Id { get; set; }
    public string DisplayText { get; set; }
}

Setup binding:

List<MyItem> items = new List<MyItem>
{
    new MyItem(){ Id = 1, DisplayText = "one"},
    new MyItem(){ Id = 2, DisplayText = "two"},
};

comboBox1.DisplayMember = "DisplayText"; // or whatever field your you want to display
comboBox1.DataSource = items;

Find value:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var item = comboBox1.SelectedItem as MyItem;
    if (item != null)
        Console.WriteLine(item.Id);
}
Albin Sunnanbo
A: 

Getting rid of the ItemData concept had to be one of the most stupid things Micro$oft has ever done, ever. Mind numbing actually.

It is exactly what you need.

Here is a link that mimics that behavior. ItemData

JustBoo
+2  A: 

Setup your combo box like this:

// item type to display in the combobox
public class Item
{
    public int Id { get; set; }
    public string Text { get; set; }
}

// build new list of Items
var data = List<Item>
{
    new Item{Id = 1, Text = "Item 1"},
    new Item{Id = 2, Text = "Item 2"},
    new Item{Id = 3, Text = "Item 3"}
};

// set databind
comboBox1.DataSource = data;
comboBox1.ValueMember = "Id";  // the value of a list item should correspond to the items Id property
comboBox1.DisplayMember = "Text";  // the displayed text of list item should correspond to the items Id property

// get selected value
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var selectedValue = comboBox1.SelectedValue;        
}
Dave
Super!Super! Ideal solution :)
netmajor