ComboBox.ValueMember and DisplayMember
Asked Answered
I

10

13

How do i set this values? I have a DataTable with all the data i want to set in the combobox, but i cant find how to set it.

I tried

ComboBox1.DataSource = dataTable;
ComboBox1.ValueMember = "id"; // --> once hes here, he just jumps out the method
ComboBox1.DisplayMember = "name";

No compilation error, warning, nothing.. just jumps out!

This is the query to fill the DataTable

"Select * from \"Table\""

I checked with the debugger and the datatable was filled. The columns names are "id" and "name". ComboBox is blank. I'm filling it for the first time!

Illsuited answered 1/3, 2012 at 18:38 Comment(1)
no, i was wrong... it was with the "id" and "name". Srry bout thatIllsuited
A
41

You should not set datasource of your listbox and/or combobox in this order

ComboBox1.DataSource = dataTable;

ComboBox1.ValueMember = "id"; 

ComboBox1.DisplayMember = "name";

Instead, this is correct order:

ComboBox1.ValueMember = "id"; 

ComboBox1.DisplayMember = "name";

ComboBox1.DataSource = dataTable;

NOTE: setting datasource should be last line.

If you set datasource first, SelectedIndexChanged event will fire and you may get the cast error or other exception.

Assets answered 24/9, 2014 at 0:16 Comment(3)
Doesn't make sense; if you don't give the combobox the datasource first, how would it know what should be the ValueMember and what should be the DisplayMember if it doesn't have the data in the first place. That's a counter-intuitive practice.Girhiny
@Girhiny you're right, it is counter-intuitive, but it works. Do a search for combobox datarowview and you'll see others who've had the same problem.Precessional
@Girhiny If you look how it works internally, you would understand that setting Datasource last is essential for performance. Because setting ValueMember triggers no action. If you set Datasource first, cbo will bind value member for you. Then, you're going to set new ValueMember [the one you want] and cbo will have to re-wire binding. So, if you set DS last, bindings will happen only once.Florri
O
8

Using keyvalue pairs to populate a combobox

A neat way to populate combo boxes is to set the datasource to a list of keyvalue pairs. It may also inspire using data stored in a list of some kind:

//Some values to show in combobox
string[] ports= new string[3] {"COM1", "COM2", "COM3"};

//Set datasource to string array converted to list of keyvaluepairs
combobox.Datasource = ports.Select(p => new KeyValuePair<string, string>(p, p)).ToList();

//Configure the combo control
combobox.DisplayMember = "Key";
combobox.ValueMember = "Value";
combobox.SelectedValue = ports[0];

The datasource can be populated using this syntax as well:

ports.Select(p => new { Key = p, Value = p }).ToList();

The technicue may be expanded with more property names for multiple column lists.

Objects that are already key-value pairs like Dictionary items can be used directly

combobox.DataSource = new Dictionary<int, string>()
{
    {0, "COM1"},
    {1, "COM2"},
    {2, "COM3"},
}.ToList();
combobox.ValueMember = "Key";
combobox.DisplayMember = "Value";

Tuples can be initialized and used like this

var ports= new List<Tuple<int, string>>()
{
    Tuple.Create(0, "COM1"),
    Tuple.Create(1, "COM2"),
    Tuple.Create(2, "COM3")
};

combobox.DataSource = ports;
combobox.ValueMember = "Item1";
combobox.DisplayMember = "Item2";
Octan answered 20/2, 2017 at 13:14 Comment(1)
This should be the answer; it functions perfectly with Enums as DataSource: Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>().Select(e => new { Key = e, Value = e }).ToList();Expendable
W
3
  ComboBox1.DataSource= dt; //the data table which contains data
  ComboBox1.ValueMember = "id";   // column name which you want in SelectedValue
  ComboBox1.DisplayMember = "name"; // column name that you need to display as text
Wellmannered answered 1/3, 2012 at 18:43 Comment(2)
ComboBox1.DataBind(); this doesnt exist. At least not in my version (visual studio 2010) ComboBox.DataBindings. and is not a method.Illsuited
DataBind() is for Web applications only; if it is a windows application that line is not neededWellmannered
S
2

They take strings...

ComboBox1.ValueMember = "id"; 
ComboBox1.DisplayMember = "name";
Strath answered 1/3, 2012 at 18:40 Comment(2)
mmm, nop! it doesnt work. U see, dataTable has values in it cuz i checked with the debbuger, those columns names are exactly id and name. if i put it like u did, the id is listed in the combobox, for some reason idk cuz names have names in it. And It never reach the displaymamber line.Illsuited
I think dataTable is not a valid source, i saw it with DataSource, but i dont have that :/, maybe i can parse the DataTable into a DataSource?Illsuited
D
2

I had the same trouble. In my case, SelectedIndexChanged event fires and just jumps out the method. Try do not use SelectedIndexChanged event. Or something like this:

ComboBox1.SelectedIndexChanged -= new System.EventHandler(ComboBox1_SelectedIndexChanged); 
ComboBox1.DataSource = dataTable; 
ComboBox1.ValueMember = "id";  
ComboBox1.DisplayMember = "name";
ComboBox1.SelectedIndexChanged += new System.EventHandler(ComboBox1_SelectedIndexChanged);

It worked for me. =)

Diligence answered 19/1, 2016 at 15:55 Comment(1)
That is a dangerous hack. You could use a Try ... Finally block to ensure that the event always gets turned back on. You could also set the DataSource last like the other answers.Armageddon
S
2
ComboBox1.ValueMember = dataTable.Columns["id"].ColumnsName;   // column name which the values are not visible 
ComboBox1.DisplayMember = dataTable.Columns ["name"].ColumnsName;
 /* 
       column name that you need to select item by proprity : 
ComboBox1.SelectedItem; 
Or   you can use easly this : 
ComboBox1.Text; 
*/

ComboBox1.DataSource= dataTable; //the data table which contains data 
// and this should be last :)
Scevour answered 19/1, 2018 at 13:51 Comment(1)
It worked for me ! Thank You. Can you please tell me more about .ColumnsName property and datatable.ColumnsBurgomaster
H
1
public class ComboDeger {
    private string yazi;
    private int deger;
    public ComboDeger(string stryazi, int strdeger) {
        this.yazi = stryazi;
        this.deger = strdeger;
    }
    public string yazisi {
        get {
            return yazi;
        }
    }
    public int degeri {
        get {
            return deger;
        }
    }
}
private void combobox_doldur() {
    ArrayList ComboDegerleri = new ArrayList();
    ComboDegerleri.Add(new ComboDeger("9 : NORMAL", 9));
    ComboDegerleri.Add(new ComboDeger("10 : ENGELLİ", 10));
    comboBox1.DataSource = ComboDegerleri;
    comboBox1.DisplayMember = "yazisi";
    comboBox1.ValueMember = "degeri";
}
private void Form3_Load(object sender, EventArgs e) {
    con.Open();
    combobox_doldur();

    // Populate the COMBOBOX using an array as DataSource.
}
Harvestman answered 12/12, 2014 at 22:52 Comment(1)
Your answer should contain an explanation of your code and a description how it solves the problem.Silk
M
0

you could specify like this

  ComboBox1.ValueMember = "id";  
  ComboBox1.DisplayMember = "name"; 
Mev answered 1/3, 2012 at 18:40 Comment(0)
S
0

Maybe not exactly the described issue but in my case the type name was shown in the ComboBox, not the DisplayValue, although everything seemed to be wired up correctly. It then turned out that the type's public properties were defined without getter and setter! :)

Steinbok answered 2/8, 2023 at 14:27 Comment(0)
H
0

by combining the given examples and adding the Select_Action for the ToolStripComboBox:

private void Combobox_SelectedIndexChanged(object? sender, EventArgs e)
{
    string colorIdx = ((System.Tuple<int, string>)((ComboBox)sender).SelectedItem).Item1;
    string colorName = ((System.Tuple<int, string>)((ComboBox)sender).SelectedItem).Item2;
}

private void AddItemsToComboBox()
{
    var myItems = new List<Tuple<int, string>>()
        {
            Tuple.Create(0, "Black"),
            Tuple.Create(1, "White"),
            Tuple.Create(2, "Red")
        };
    combobox.ComboBox.DataSource = myItems;
    combobox.ComboBox.ValueMember = "Item1";
    combobox.ComboBox.DisplayMember = "Item2";
}
Hyphen answered 10/3 at 5:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.