How can I copy a collection of items in a comboBox to a StringCollection in my C# application? I'm only interested in capturing the string text for each item in their respective order. I am trying to make a MRU file list that is saved between sessions, so I would like to copy comboBox.Items to StringCollection Properties.Settings.Default.MostRecentlyUsedHexFiles. Any thoughts or suggestions you may have would be appreciated. Thanks.
You should be able to loop over the combobox.items and simply use stringcollection.Add() to add the string to the collection.
The tostring method will perform as described here:
Although the ComboBox is typically
used to display text items, you can
add any object to the ComboBox.
Typically, the representation of an
object in the ComboBox is the string
returned by that object's ToString
method. If you want to have a member
of the object displayed instead,
choose the member that will be
displayed by setting the DisplayMember
property to the name of the
appropriate member. You can also
choose a member of the object that
will represent the value returned by
the object by setting the ValueMember
property. For more information, see
ListControl.
So something like:
Foreach(object o in combobox.items)
{
//might need to access a datamember of the combobox's item if more complex solution is required, but this will probably do
stringcollection.Add(o.ToString);
}
Related
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.
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...
I have a simple 3-column ListView. This control is programatically populated with data from a collection (a generic List) I'd like to use double click event on every row in this ListView to open another form. This form will display data which are in clicked row and will be also used to edit these data so I need access to proper object in collection. But I have no idea how to make a some sort of connection between a row in ListView and specific object in collection.
Use the Tag property, which exists exactly for that purpose.
From MSDN:
Gets or sets an object that contains data to associate with the item.
To retrieve the data object, just cast the Tag property to the type of the object.
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.
I am trying to work thru some sample code.
The code I am having a problem with is:
private ListControl GetSelectedList()
{
return (ListControl)FindControl(ddlControls.SelectedItem.Value);
}
ddlControls is a DropDownListBoxControl collection
What does the ddlControls.SelectedItem.Value return (its a numeric value, but I don't know what it represents)?
2nd question: What is return (ListControl)FindControl(ddlControls.SelectedItem.Value); ?
Thanks
SelectedItem.Value, as the name suggests, is the value of the currently selected item in the drop-down list. For example, if this were a list of months and someone had selected "September", this property has the value "September".
what is return (ListControl)FindControl(ddlControls.SelectedItem.Value);
FindControl is a method that looks up controls by their id. Using our example from before, it would try to find a control with the name "September". The (ListControl) at the beginning is a cast; the GetSelectedList() method is implicitly assuming that every possible answer you could get from ddlControls is the name of another ListControl. (This might not be a good idea depending on the circumstances.)
The result -- that is, the control whose id is the same as the currently selected value in ddlControls -- is then returned, and that's the result of GetSelectedList().
DropDownList Class in MSDN has the answer to the first question. In particular, it links to ListControl.SelectedItem, which is defined as:
If the list control allows only a single selection, use this property to get the individual properties of the selected item. If the list control allows multiple selections, use this property to get the properties of the lowest indexed item selected from the list control.
Similarly, Control.FindControl gives the answer to your second question. It's defined as:
Searches the current naming container for a server control with the specified id parameter.