1

I am working on some homework for class, and decided to add some extra stuff, and wound up confusing myself a bit. I have tried various comparison methods, and none of them seem to work, but I don't understand why.

Basically when an order is added to the system, it creates an instance of the class 'OrderInfo', and adds it to an ArrayList. In my code, I am using a foreach() loop to find the class instance that matches which entry in the ListBox they clicked, but something is wrong.

private void ordersListBox_DoubleClick(object sender, EventArgs e)
{
    if (ordersListBox.SelectedItem != null)
    {
        foreach (OrderInfo i in ordersList)
        {
            if (String.Compare(i.GetClientName(), ordersListBox.ToString(), true) == 0)
            {
                MessageBox.Show(i.GetClientName());
                break;
            }
        }
    }
}
1
  • do you really mean ordersListBox.ToString()? By default, this will not return the text of the selected item. Commented Feb 13, 2011 at 21:28

5 Answers 5

4

Instead of

 if (String.Compare(i.GetClientName(), ordersListBox.ToString(), true) == 0)

try

 if (String.Compare(i.GetClientName(), ordersListBox.SelectedValue.ToString(), true) == 0)
Sign up to request clarification or add additional context in comments.

Comments

0

For String comparisons it is better to use the Equals() method.

private void ordersListBox_DoubleClick(object sender, EventArgs e)
{
    if (ordersListBox.SelectedItem != null)
    {
        foreach (OrderInfo i in ordersList)
        {
            if (i.GetClientName().Equals(ordersListBox.ToString()))
            {
                MessageBox.Show(i.GetClientName());
                break;
            }
        }
    }
}

Comments

0

String.Compare returns a number, not a boolean.
The number will be positive, negative, or zero, depending on the relative alphabetical ordering of the strings.

You should call String.Equals, and pass StringComparison.OrdinalIgnoreCase.

Comments

0

I doubt you really want to compare the string representation of the ordersListBox to some sensible string.

The default implementation of ToString() of any object is to output the name of the type of the instance. The ordersListbox most likely is doing just that. You will want to consult the SelectedValue.

Comments

0

You can also try this one.

 if (String.Compare(i.GetClientName(), ordersListBox.SelectedValue.ToString(), StringComparison.InvariantCultureIgnoreCase) == 0)
        {
            MessageBox.Show(i.GetClientName());
            break;
        }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.