SelectedItem of a variable combobox - c#

There is a combobox which i fill with this loop
foreach (Machine.Types machine in machineList)
{
cbMachineGUI.Items.Add(machine);
}
after that i want the selected index to be one specific machine.
string machineComboBox = SettingsManager.getParameter("MachineType");
cbMachineGUI.SelectedItem = machineComboBox;
The parameter is correct and set, but the selecteditem of the combobox is always nothing.
if i set the machines in the properties of the combobox (not via the loop) it works. but i need the combobox to be variable.
any suggestions?

The problem is that what you put in Items and what you set SelectedItem to are different types.
You are filling the Items collection with Machine.Types instances, and setting SelectedItem to a string instance.
Using IndexOf like other answers suggest will not help, as this will not do anything that setting SelectedItem does not already do. It still won't find machineComboBox in the Items collection, just like it can't find it now.
You need to use matching types, so do one of these things (depending on how else you use the values in the combobox):
Convert Machine.Types to a string when filling the collection:
cbMachineGUI.Items.Add(machine.ToString());
Convert machineComboBox into an instance of Machine.Types that will match the one in Items when setting SelectedItem - how to do it depends on what Machine.Types is
Find the correct item yourself when setting SelectedItem:
cbMachineGUI.SelectedItem = cbMachineGUI.Items
.OfType<Machine.Types>()
.FirstOrDefault(item => item.ToString() == machineComboBox);
Either way, you must make a conversion between these two types somewhere.

Instead of setting SelectedItem, I suggest you find the item's index and set the selected index.
Something like this:
string machineComboBox = SettingsManager.getParameter("MachineType");
int itemIndex = cbMachineGUI.Items.IndexOf(machineComboBox);
cbMachineGUI.SelectedIndex = itemIndex;

You could try the following:
cbMachineGUI.SelectedIndex = cbMachineGUI.Items.IndexOf("MachineType"); // or whatever you want to select

It could be possible that the item you are trying to set doesn't present in combobox item list and since you haven't actually selected anything it sets to nothing. To check if the item does exist do below
string machineComboBox = SettingsManager.getParameter("MachineType");
if(cbMachineGUI.Items.IndexOf(machineComboBox) >= 0)
cbMachineGUI.SelectedItem = machineComboBox;
Quoting from MSDN documentation:
When you try to set the SelectedItem property to an object, the
ComboBox attempts to make that object the currently selected one in
the list. If the object is found in the list, it is displayed in the
edit portion of the ComboBox and the SelectedIndex property is set to
the corresponding index. If the object does not exist in the list, the
SelectedIndex property is left at its current value.The ComboBox class
searches for the specified object by using the IndexOf method.
Check ComboBox.SelectedItem for more information.

Related

Combobox.SelectedValue wont select the actual value

I have a problem that I'm struggling with.
I fill a combobox this way:
RDTA_cb_provincias.DataSource = provincias;
RDTA_cb_provincias.DisplayMember = IdiomaBD.ObjCI.ToString().Equals("eu-ES")
? "TTEXNOMBRPROV_EU"
: "TTEXNOMBRPROV_ES";
RDTA_cb_provincias.ValueMember = "TCODIDTERRITORIO";
There's some stuff depending on the language of the user, but i guess that's not important here.
Well, when i want to select depending on the value member i do this:
RDTA_cb_provincias.SelectedValue = provincia2.TCODIDTERRITORIO;
But for some reason it won't show up the actual item I want to show. While debugging i can see that RDTA_cb_provincias.SelectedValue matches provincia2.TCODIDTERRITORIO.
For example, I've set SelectedValue to 51, but when i see the SelectedItem inside the ComboBox once I've changed the value, It shows up an object that has 47 as its TCODIDTERRITORIO.
What can it be? Or how can I bypass this problem (Maybe iterating the whole ComboBox item list until i find the one i want to select?)
Thanks in advance!
You should use SelectedItem instead:
RDTA_cb_provincias.SelectedItem = provincia2;
Or you can use SelectedIndex as follows:
RDTA_cb_provincias.SelectedIndex = RDTA_cb_provincias.FindStringExact(provincia2.TCODIDTERRITORIO)

Struct & Enum, Combobox.SelectedItem

The program is a minidatabase-ish thing for product ordering purposes, where I keep the unique orders in a struct, and the productNames in an enum (for practice basically). I only have 3 productnames (Product0, Product1, Product2), and they are added to a combobox (cbo_productNameEdit.DataSource = Enum.GetNames(typeof(productNames));).
Anyway, after saving an order, I want this combobox to change it's selected item to the saved product's name, but it fails to do so. I checked it with a MessageBox, to see if it didn't store it properly...
MessageBox.Show(Orders[cbo_productID.SelectedIndex].productName.ToString());
cbo_productNameEdit.SelectedItem = Orders[cbo_productID.SelectedIndex].productName;
... the messagebox returned Product2, which is indeed the correct one, but the selected item stayed at Product0.
One thing you could do to solve it is to set the SelectedIndex instead of SelectedItem property on the combobox. By default Enums are 0 based integers, so the index will corespond to the value of the enum.
cbo_productNameEdit.SelectedIndex = (int)Enum.Parse(typeof(productNames),
Orders[cbo_productID.SelectedIndex].productName.ToString());
Because you used .DataSource property for filling ComboBox with items
You need to use .SelectedValue for setting selecting item
cbo_productNameEdit.SelectedValue = Orders[cbo_productID.SelectedIndex].productName;
From MSDN: ComboBox.SelectedValue

Combobox SelectedItem does not work

I have the code below
FooCB.DisplayMember = "FooNome";
FooCB.ValueMember = "Foo";
FooCB.DataSource = FooRepository.Instance.All();
FooCB.DataBindings.Add("SelectedItem", Bar, "Foo");
but when I display the form the SelectedItem is always the first.
What am I doing wrong?
I have been struggling a little with the behaviour of Winforms comboboxes and databinding recently and these are my observations (.Net4) when binding the ComboBox.DataSource to a list of items and also binding an object property to ComboBox.SelectedItem.
When binding a list of objects (in your case List<Foo>) to ComboBox.DataSource, the first object in the list is always shown in the combobox.
If you bind an object property to ComboBox.SelectedItem (in your case Bar.Foo) and that object property matches one of the combobox list objects then that object is displayed in the combobox. If the object property is null (Bar.Foo == null) or the object property is not in the combobox list then the first object is shown in the combobox.
Setting ComboBox.SelectedItem = null or ComboBox.SelectedIndex = -1 clears the displayed item on the combobox even though this seems to warn against it. And will set your bound object property to null.
If a user clears the combobox selection when using ComboBox.DropDownStyle == DropDown (with backspace) then the bound object property is set to null.
If you have implemented INotifyPropertyChanged on the object whose property is bound to Combobox.SelectedItem (Bar.Foo) and you programatically set the bound property to a value and that value appears in the combobox list then the changed value will be displayed. If you set the property to null or a value not in the list then the combobox displayed value will not change.
So what can you do about it? The only real issue I have is having no value displayed when my bound property is null so I have just been explicitly setting Combobox.SelectedItem = null as in point #3. You may be able to extend ComboBox and override the default behaviour but so far I have been content with an extra line of code here and there combined with using default values on non-nullable properties.
Probably you are missing some decleration. If you created the Combobox from the Tool Box, -I had the similar problem- you might want to add name of the Combobox's Name as a tag on XAML.
Other than that, if you created it dynamically by code, check if you are missing any decleration for class.
I can't tell from the OP's code whether I'm answering their question, but maybe this will help somebody reading this question. The ComboBox has four ways to set the current value:
SelectedIndex
SelectedItem
SelectedText
SelectedValue
You need to be consistent about what you're setting (and about which event handler you're using). You'll get an error if you set SelectedIndex to something dumb (less than -1 or longer than the list). However, you don't get errors setting the other three to something that doesn't exist for that type of selection.
Suppose you use a Dictionary (that's pseudo code) as a binding source and set DisplayMember = "Value" and ValueMember = "Key", the mapping would look like:
SelectedIndex - -1 to index of last item
SelectedItem - KeyValuePair<Key, Value>
SelectedText - Dictionary value
SelectedValue - Dictionary key
Supplying either value or key to SelectedItem will not generate an error, it will simply act like the OP has described. And that's why I thought this answer might help somebody.
I might also note that, if you're swapping out the contents of the ComboBox, it's not always safe to use SelectedIndex. Suppose the same basic kind of data is in the ComboBox, but selections are limited in some cases compared to others. Using SelectedIndex to persist a previous selection that was still valid in the new list of options is only going work if that previous selection held the exact same place in the list. You'd almost think this was the voice of very, very recent experience speaking...

C# Winforms - How can I dynamically set the selectedItem of combo box?

I cannot seem to figure out how to dynamically change the selected item in a combo box. I am trying this:
myComboBox.SelectedItem = item.Id;
Here item.Id is a int that corresponds to valid ValueMember that is bound to the combobox. However the combobox remains unchanged. I have trying invalidating the control after changing the selected item. What's the trick?
Thanks
try SelectedValue instead..
myComboBox.SelectedValue = item.Id;
You can use either of these:
SelectedIndex Property
ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index. If the object does not exist in the list, the SelectedIndex property is left at its current value.
SelectedItem Property
Get or Set A zero-based index of the for selected item.

C# ComboBox String value to object variable to class?

I'm attempting to take a string value from a Combo box then pass it through an object variable to a class and store it there in a string variable.
private void cboTimeZone_SelectedValueChanged(object sender, EventArgs e)
{
extTime1.timeZone = cboTimeZone.SelectedItem;
}
I'm not totally use to the combo box options to use so.
Does the cboTimeZone contain string objects? In this case, a simple cast should be enough if extTime1.timeZone is a string:
extTime1.timeZone = (string)cboTimeZone.SelectedItem
if cboTimeZone was filled with objects of type myObject, u can use the ToString() method on the item if you overwrote it in your myObject class:
extTime1.timeZone = cboTimeZone.SelectedItem.ToString()
If you selected a specific property MyProperty of myObject to be shown in the combo box, you can first cast to the object and then access the property by using
extTime1.timeZone = ((myObject)cboTimeZone.SelectedItem).MyProperty
to get that property as a result.
Hope that helps.
It's not clear from your question whether your ComboBox is data-bound or not; either way, I think it would be a good idea to first figure out if SelectedItem is indeed the correct property to use, or if there's another, more appropriate one.
If you've set a DataSource for your ComboBox, you've probably also set a DisplayMember. In that case, the DisplayMember will determine which property of the currently selected item of the data source will be shown in the ComboBox as text.
If you've set a ValueMember, you can also use the SelectedValue property to retrieve that property of the currently selected data source item.
SelectedItem simply retrieves the currently selected data source item. This may be a complex object, or a string object, or something else; check with your data source.
The ComboBox's Text property simply contains the text that's currently displayed in the ComboBox's text input field and has type string.

Categories