Content feed Comments Feed

The Official ASATO Site

Hi, welcome to my blog. ASP,asp.net,Health,Javascript,JQUERY

What is List and How to bind List to GridView?

Posted by admin On March - 12 - 2010

C# List Examples
Lists are dynamic arrays in the C# language. They can grow as needed when you add elements. They are called generic collections and constructed types.You need to use < and > in the List declaration.
Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

Examples 1

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
        List<string> dinosaurs = new List<string>();
        dinosaurs.Add("one");
        dinosaurs.Add("two");
        dinosaurs.Add("three");
        dinosaurs.Add("four");
        dinosaurs.Add("five");
        foreach(string din in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

Examples 2
This example shows how you can create a new List of unspecified size, and add object to it.

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Client
{
    public Client(string Name, int Age)
    {
        _Name = Name;
        _Age = Age;
    }
    private int _Age;
    public int Age
    {
        get { return _Age; }
        set { _Age = value; }
    }
    private string _Name;
    public string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }
}
?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
List<Client> lst = new List<Client>();
lst.Add(new Client("Mike", 20));
lst.Add(new Client("Tom", 22));
foreach(Client cit in lst)
{
     Console.WriteLine(cit.Name);
     Console.WriteLine("------------");
     Console.WriteLine(cit.Age);
     Console.WriteLine(cit.Name);
}

How to bind List<> to GridView?

?View Code CSHARP
1
2
GridView1.DataSource = lst;
GridView1.DataBind();