Reputation: 5242
I have a DataGridView
that is filled with objects, now I want a search/filter-function for this DataGrid
. I'm trying to use a textbox where you can enter a textstring and in my head a want to match this string against all the object fields (for example if the objects are Emails, I want to match the string against the Subject field) in the DataGrid.
If it is to any help the DataGrid.DataSource
is declared like this (don't worry about the methods, the problem is the filter/search-function):
var newMess = LM.GetNewMessages();
if (newMess.Count > 0)
{
for (int i = 0; i < newMess.Count; i++)
{
LM.InboxTemp.Insert(0, newMess[i]);
}
}
BindingSource source = new BindingSource();
source.DataSource = LM.InboxTemp; //List with Objects
dgNewMess.DataSource = source;
dgNewMess.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dgNewMess.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dgNewMess.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dgNewMess.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
Upvotes: 2
Views: 1399
Reputation: 236208
If you want to filter collection of Emails, you can use Linq for that. Also you can use ForEach
method of List<Email>
to insert new filtered emails to your InboxTemp
list:
string filter = txtFilter.Text;
LM.GetNewMessages()
.Where(msg => msg.Subject.Contains(filter))
.ToList()
.ForEach(msg => LM.InboxTemp.Insert(0, msg));
UPDATE with Equin.ApplicationFramework.BindingListView you can assign datasource this way
dgNewMess.DataSource = new BindingListView<Email>(LM.InboxTemp);
and later apply filter
string filter = txtFilter.Text;
BindingListView<Email> emails = (BindingListView<Email>)dgNewMess.DataSource;
emails.Filter = new PredicateItemFilter<Email>(msg => msg.Subject.Contains(filter));
Upvotes: 5