Ranadheer Reddy
Ranadheer Reddy

Reputation: 4324

How to add List<> values to gridview?

I created a asp.net website. and added a class file to it. i wrote this code in classfile.(person.cs)

public class Person
{
public string name{get; set;}
public int age { get; set; }
public float sal { get; set; }

public Person(string n, int a, float s)
{
    name = n;
    age = a;
    sal = s;
}


public List<Person> getDetails()
{
    Person p1 = new Person("John",21,10000);
    Person p2 = new Person("Smith",22,20000);
    Person p3 = new Person("Cena",23,30000);
    List<Person> li = new List<Person>();
    li.Add(p1);
    li.Add(p2);
    li.Add(p3);
    return li;
}

}

and i want this list to display in my gridview.

so, i have added a default page in website. then what should i write in default.aspx.cs file?so that my list values are shown on gridview?

Thanks.

Upvotes: 0

Views: 7279

Answers (2)

Dmitry Reznik
Dmitry Reznik

Reputation: 6862

Make the method static:

public static List<Person> getDetails()
{
    Person p1 = new Person("John",21,10000);
    Person p2 = new Person("Smith",22,20000);
    Person p3 = new Person("Cena",23,30000);
    List<Person> li = new List<Person>();
    li.Add(p1);
    li.Add(p2);
    li.Add(p3);
    return li;
}

And use it from default.aspx.cs like this:

    gridView.DataSource = Person.getDetails();
    gridView.DataBind();

Upvotes: 1

ankit rajput
ankit rajput

Reputation: 182

You can access you getDetails(); method from class file as follows:

Person per=new Person();

grdview.DataSource=per.getDetails();
grdview.DataBind();

Upvotes: 0

Related Questions