Programmically Adding Items to ListView Control in WPF

A ListView control is similar to a ListBox but can contain multiple columns. But to add data we need to bind it to an object which has the same data members as the columns of the ListView control.

This is how I have declared the ListView and its columns

<ListView Name="list">
            <GridViewColumn Header="Serial No." DisplayMemberBinding="{Binding Serial}" />
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" />
            <GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}" />

Notice the Binding values. Now I will create a class named Item (you can name it anything you like)

class Item
    int serial;
    string name;
    int age;

    public Item(int s, string n, int a)
        serial = s;
        name = n;
        age = a;

    public int Serial
        set { serial = value; }
        get { return serial; }

    public string Name
        set { name = value; }
        get { return name; }

    public int Age
        set { age = value; }
        get { return age; }

The property names of this class matches the binding values. Finally we can add new items:

list.Items.Add( new Item(1, "Ibrahim", 21) );
list.Items.Add( new Item(2, "Sumayyah", 15) );
list.Items.Add( new Item(3, "Yusuf", 20) );

This should work


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s