sab669
sab669

Reputation: 4104

Why is this IndexOf call returning -1?

I understand that IndexOf returns -1 when the parameter isn't found, but this doesn't make sense to me.

I have this code that iterates over all the DevExpress Checkboxes on my form, checks to see what their tag is, and tries to find it in the "filter" parameter that was passed to the method. If the tag is found in the filter, it should check that checkbox. It is always equating to false.

    public void FilterChanged(Control.ControlCollection controls, string filter)
    {
        filter = filter.Replace("[", String.Empty);
        filter = filter.Replace("]", String.Empty);

        foreach (Control control in controls)
        {
            if (control is CheckEdit && control.Tag != null)
            {
                var c = (CheckEdit)control;
                var cFilter = c.Tag.ToString();
                cFilter = cFilter.Replace("(", String.Empty);
                cFilter = cFilter.Replace(")", String.Empty);

                if (filter.ToUpper().IndexOf(c.Tag.ToString().ToUpper()) >= 0)
                    c.Checked = true;
                else
                    c.Checked = false;
            }
        }
    }

I set a breakpoint on my inner IF statement, and in my Immediate Window I entered the following:

filter.ToUpper().IndexOf(c.Tag.ToString().ToUpper()) = -1

filter.ToUpper() = "FILE NOT LIKE '%VERSIONINFO.CS%'"

cFilter.ToUpper() = "FILE NOT LIKE '%VERSIONINFO.CS%'"

Those look like pretty much the exact same thing, so shouldn't it be returning 0?

I cannot use equals because the filter might include multiple clauses, and thus wouldn't be equal.

Upvotes: 1

Views: 283

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460018

cFilter.ToUpper() = "FILE NOT LIKE '%VERSIONINFO.CS%'"

Those look like pretty much the exact same thing, so shouldn't it be returning 0?

But you are using c.Tag.ToString() instead of cFilter.ToUpper().

So this should work as expected:

if (filter.ToUpper().IndexOf(cFilter.ToUpper()) >= 0)
    c.Checked = true;
else
    c.Checked = false;

Note that you should use StringComparison.OrdinalIgnoreCase instead in IndexOf

c.Checked = filter.IndexOf(cFilter, StringComparison.OrdinalIgnoreCase) >= 0;

Upvotes: 8

Related Questions