SoFunction
Updated on 2025-03-07

Master the usage and sample code of C# ListView control in one article

ListViewIt is a multi-column list view control that can be used to display multiple data items and their related information.ListViewControls provide rich properties and events that can be used to implement a variety of table views, including functions such as cell editing, sorting and grouping.

Below we use a few examples to demonstrate how to use itListViewControl.

Example 1: Basic use

In this example, we will create a basicListViewControl and add three columns of data to it - name, phone number and address. We will useItemsAttribute directionListViewAdd data to the control, and each customer information will be occupied.ListViewIn one row, each attribute will be displayed in a different column in a row. Here is the sample code:

private void Form1_Load(object sender, EventArgs e)
{
    // Create three columns representing name, phone number and address respectively    var colName = new ColumnHeader();
     = "Name";
     = 100;
    var colPhone = new ColumnHeader();
     = "Telephone";
     = 150;
    var colAddress = new ColumnHeader();
     = "address";
     = 200;
    // Add column to ListView control    (colName);
    (colPhone);
    (colAddress);
    // Add customer information to the ListView control    ListViewItem item1 = new ListViewItem("Zhang San");
    ("123456789");
    ("Haidian District, Beijing");
    ListViewItem item2 = new ListViewItem("Li Si");
    ("234567890");
    ("Shanghai Pudong New District");
    ListViewItem item3 = new ListViewItem("Wang Wu");
    ("345678901");
    ("Tianhe District, Guangzhou");
    (item1);
    (item2);
    (item3);
}

In this code, we first create threeColumnHeaderObjects represent three columns in the list view - name, phone number and address. We useTextProperties to set the title of each column, useWidthProperties to set the width of each column, and then add these three columns toListViewin the control. When adding each column, we add it toColumnsIn the collection, thus creating a new column in the list view.

Next, we useListViewItemObject andSubItemsProperties to fill the data of each row. In this example, we manually create three objects, each representing a customer's name, phone number, and address. We add each object toItemsIn the collection, thus creating new rows in the list view. We useAddMethods to add eachListViewItemThe object is toItemsIn the collection, thus creating a new row in the list view. We useSubItemsProperties to add column attributes in each row, which can help us display multiple column data.

Example 2: Dynamically add and delete rows

In this example, we will dynamically add and delete rows. We created two buttons, one for adding rows and one for deleting selected rows. We will add two event handlers to respond to the user's clicking of these two buttons. Here is the sample code:

private void btnAdd_Click(object sender, EventArgs e)
{
    // Display a dialog box to guide the user to enter new customer information (name, phone number, address)    using (var dlg = new AddCustomerDialog())
    {
        var result = ();
        if (result == )
        {
            // When the user clicks the OK button, add a line of data to the ListView control            var item = new ListViewItem();
            ();
            ();
            (item);
        }
    }
}
private void btnDelete_Click(object sender, EventArgs e)
{
    // Delete the selected row    foreach (ListViewItem item in )
    {
        (item);
    }
}

In this code, we first create two event handlers, one for adding rows and one for deleting selected rows. In the event handler that adds a row, we useAddCustomerDialogMode dialog box guides users to enter new customer information. When the user clicks the "OK" button, we obtain the customer information entered in the mode dialog box and create a newListViewItemofListViewItemObject and add it toListViewIn the item collection of the control, thereby creating a new row in the list view. Note that before adding a new line, we need to check that the user has clicked the "OK" button in the mode dialog box to ensure that the user has entered valid customer information. In the event handler that deletes the selected row, we simply traverseSelectedItems gather,For each selected ListViewItemObject, useRemoveMethod to transfer it fromListViewRemoved from the item collection of controls. During the process of deleting rows, we did not check whether any row was selected, but we need to note that if no row was selected,SelectedItemsThe collection will be empty, and the code that deletes the line will do nothing.

Example 3: Custom columns

In this example, we willListViewAdd a data with a custom column to the control. We will create a newListViewSubclass, coverOnCreateControlMethod to add custom columns to the control. In the column title area of ​​the custom column, we will add a new button control to trigger events when the column title is clicked. Here is the sample code:

public class CustomListView : ListView
{
    private ColumnHeader customColumnHeader = null;
    protected override void OnCreateControl()
    {
        ();
        AddCustomColumn();
    }
    private void AddCustomColumn()
    {
        // Create a custom list header        customColumnHeader = new ColumnHeader();
         = "operate";
         = 100;
        (customColumnHeader);
        // Add button to custom list header        var btn = new Button();
         = "New Customer";
         = true;
         += (sender, e) =>
        {
            // TODO: Add new customer code here        };
         = ;
         = btn;
    }
}

In this code, we create a name calledCustomListViewNew class and inheritedListView. We've coveredOnCreateControlMethod, add a custom column when the control is first created. We created aColumnHeaderObject to represent the column header of a custom column, add the custom column to the control'sColumnsIn the collection. We're atColumnHeaderControl'sControlA button control has been added to the property, which will appear in the column header. When clicking a button, we may handle operations related to new customers by adding code.

It is worth noting that to ensure that the button only accounts for a portion of the column header, we passAutoSizeProperties to resize the control to the same size as the content it contains, thus placing the button at the front of the column header. We passedTextAlignAttributes andValue to center the button in the entire column header.

This example just shows how toListViewData with custom columns are added to the control, and the specific event handler of the button needs to be defined according to the specific needs.

Of course there is, let me introduce it hereListViewIntegrated view mode and virtual mode of the control.

Integrated view mode

Integrated view mode allows data to be associated withListViewControls to display. In this mode, we can specify a data source, which must be implementedIListInterface. In this mode, when we go toItemsWhen adding data to a collection, it is actually adding the data item to the data source. Here is the example code implemented using the integrated view mode:

private void Form1_Load(object sender, EventArgs e)
{
    // Create a data source    var customers = new List<Customer>();
    (new Customer() { Name = "Zhang San", Phone = "123456789", Address = "Haidian District, Beijing" });
    (new Customer() { Name = "Li Si", Phone = "234567890", Address = "Shanghai Pudong New District" });
    (new Customer() { Name = "Wang Wu", Phone = "345678901", Address = "Tianhe District, Guangzhou" });
    // Associate the data source and ListView control     = ;
     = ;
     += (s, args) =>
    {
        var customer = customers[];
         = new ListViewItem();
        ();
        ();
    };
}

In this code, we create aList<Customer>Object, and several customer information were added. Then, we willView The property is set to Details, and willVirtualListSizeThe property is set to the size of the data source. We useRetrieveVirtualItemEvents to provide data. In this event, we useListViewItemandSubItemsAttributes toListViewThe control fills the data for each row. Using virtual lists improves rendering speed when data is large.

Virtual mode

When we need to display a large amount of data, using virtual mode can significantly improve.ListViewControl performance. In virtual mode,ListViewThe control only retrieves data from the data source when it needs to be displayed. Here is the example code that is implemented using virtual mode:

private void Form1_Load(object sender, EventArgs e)
{
    // Create a data source    var customers = new List&lt;Customer&gt;();
    for (int i = 1; i &lt;= 100000; i++)
    {
        (new Customer() { Name = $"client{i}", Phone = $"Phone {i}", Address = $"Address {i}" });
    }
    // Set the style and virtual mode of the list view     = ;
     = true;
     = ;
    // Add data to the column    ("Name");
    ("Telephone");
    ("address");
     += (s, args) =&gt;
    {
        var customer = customers[];
        var item = new ListViewItem();
        ();
        ();
         = item;
    };
}

In this code, we create a data source with 100,000 pieces of customer information andVirtualMode The property is set to true. Then, we willView The property is set to Details, and add the title for each column. existRetrieveVirtualItemIn the incidentRetrieveVirtualItemIn the event, we first obtainitemIndexThe corresponding data item and then add it toListViewItemIn the object and passReturns this item so that it appears in the control. Note that in virtual mode, only items that the control needs to display will be retrieved from the data source, so this event will be called multiple times when the control scrolls to get the data for the corresponding item.

It should be noted that when using virtual mode, if you want to add, delete or update rows, etc., we need to make corresponding modifications in the data source, rather than directly in theItemsPerform corresponding operations in the collection.

When using virtual mode, the control only retrieves the data to be displayed from the data source without loading the entire data source into memory. Therefore, in the case of large amounts of data, virtual mode can effectively save memory and improve control performance.

The above are some commonListViewControl usage and sample code. certainly,ListViewThe functions of the control are much more than that. It also provides many other properties and events, such as cell editing, sorting, grouping, full screen display, etc. You can freely choose and use them according to your needs.

This is the end of this article about mastering the usage of C# ListView in one article. For more related content on usage of C# ListView, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!