WinForms ListView - get source object from selected string item - c#

I am building a simple language learning helper application in WinForms. One of its modules is a dictionary. It consists of "Sets" and words are stored in a Set. User can create a new Set of words and store some of them in it.
I'm printing all the words from selected one or several Sets in a ListView with columns. Upon checking a Set or Sets in CheckedListBox the List clears and prints words (as string variables).
Trouble comes when there are few Sets checked with their words listed, and user wants to edit one of the listed words. I cannot use indexes (such as index of List item equals to word item in a Set), as those List string items are from different Sets.
Is there any way get a source object from a ListView item? I have not added objects to the list but only some of their variables, but are they somehow connected?
Thank you for your help.
Cheers!
EDIT: Explaining why to me setting a Tag is not a solution:
All the Sets are stored in a List<DictionarySet> dictionarySets. Every Set containts a List<Word> words where words are stored.
How do I fill the ListView:
private void UpdateList()
{
wordsListView.Items.Clear();
List<Word> currentSetWordList;
foreach (DictionarySet ds in setCheckedListBox.CheckedItems) //List<DictionarySets> dictionarySets inserted, DisplayMember set to its Name property
{
currentSetWordList = ds.words;
foreach (Word w in currentSetWordList)
{
ListViewItem newItem = new ListViewItem("--"); //for now a string, later an enum
newItem.Tag = ds;
newItem.SubItems.Add(w.GermanTranslation); //string property
newItem.SubItems.Add(w.PolishTranslation); //string property
wordsListView.Items.Add(newItem);
}
}
}
In this case the program loops through each Set and its word list and prints the words. Their tag is DictionarySet everywhere.

You could use the Tag property on the ListViewItem. The Tag property:
Gets or sets an object that contains data to associate with the item.
In short, when you create each item of the list view, you could add your object as the tag. This way you'll be able to get it back when the user selects an item.
See MSDN for details.

Related

SelectedItem of a variable combobox

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.

C# Combobox Displaying Blank Items

I'm coding a combobox in C# and for some reason the items in the drop down don't have text. When I have selected an item, it is shown in the combo box text field (the drop down list is always blank whenever I click the drop down button). The datasource seems bound properly because the proper values are being returned when I select items, and the size of the drop down list will change depending on how many items the datasource has. Everything looks fine except for the fact that it seems like my drop down is populated with a bunch of empty strings, which it clearly isn't since as soon as an item is selected the proper text will display.
This is the relevant code:
if (list.Count > 0)
{
cboCustomers.DisplayMember = "Name";
cboCustomers.DataSource = list;
cboCustomers.ValueMember = "ID";
cboCustomers.SelectedIndex = 0;
}
I have looked for an answer to this but can't find it anywhere...I'm sure it's something really simple, but I can't figure it out. The closest problem I found had an answer suggested to set the display member before the data source, which clearly didn't work.
The list is populated from a database query. This will run on keyUp, the idea is that the list is populated as the person is typing based on the info given. So if I wrote 'S' I'd get a combobox with a dropdown that had all the clients starting with 'S'.
Given you don't have any anomalies in your binding, you are probably being affected by DrawMode property of your ComboBox, which may be set to OwnerDrawFixed or OwnerDrawVariable. Set it to Normal and things should get better.
as soon as an item is selected the proper text will display.
A foreground color the same as the background color will produce the same results you are seeing.

What class to use for lookup value?

I am building a C# windows form that displays a listbox with some items to select from to a user. That selection will determine the criteria for a query. The query will return 2 fields, an ID and a description. I want to display the description in a second listbox on the form but use the ID for subsequent processing if that description is selected in the list box.
Here's some more details about what I am trying to do:
ListBox1
Accessories
Men's
Women's
Children
When the user selects 'Accesories' a query runs and returns:
1234 Belts
2345 Scarves
4566 Handbags
ListBox2 displays the descriptions
Belts
Scarves
Handbags
But when the user double clicks on Belts I want to add 1234 to a field in class instance. What kind of list should I put the results of the query into so that I can use it to add Items to my list box and still be able to know the ID?
Thanks!
Leslie
In the .NET list boxes, the item list is not just a list of strings, but objects. The component will use the string value of the object for display, but you can reference the ID when you look at the selected value.
Define a class thusly
class Choices
{
public string Name;
public int ID;
public override string ToString()
{
return name;
}
}
Populate the list with instance of this class, and you should be good to go.
Both WinForms and WPF are quite flexible. Just add the Accessory objects to the Items property. Or set DataSource to an existing list.
The default display is through ToString() but you can set DisplayMember to the name of a specific property.
You can get at the entire object through SelectedItem. And/or set ValueMember and read SelectedValue.

How to get elements from an object in C#?

I am using the AutoCompleteBox in WPF, I populate the suggestions with a List that consists of four fields. When the user selects an item and I reach my eventHandler, i can see that
MyAutoCompleteBox.SelectedItem
is an object that has my four values, if i hover this text in the debugger i can see the four values listed, however i don't know how to access these values in the code.
I tried
List<Codes> selected = MyAutoCompleteBox.SelectedItem as List<Codes>;
where Codes is my List. selected returns as null and empty every time. Is there a way to get to these values? Thanks!
If you want the listing of items used as the backing collection for the AutoCompleteBox try...AutoCompleteBox.ItemsSource.
Can you try:
Codes selected = MyAutoCompleteBox.SelectedItem as Codes;
or
Codes[] selected = MyAutoCompleteBox.SelectedItem as Codes[];
It means that you cannot convert whatever MyAutoCompleteBox.SelectedItem is to a List.

Working thru sample code

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.

Categories