Adding items to a listview in C#

Before adding items to a listview, set the listview’s View property to Detail.  This allows the definition of multiple columns.

Now, the individual columns can now be defined.  In this example, I will create and use a 4-column listview.  To create the listview, use the Columns property and define the Name and Text.

Column Definition

Column Definition

Defining all four columns creates this listview:

Listview and properties

Listview and properties

Each row in the listview is a ListViewItem.  Each column in a ListViewItem is a SubItem.  Each SubItem is added to each ListViewItem in the order the columns are defined.

These are the steps taken to add multiple ListViewItems (or rows) to a listview:

  1. Notify the listView control that an update is about to begin
  2. Clear any existing listViewItems
  3. Create an individual ListViewItem
  4. Add the subItems
  5. Notify the listView control that the update has ended
  6. Notifi the listView control to refresh itself so that it will display the new rows
 int i = 1;
 lstXmlItems.BeginUpdate();
 lstXmlItems.Items.Clear();

 foreach (var item in bools)
 {
      ListViewItem row = new ListViewItem(i.ToString());
      row.SubItems.Add(item.EventId);
      row.SubItems.Add(item.Name);
      row.SubItems.Add(item.WordPos);
      lstXmlItems.Items.Add(row);
      i++;
 }
lstXmlItems.EndUpdate();
lstXmlItems.Refresh();
Advertisements

4 Responses to Adding items to a listview in C#

  1. Rishi says:

    great post..
    In the same way I want to add a row with following items (Cloumns):
    1. CheckBox
    2. Name
    3. Address
    4. ImageButton/Button/Image

    Is it possible ?
    Please tell me how can I creae suhlist view.. Its urgent.

    Thanks in advance.

    • Jim Lahman says:

      Rishi –

      Check out the ‘Bind List to a DataGridView’ I just uploaded. Please let me know if that helps.

      Good luck!

      Jim

  2. Ravi says:

    Nice Post…
    Very usefull one.

    Thanks for guiding.

  3. Its like you read my mind! You seem to know a lot
    about this, like you wrote the book in it or something.
    I think that you can do with some pics to drive the
    message home a bit, but other than that,
    this is wonderful blog. A great read. I will certainly be back.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: