I have 2 Listbox and I want to check the first Listbox text so that I can add them to the second Listbox. Like, let's say that I have a car registration plate on the first Listbox ( 02-TH-93 ) and now I want to add on my second Listbox that same plate ( 02-TH-93 ) BUT if that plate doesn't exist on the first ListBox then it should just show a message error.
For example:
ListBox1: 02-TH-93 | 06-JK-58 | 07-HJ-95 | 02-FG-56
ListBox2: 02-TH-93 | 06-JK-58 | 07-HJ-95 | 45-ER-01 (Show message error now because there's no match of this registration plate on listbox1)
I tried this but it doesn't really make a lot of sense I guess:
parking.Entrance = textBoxEntrance.Text;
parking.Exit = textBoxExit.Text;
if(parking.Entrance == parking.Exit)
{
listBoxExit.Items.Add("Plate: " parking.Exit " Exited ");
}
Thanks
CodePudding user response:
I assume that your Listbox.ItemsSource
is a list of strings so you could just loop through one of those lists and look for a match like this:
private bool IsInFirst(string plateToAdd, List<string> plates)
{
foreach(string plate in plates)
{
if (plate.Equals(plateToAdd))
{
return true;
}
}
return false;
}
If it returns true
the list contains the plate to add and if it returns false
it doesn't. This tutorial helped me.
CodePudding user response:
I have created a variate as I understand it, so it asks if the "plate" is present in lb1. If yes then add it if not ignore it and make a message box
private bool ExistsCheck(string newPlate, List<string> allPlates)
{
bool result = false;
foreach (var plate in allPlates)
if (plate.Equals(newPlate))
result = true;
return result;
}
private void AddAndCheck_Click(object sender, EventArgs e)
{
List<string> allPlates = new List<string>();
for (int i = 0; i < lb1.Items.Count; i )
allPlates.Add(lb1.Items[i].ToString());
if (ExistsCheck(tb_plate.Text, allPlates))
{
// If its return False
lb2.Items.Add(tb_plate.Text);
}
else
{
// If its return True
MessageBox.Show("It is not present in listbox 1");
}
}