Search code examples
c#for-looptext-comparison

C# for loops text compare


I'm trying to assign a combobox index by looping through the values and finding the one that matches my diameter variable. (the combobox items change based on the diameter, e.g. some pipe types only have 0.5", 1.0" while others may have an intermediate 0.75" value).

The code comparison never seems to go true (so myIndex is never assigned anything outside of the initialization) although when I put a breakpoint on it, the text strings match at the appropriate iteration.

int myIndex = 0;

for (int i = 0; i <= cboDiameter.Items.Count-1; i++)
{
    if (cboDiameter.GetItemText(cboDiameter.Items[i]) == formPipe.diameter.ToString()) 
    {
        //this line never executes, even when there's seemingly a text match
        myIndex = i;
    }
}
cboDiameter.SelectedIndex = myIndex;

This is what I'm using to assign the pipe diameter, but it's being truncated. (e.g. when the combobox text is "1.0", the pipe diameter is being assigned "1"

//assign the value of the dropdown to the object
double.TryParse(cboDiameter.GetItemText(cboDiameter.SelectedItem), out value);
formPipe.diameter = value;

Solution

  • Not 100% sure why the double was being truncated to an integer, but to fix it I parsed the combobox value to another double and just compared the two doubles instead of comparing strings:

    for (int i = 0; i <= cboDiameter.Items.Count-1; i++)
                    {
                        double.TryParse(cboDiameter.GetItemText(cboDiameter.Items[i]), out val);
                        if (val == formPipe.diameter)
                        {
                            myIndex = i;
                        }
                    }