Kohnarik
Kohnarik

Reputation: 377

Select ComboBox.Item by string

I have a combobox called comType_1, which contains certain selectable strings. I have a variable k.Type_1, which contains the desired string.

Example:

k.Type_1 contains "Test". comType_1 contains an Item called "Test". How do I select this item?

I've tried multiple things, and none of them worked:

comType_1.SelectedValue = k.Type_1;
comType_1.SelectedValue = comType_1.Items.IndexOf(k.Type_1);
comType_1.SelectedItem = comType_1.Items.Equals(k.Type_1);

I'm using Visual Studio 2015 Community and this application is a WPF-application.

Upvotes: 1

Views: 2395

Answers (2)

Rachel
Rachel

Reputation: 132648

You said the ComboBox Items are Objects, while you are trying to set the SelectedValue to a string.

A ComboBox compares items by reference when trying to set the SelectedItem, so your string is never going to match the Objects in the ComboBoxes.

I'd recommend setting the SelectedValuePath to the property on your object containing the string, and then you can set the SelectedValue to a string as well.

public class MyObject()
{
    public string Name { get; set; }
}
<ComboBox x:Name="comType_1" ItemsSource="{Binding MyCollection}"
          SelectedValuePath="Name" DisplayMemberPath="Name" />
comType_1.SelectedItem = "Test";

As an alternative you could overwrite the .Equals of your object so it correctly compares against a string and returns true (not really recommended, and if you do you probably want to overwrite GetHasCode() as well)

public class MyObject()
{
    public string Name { get; set; }

    public override bool Equals(object obj) 
    { 
        if (obj == null) 
            return false; 

        if (obj is string)
            return (string)obj == this.Name;

        if (obj is MyClass)
            return ((MyClass)obj).Name == this.Name); 

        return false;
    }
}

A third option would be to cast your ComboBox Items into your objects and check against your string for the correct object, then set SelectedItem

var items = comType_1.Items as ObservableCollection<MyObject>;
if (items == null)
    return;

foreach(MyObject item in items)
{
    if (item.Name == k.Type_1)
    {
        comType_1.SelectedItem = item;
        break;
    }
}

Of the 3 options, I'd recommend the first one.

Upvotes: 0

EylM
EylM

Reputation: 6103

First you need to update the ComboxBox-Tag to include the SelectedValuePath=Content,

Example:

<ComboBox Name="combo1" SelectedValuePath="Content">

Then you can perform the assignment:

  comType_1.SelectedValue = k.Type_1;

Upvotes: 1

Related Questions