August Williams
August Williams

Reputation: 929

How to iterate over all entries in a single GridView's column?

Consider the following grid view:

enter image description here

Its fairly empty at the moment but will be more populated.

peronID column will always be in the same place. How can I iterate over the first column, counting all personID's equal to a given amount? Something like this (pseudocode) :

foreach element in personID
if element == 25
    count += 1

Code that populates the GridView:

    private void DisplayTable()
    {
        LibraryEntities1 myDB = new LibraryEntities1();
        var people = myDB.People;
        gridViewPeople.DataSource = people.ToList();
        gridViewPeople.DataBind();
    }

Upvotes: 0

Views: 40

Answers (1)

Crowcoder
Crowcoder

Reputation: 11514

I suggest you operate on the data, not on the grid, so assuming the List below is what you might have bound to your grid:

Given class Person:

class Person
{
    public int PersonID { get; set; }
    public string PersonName { get; set; }
}

You can group by and sum just like you might do in SQL:

List<Person> persons = new List<Person>{
    new Person{ PersonID = 13,  PersonName = "Foo" },
    new Person{ PersonID = 13,  PersonName = "Foo" },
    new Person{ PersonID = 15,  PersonName = "Foo" }
};

var grp = persons.GroupBy(p => p.PersonID)
    .Select(p => new {pid = p.Key, count = p.Count()});

foreach (var element in grp)
{
    Console.WriteLine($"PersonID = {element.pid}, Count of Person = {element.count}");
}

Output:

PersonID = 13, Count of Person = 2
PersonID = 15, Count of Person = 1

Upvotes: 1

Related Questions