1
I am creating a (several) combobox at Runtime and trying to manually set a SelectedValue 'standard', but I realized that even manually setting a value that exists inside the combo nothing is selected.
I’ve already checked if the data type matches (both are long).
Below the code in which I create the combo:
ComboBox cmb = new ComboBox()
{
DropDownStyle = ComboBoxStyle.DropDown,
BackColor = Color.FromArgb(210, 211, 213),
ForeColor = Color.Black,
Location = new Point(5, y),
Size = new Size(265, 10),
Font = new Font("Verdana", 11f, FontStyle.Regular),
FlatStyle = FlatStyle.Popup,
AutoCompleteMode = AutoCompleteMode.SuggestAppend,
AutoCompleteSource = AutoCompleteSource.ListItems,
Tag = null
};
cmb.DataSource = null;
cmb.ValueMember = "Id";
cmb.DisplayMember = "Login";
cmb.DataSource = UsuarioDB.FindAll().Where(x => x.Id > 0).OrderBy(x => x.Login).ToList();
cmb.SelectedValue = (long)1; //Aqui estou setando manualmente o valor para testar
There are three important things to score:
- Debugging the code I see that property
DataSourceis correct with all records, however the propertyItemsis empty; - Even with the property
Itemsempty, the combo shows the values exactly as I need (I mean, running) and when changing the selected value and try to capture bySelectedValuethe value comes right. - In the same form is created a combobox (this in time design), where I also serve the
SelectedValuemanually, but this works right.
Any idea what it might be?
Instead of
SelectedValuebecause it does not useSelectedIndex?– Felipe Douradinho
Because I need to select based on
ValueMemberwhich is the Id.– Jéf Bueno
Just for the record, you want to select an item in the combo based on its value which is a
longresulting fromDataSource, correct?– Felipe Douradinho
Correct @Felipedouradinho
– Jéf Bueno
I particularly use it this way when I associate a
DataSourceto Combobox:cmb.SelectedIndex = cmb.Items.IndexOf(UsuarioDB.Where(x => x.Id == 1).FirstOrDefault());– aleDsz
Nah, the problem doesn’t have to do with it. By the way, do you make an appointment at the bank just to validate it? It seems unnecessary.
– Jéf Bueno