L.Verbree
L.Verbree

Reputation: 13

C# How to check a Listbox for a string + object?

I'm trying to search for a certain number(object) in a listbox which comes together with a string in order to highlight it. In the following bit of code i override a ToString() method to contain all my objects.

 public override string ToString()
    {

        string reservatiestring;
        reservatiestring = "Kamer: " + roomNumber + "" + "  Op datum: " + datum + "  Aantal personen: " + personen.Count + "  Naam: " + reservatienaam;
        return reservatiestring;
    }

Following this I add it to my listbox in the following bit of code:

 listBox1.Items.Add(reservatie.ToString());

I now want to search for all the items in my listbox containing the same roomNumber object. To do this i tried the Contains() method with the text before it: "Kamer: " and the object which I'm looking for +comboBox1.SelectedItem. This however always fails and my code goes to the else option giving me the error message.

private void buttonSearch_Click(object sender, EventArgs e)
    {
        listBox1.SelectionMode = SelectionMode.MultiExtended;
        Reservations reservaties = new Reservations();

        reservaties.roomnumberstring = "Kamer: " + comboBox1.SelectedValue;

        for (int i = listBox1.Items.Count - 1; i >= 0; i--)
        {
            if (listBox1.Items[i].ToString().ToLower().Contains(("Kamer: " + comboBox1.SelectedValue)))
            {
                listBox1.SetSelected(i, true);
            }
            else
            {
                MessageBox.Show("error");
            }
        

Please note: All my roomNumber objects are stored in the combobox, so whenever i select for example roomNumber 3 in my combobox and hit search all the items in the listbox containing "Kamer: 3" should be selected.

The roomnumberstring is a option I tried which did not work unfortunately.

reservaties.roomnumberstring = "Kamer: " + comboBox1.SelectedValue;

Upvotes: 0

Views: 187

Answers (2)

Mikael Puusaari
Mikael Puusaari

Reputation: 1034

I can see one thing that might make your code fail. you are comparing

.ToLower()

with "Kamer", where the "K" isn´t in lowercase

Upvotes: 0

Brendan Long
Brendan Long

Reputation: 286

Your override of the ToString method is wrong and won't modify anything. Try this :

public override string ToString(this string reservatiestring)
{

    reservatiestring = "Kamer: " + roomNumber + "" + "  Op datum: " + datum + "  Aantal personen: " + personen.Count + "  Naam: " + reservatienaam;
    return reservatiestring;
}

Upvotes: 0

Related Questions