Adam Rackis
Adam Rackis

Reputation: 83356

Windows Forms ComboBox - case insensitive data-binding

If I'm databinding a winforms combo box, is there a way to make the binding case insensitive?

For example if the combo box is bound to a property whose value is FOO, get it to select combo box item with value of Foo?

Upvotes: 3

Views: 2952

Answers (2)

MCattle
MCattle

Reputation: 3167

A little late to the game, but here's what I've done to allow case insensitive binding to a WinForms ComboBox:

I've created my own class that inherits from ComboBox, and have added the following property to bind my data to (pardon the auto-conversion from VB.NET):

public object Value {
    get {
        if (string.IsNullOrEmpty(ValueMember)) {
            return Text;
        } else {
            return SelectedValue;
        }
    }
    set {
        if (DesignMode)
            return;

        // If we're databound, Value is the SelectedValue.  Otherwise, it's the Text.
        object oldValue = string.IsNullOrEmpty(ValueMember) ? Text : SelectedValue;

        // Want to make sure we're comparing apples to apples, and not specific instances of apples.
        string strOld = oldValue == null ? string.Empty : Convert.ToString(oldValue);
        string strNew = value == null ? string.Empty : Convert.ToString(value);

        if (!string.Equals(strOld, strNew, StringComparison.OrdinalIgnoreCase)) {
            if (ValueMember.HasValue) {
                if (value != null && !string.IsNullOrEmpty(Convert.ToString(value))) {
                    SelectedItem = Items.OfType<object>.FirstOrDefault((System.Object i) => string.Equals(Convert.ToString(FilterItemOnProperty(i, ValueMember)), strNew, StringComparison.OrdinalIgnoreCase));
                } else {
                    SelectedIndex = -1;
                }
            } else {
                Text = value != null ? value.ToString : string.Empty;
            }
            ValidateField();
            if (PropertyChanged != null) {
                PropertyChanged(this, new PropertyChangedEventArgs("Value"));
            }
        }
    }
}

ValidateField is a custom method that you can probably ignore, but you'll want to implement INotifyPropertyChanged for the Value property.

Upvotes: 2

Aliostad
Aliostad

Reputation: 81660

No it is not possible. This is internally implemented using reflection which is case-sensitive.

Upvotes: 4

Related Questions