Search code examples
c#winformsclassdata-bindingdatagrid

Filter binded datagrid so that it displays only items that have a particular value (Winforms)


So in my winforms project I have a datagrid that is binded to a 'Wrestler' class. This class has a number of different properties such as 'Name', 'Gender' ,'Title' (whether the person has a championship title or not), etc. This class gets its data from a JSON text file which contains all of the various 'Wrestlers' and their different attributes. The datagrid is set so that the only column visible is the 'Name' column. I also have a bunch of labels on the form that get updated to show the corresponding values of each 'Wrestler' object, whenever the user clicks on them in the datagrid.

This is all working fine however what I would like to do is have a 'Filter Champions' button where, when the user clicks it, only the 'wrestler' objects that DO NOT have the value "None" in their corresponding 'Title' property (those who DO hold a championship title) will be displayed in the DataGrid.

I consider myself a beginner in C# so I hope this makes sense. Any help would be much appreciated. Thanks in advance!

As I'm new to C# I have no idea where to start when it comes to filtering the datagrid in this manner. However, to give you an idea of what I have so far..

In the Form_Load event I have:

 var json = File.ReadAllText(_filePath);
 Wrestlers = JsonConvert.DeserializeObject<BindingList<Wrestler>>(json);

var wrestlers = this.Wrestlers;
dataGridView1.DataSource = wrestlers;

In the datagrid _Cell Click event I have:

Wrestler selectedWrestler = (Wrestler)dataGridView1.SelectedCells[0].OwningRow.DataBoundItem;
lblName.Text = selectedWrestler.FullName;
lblTitle.Text = selectedWrestler.Title;

Solution

  • Make a button and in on Click event of it, update the source of DataGrid and then refresh it. you can do this:

    var newResult = wrestlers.Where(x=>x.Title != "None").ToList(); // Replace "None" with something that you Don't want Title Be.
    // Or you can replace whole Condition after x=>x. for example (x=>x.Title == "championship")
    dataGridView1.DataSource = null;
    dataGridView1.DataSource = wrestlers;