Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter data from class array before binding to gridview in .net using c#

Tags:

c#

I have a ICollection class LabCollection with an array list.This array list contains another class LabEntity.LabEntity has property LabID,LabName etc

I am binding icollection class to gridview

LabCollection objLabCollection=new LabCollection();

gridview.datasource=objlabCollection
gridview.databind();

I have to fillter class before binding to grid with specific LabName. I try this

BindingSource bs = new BindingSource();
bs.DataSource=objlabCollection
bs.Filter = "LabName='CPT'";

gridview.DataSource = bs;
gridview.DataBind();

How to achieve this?

like image 609
Gladiator Avatar asked Aug 24 '26 06:08

Gladiator


1 Answers

You have two classes LabCollection and LabEntity. LabCollection contains an ArrayList now.

A much better approach will be to change the LabCollection class like this. ( I would rather name it LabCollectionManager )

public class LabCollectionManager()
{

    //.................

    public List<LabEntity> GetAllLabEntities()
    {
        //method that generates a generic list of LabEntity 
    }

    public List<LabEntity> GetLabEntitiesByLabName(string labName)
    {
        return GetAllLabEntities().Where(le => le.LabName == labName).ToList();
    }

    //.................

}

Now call it in the code-behind like this

var labManager = new LabCollectionManager();
gridview.DataSource = labManager.GetLabEntitiesByLabName("CPT");
gridview.DataBind();

Update:

If you wanna persist using ArrayList, change your functions like this

public class LabCollectionManager()
{

    //.................

    public ArrayList GetAllLabEntities()
    {
        //method that generates a generic list of LabEntity 
    }

    public ArrayList GetLabEntitiesByLabName(string labName)
    {
        var completeList = GetAllLabEntities();
        var filteredList = new ArrayList(completeList.Cast<LabEntity>()
                                    .Where(le => le.LabName == labName)
                                    ToList());
        return filteredList;
    }

    //.................

}

P.S: Not very optimised, but this will help you get started.

like image 163
naveen Avatar answered Aug 25 '26 21:08

naveen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!