我有一个带有数组列表的ICollection类LabCollection。此数组列表包含另一个类LabEntity.LabEntity具有属性LabID,LabName等

我将icollection类绑定到gridview

LabCollection objLabCollection=new LabCollection();

gridview.datasource=objlabCollection
gridview.databind();


在绑定到具有特定LabName的网格之前,我必须先填充类。我尝试这个

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

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


如何实现呢?

最佳答案

您有两个类LabCollectionLabEntityLabCollection现在包含一个ArrayList

更好的方法是像这样更改LabCollection类。 (我宁愿将其命名为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();
    }

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

}


现在像这样在后台代码中调用它

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


更新:

如果您想继续使用ArrayList,请像这样更改功能

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;
    }

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

}


附注:优化程度不是很高,但这可以帮助您入门。

关于c# - 使用C#绑定(bind)到.net中的gridview之前,从类数组中过滤数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13337799/

10-09 06:42