I am currently working on a home project. Basically I have a list that is being used to load data from the database. That works fine, data is being loaded to a list and from that list I am able to populate the list view control.
Now I am trying to create a filter that will simply filter the list view based on user input in text box. So I have a list view:
Name Surname Address
Tom Nah 1
Kerrt Nah 2
Robert Dell 3
How to do it so that whatever user enters in a textbox and click a button event, It will filter through the whole list and based on the user input return only the items that they were searching for. For example, if they search for Surname 'Nah', it will display the whole row of Tom and Kerry because they both contain surname 'Nah'
NOTE: There are 3 text boxes each of them is used for specific row. So txtName, txtSurname and txtAddress.
What I have tried:
I have tried to Filter through schemes like that:
private List FilterPeople()
{
List filteredPeople = new List();
string Name= txtName.Text.ToLower();
string Surname= txtSurname.Text.ToLower();
string Address = txtAddress.Text.ToLower();
listView.Items.Clear();
foreach (var person in _people)
{
if (!string.IsNullOrEmpty(Name) || !string.IsNullOrEmpty(Surname) ||
!string.IsNullOrEmpty(Address))
{
if ((!person.Name.ToLower().Contains(Name)) ||
(!person.Surname.ToLower().Contains(Surname)) ||
(!person.Address .ToLower().Contains(Address)))
{
continue;
}
}
filteredPeople.Add(person);
}
return filteredPeople;
}
The problem is that filteredPeople is always 0. It did actually hit 'continiue' whenever I put a breakpoint on it and it seems that it found surname 'Nah'. But for some reason I don't know what it is returning 0 in filteredPeople.
This is my click event button:
private void btnApplyFilters_Click(object sender, EventArgs e)
{
foreach (var person in FilterPeople())
{
AddToListView(person);
}
}
Add to list view method:
private void AddItemToListView(Person person)
{
ListViewItem lv = new ListViewItem(person.Name);
lv.SubItems.Add(person.Surname);
lv.SubItems.Add(person.Address);
lvLog.Items.Add(lv);
}
Any help would be appreciated.
Thanks