[c#] C#: How to add subitems in ListView

Creating an item(Under the key) is easy,but how to add subitems(Value)?

listView1.Columns.Add("Key");
listView1.Columns.Add("Value");
listView1.Items.Add("sdasdasdasd");
//How to add "asdasdasd" under value?

This question is related to c# .net winforms list view

The answer is


Suppose you have a List Collection containing many items to show in a ListView, take the following example that iterates through the List Collection:

foreach (Inspection inspection in anInspector.getInspections())
  {
    ListViewItem item = new ListViewItem();
    item.Text=anInspector.getInspectorName().ToString();
    item.SubItems.Add(inspection.getInspectionDate().ToShortDateString());
    item.SubItems.Add(inspection.getHouse().getAddress().ToString());
    item.SubItems.Add(inspection.getHouse().getValue().ToString("C"));
    listView1.Items.Add(item);
  }

That code produces the following output in the ListView (of course depending how many items you have in the List Collection):

Basically the first column is a listviewitem containing many subitems (other columns). It may seem strange but listview is very flexible, you could even build a windows-like file explorer with it!


add:

.SubItems.Add("asdasdasd");

to the last line of your code so it will look like this in the end.

listView1.Items.Add("sdasdasdasd").SubItems.Add("asdasdasd");

ListViewItem item = new ListViewItem();
item.Text = "fdfdfd";
item.SubItems.Add ("melp");
listView.Items.Add(item);

Generally:

ListViewItem item = new ListViewItem("Column1Text")
   { Tag = optionalRefToSourceObject };

item.SubItems.Add("Column2Text");
item.SubItems.Add("Column3Text");
myListView.Items.Add(item);

Great !! It has helped me a lot. I used to do the same using VB6 but now it is completely different. we should add this

listView1.View = System.Windows.Forms.View.Details;
listView1.GridLines = true; 
listView1.FullRowSelect = true;

I've refined this using an extension method on the ListViewItemsCollection. In my opinion it makes the calling code more concise and also promotes more general reuse.

internal static class ListViewItemCollectionExtender
{
    internal static void AddWithTextAndSubItems(
                                   this ListView.ListViewItemCollection col, 
                                   string text, params string[] subItems)
    {
        var item = new ListViewItem(text);
        foreach (var subItem in subItems)
        {
            item.SubItems.Add(subItem);
        }
        col.Add(item);
    }
}

Calling the AddWithTextAndSubItems looks like this:

// can have many sub items as it's string array
myListViewControl.Items.AddWithTextAndSubItems("Text", "Sub Item 1", "Sub Item 2"); 

Hope this helps!


You whack the subitems into an array and add the array as a list item.

The order in which you add values to the array dictates the column they appear under so think of your sub item headings as [0],[1],[2] etc.

Here's a code sample:

//In this example an array of three items is added to a three column listview
string[] saLvwItem = new string[3];

foreach (string wholeitem in listofitems)
{
     saLvwItem[0] = "Status Message";
     saLvwItem[1] = wholeitem;
     saLvwItem[2] = DateTime.Now.ToString("dddd dd/MM/yyyy - HH:mm:ss");

     ListViewItem lvi = new ListViewItem(saLvwItem);

     lvwMyListView.Items.Add(lvi);
}

I think the quickest/neatest way to do this:

For each class have string[] obj.ToListViewItem() method and then do this:

foreach(var item in personList)
{
    listView1.Items.Add(new ListViewItem(item.ToListViewItem()));
}

Here is an example definition

public class Person
{
    public string Name { get; set; }
    public string Address { get; set; }
    public DateTime DOB { get; set; }
    public uint ID { get; set; }

    public string[] ToListViewItem()
    {
        return new string[] {
            ID.ToString("000000"),
            Name,
            Address,
            DOB.ToShortDateString()
        };
    }
}

As an added bonus you can have a static method that returns ColumnHeader[] list for setting up the listview columns with

listView1.Columns.AddRange(Person.ListViewHeaders());

Create a listview item

ListViewItem item1 = new ListViewItem("sdasdasdasd", 0)
item1.SubItems.Add("asdasdasd")

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to view

Empty brackets '[]' appearing when using .where SwiftUI - How do I change the background color of a View? Drop view if exists Difference between View and ViewGroup in Android How to make a view with rounded corners? How to remove all subviews of a view in Swift? How to get a view table query (code) in SQL Server 2008 Management Studio how to add button click event in android studio How to make CREATE OR REPLACE VIEW work in SQL Server? Android findViewById() in Custom View