I have a combobox and the items of the group membership look like
- 200;Heater
- 300;Cooler
- 400;Fan
If I select a part, only the number of the membership e.g. 200 is stored in the database.
Now I want to do a pre selection of the combobox. To check if the combobox contains a membership number is working.
void MembershipPreSelection(ComboBox cb, string text)
{
if (cb.Items.Cast<Part>().Any(c => c.Membership.Contains(text)))
{
// now I want the string for the item that contains the text.
}
}
But to get the text of the combobox item (e.g. 200;Heater)?? This is what I tried, but I do not get the item text.
string m = cb.Items.Cast<Part>().Where(c => c.Hauptbaugruppe.Contains(text)).ToString();
CodePudding user response:
The biggest issue seems to be using Where
in your Linq
statement which will return a collection of Part
. Then, when the ToString()
is called on the result, it's probably is something cryptic like:
System.Linq.Enumerable WhereEnumerableIterator`1[your_namespace.Part]
To fix, consider something like First
or Single
in place of Where
to return a single item.
string m =
cb.Items.Cast<Part>().Single(c => c.Hauptbaugruppe.Contains(text)).ToString();
You've probably already done this, but make sure that you have an override to Part.ToString()
that returns the format that you want.
// Example Part class
class Part
{
public int ID { get; set; } = 0;
public string Description { get; set; } = "New Item";
// What do you want to see for `Part.ToString()`
public override string ToString()
{
return $"ID: {ID} Description: {Description}";
}
}