Reputation: 318
I have the following problem: I want to check if the reservation number already exists in my listview.
I have the following code to add a reservation to the listview.
reservations.Add(new Reservation(nameTextbox.Text, lastnameTextBox.Text, gendercomboBox.SelectedText, Convert.ToInt32(ageNumericUpDown.Value), Convert.ToInt32(kamercomboBox.SelectedIndex) + 1, Convert.ToInt32(quantityUpDown.Value), true));
reserveringListView.Items.Clear();
foreach (Reservation reservation in reservations)
{
if (!reserveringListView.Items.Contains(reservation.roomnumber))
{
ListViewItem livi = new ListViewItem(reservation.name);
livi.SubItems.Add(reservation.lastname);
livi.SubItems.Add(Convert.ToString(reservation.gender));
livi.SubItems.Add(Convert.ToString(reservation.age));
livi.SubItems.Add(Convert.ToString(reservation.quantity));
livi.SubItems.Add(Convert.ToString(reservation.roomnumber));
reserveringListView.Items.Add(livi);
}
else
{
MessageBox.Show("Its impossible to reserve")
}
}
When i try to test this code i get the following error: Cannot convert from int to System.Windows.Forms.ListViewItem
Upvotes: 1
Views: 825
Reputation: 2876
List<T>.Contains
(docs) method expects an argument of type T
(System.Windows.Forms.ListViewItem
) in your case. But you try to pass an int
to that method. Thats why you get the error.
In your case I would create a HashSet<int>
and store reservation.roomnumber
in it, so you can look up next time, if the roomnumber
is already there.
Example:
reserveringListView.Items.Clear();
HashSet<int> roomCheck = new HashSet<int>();
foreach (Reservation reservation in reservations)
{
if (roomCheck.Add(reservation.roomnumber))
{
...
}
}
EDIT: added an example
Upvotes: 0
Reputation: 12171
You should change your if
statement, because you check if ListView.Items
contains int
. You can't do this and, also, inside if
you add roomnumber
as string
(but you check if it is in ListView.Items
as int
). Your if
statement should be:
if (!reserveringListView.Items.Cast<ListViewItem>().Any((i) => i.SubItems[5].Text == Convert.ToString(reservation.roomnumber)))
Maybe I made mistake with index in SubItems
. You should check it and if there is mistake write a comment please.
Upvotes: 2
Reputation: 1217
You are getting the error because you are giving the .Contains method an int parameter, while it only accepts a ListViewItem as parameter
try something like:
if (!reserveringListView.Items.Any(litem => litem.SubItems[5].Value == reservation.roomnumber))
{
}
Upvotes: 1