How to fill a ListView?

BenTam 1,741 Reputation points
2024-04-30T05:22:04.94+00:00

Dear all,

I'm a beginner in C#. Could anyone tell me how to fill a ListView?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,114 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Jiale Xue - MSFT 47,666 Reputation points Microsoft Vendor
    2024-04-30T07:08:59.88+00:00

    Hi @BenTam-3003 ,Welcome to Microsoft Q&A,

    For more information on the use of ListView, you can check out the official documentation: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.listview?view=windowsdesktop-8.0

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace xxx
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                CreateMyListView();
            }
            private void CreateMyListView()
    {
        // Create a new ListView control.
        ListView listView1 = new ListView();
        listView1.Bounds = new Rectangle(new Point(10,10), new Size(300,200));
    
        // Set the view to show details.
        listView1.View = View.Details;
        // Allow the user to edit item text.
        listView1.LabelEdit = true;
        // Allow the user to rearrange columns.
        listView1.AllowColumnReorder = true;
        // Display check boxes.
        listView1.CheckBoxes = true;
        // Select the item and subitems when selection is made.
        listView1.FullRowSelect = true;
        // Display grid lines.
        listView1.GridLines = true;
        // Sort the items in the list in ascending order.
        listView1.Sorting = SortOrder.Ascending;
                    
        // Create three items and three sets of subitems for each item.
        ListViewItem item1 = new ListViewItem("item1",0);
        // Place a check mark next to the item.
        item1.Checked = true;
        item1.SubItems.Add("1");
        item1.SubItems.Add("2");
        item1.SubItems.Add("3");
        ListViewItem item2 = new ListViewItem("item2",1);
        item2.SubItems.Add("4");
        item2.SubItems.Add("5");
        item2.SubItems.Add("6");
        ListViewItem item3 = new ListViewItem("item3",0);
        // Place a check mark next to the item.
        item3.Checked = true;
        item3.SubItems.Add("7");
        item3.SubItems.Add("8");
        item3.SubItems.Add("9");
    
        // Create columns for the items and subitems.
        // Width of -2 indicates auto-size.
        listView1.Columns.Add("Item Column", -2, HorizontalAlignment.Left);
        listView1.Columns.Add("Column 2", -2, HorizontalAlignment.Left);
        listView1.Columns.Add("Column 3", -2, HorizontalAlignment.Left);
        listView1.Columns.Add("Column 4", -2, HorizontalAlignment.Center);
    
        //Add the items to the ListView.
        listView1.Items.AddRange(new ListViewItem[]{item1,item2,item3});
    
        // Create two ImageList objects.
        ImageList imageListSmall = new ImageList();
        ImageList imageListLarge = new ImageList();
    
        // Initialize the ImageList objects with bitmaps.
        //imageListSmall.Images.Add(Bitmap.FromFile("C:\\MySmallImage1.bmp"));
        //imageListSmall.Images.Add(Bitmap.FromFile("C:\\MySmallImage2.bmp"));
        //imageListLarge.Images.Add(Bitmap.FromFile("C:\\MyLargeImage1.bmp"));
        //imageListLarge.Images.Add(Bitmap.FromFile("C:\\MyLargeImage2.bmp"));
    
        //Assign the ImageList objects to the ListView.
        listView1.LargeImageList = imageListLarge;
        listView1.SmallImageList = imageListSmall;
    
        // Add the ListView to the control collection.
        this.Controls.Add(listView1);
        }
    } }
    
    

    User's image

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Karen Payne MVP 35,456 Reputation points
    2024-05-01T14:46:59.7066667+00:00

    I have a GitHub repository dedicated to working with ListView. Which read data from SQL-Server database.

    Below is one example

    Backend

    public List<Contact> GetOwnerContacts()
    {
        mHasException = false;
        var ownerContacts = new List<Contact>();
    
    
        var selectStatement =
            @"
            SELECT   Cust.CustomerIdentifier ,
                     Cust.CompanyName ,
                     cont.FirstName ,
                     cont.LastName ,
                     PT.PhoneTypeDescription ,
                     CCD.PhoneNumber ,
                     Countries.CountryName
            FROM     Customers AS Cust
                     INNER JOIN dbo.Contact AS cont ON Cust.ContactIdentifier = 
                        cont.ContactIdentifier
                     INNER JOIN dbo.ContactContactDevices AS CCD ON cont.ContactIdentifier = 
                        CCD.ContactIdentifier
                     INNER JOIN dbo.PhoneType AS PT ON CCD.PhoneTypeIdenitfier = 
                        PT.PhoneTypeIdenitfier
                     INNER JOIN dbo.Countries ON Cust.CountryIdentfier = Countries.id
            WHERE    ( Cust.ContactTypeIdentifier = 7 )
            ORDER BY Cust.CompanyName;";
    
    
        using (var cn = new SqlConnection() { ConnectionString = ConnectionString })
        {
            using (var cmd = new SqlCommand() { Connection = cn })
            {
                try
                {
                    cn.Open();
    
                    cmd.CommandText = selectStatement;
    
                    var reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        ownerContacts.Add(new Contact()
                        {
                            CustomerIdentifier = reader.GetInt32(0),
                            CompanyName = reader.GetString(1),
                            FirstName = reader.GetString(2),
                            LastName = reader.GetString(3),
                            PhoneTypeDescription = reader.GetString(4),
                            PhoneNumber = reader.GetString(5),
                            CountryName = reader.GetString(6)
                        }) ;
                    }
    
                }
                catch (Exception e)
                {
                    mHasException = true;
                    mLastException = e;
                }
            }
        }
    
        return ownerContacts;
    }
    

    Frontend

    private void Form1_Shown(object sender, EventArgs e)
    {
        var dataOperations = new SqlInformation();
        var contacts = dataOperations.GetOwnerContacts();
    
        ownerContactListView.BeginUpdate();
        foreach (var contact in contacts)
        {
    
            ownerContactListView.Items.Add(
                new ListViewItem(contact.ItemArray)
                {
                    Tag = contact.CustomerIdentifier
                });
    
        }
    
        ownerContactListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
        ownerContactListView.EndUpdate();
    
        // this is how to select the first item
        //ownerContactListView.FocusedItem = ownerContactListView.Items[0];
        //ownerContactListView.Items[0].Selected = true;
    
        /*
         * This is a hard coded example to find an item and ensure it's visible
         */
        var item = ownerContactListView.FindItemWithText("Santé Gourmet");
    
        if (item != null)
        {
            var index = ownerContactListView.Items.IndexOf(item);
            ownerContactListView.Items[index].Selected = true;
            ownerContactListView.EnsureVisible(index);
        }
    
        CountLabel.Text = $@"Row count: {ownerContactListView.Items.Count}";
        ActiveControl = ownerContactListView;
    }
    

    A1

    A Group example A2


  3. KOZ6.0 6,580 Reputation points
    2024-05-02T20:31:26.83+00:00

    You can get custom controls with DataSource property using nuget. https://www.nuget.org/packages/MvvmFx-BoundControls-WinForms

    using System;
    using System.Data;
    using System.Windows.Forms;
    
    public partial class Form1 : Form
    {
        public Form1() {
            InitializeComponent();
        }
    
        private void Form1_Load(object sender, EventArgs e) {
            var dt = new DataTable();
            dt.Columns.Add("A");
            dt.Columns.Add("B");
            dt.Columns.Add("C");
            dt.Rows.Add("aaa", "bbb", "ccc");
            dt.Rows.Add("ddd", "eee", "fff");
            boundListView1.View = View.Details;
            boundListView1.DataSource = dt;
        }
    }
    

    BoundListView


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.