Populating Columns in ListView Control
In C# Windows Forms, the ListView control allows you to display data in a tabular format. By default, items are added to the first column (Column1). This article explores how to populate data into columns beyond the first one.
Method 1: Using SubItems Property
To add items to columns 2, 3, 4, and so on, you can use the SubItems property of the ListViewItem. Its syntax is:
ListViewItem item = new ListViewItem("Column1Text"); item.SubItems.AddRange(new string[] { "s2", "s3", "s4" });
Here, we create a new ListViewItem object with "Column1Text" as the text for the first column. Then, using the AddRange method, we add items to the subsequent columns as a string array.
Method 2: Using Individual SubItems
Another way is to add sub-items individually using the SubItems collection:
ListViewItem item = new ListViewItem("Something"); item.SubItems.Add("SubItem1a"); item.SubItems.Add("SubItem1b"); item.SubItems.Add("SubItem1c");
This method allows finer control over each sub-item.
Adding Multiple Items
You can add multiple items to the ListView at once using the AddRange method of the Items collection:
ListViewItem item1 = new ListViewItem("Something1"); item1.SubItems.AddRange(new string[] { "s1a", "s1b", "s1c" }); ListViewItem item2 = new ListViewItem("Something2"); item2.SubItems.AddRange(new string[] { "s2a", "s2b", "s2c" }); listView1.Items.AddRange(new ListViewItem[] { item1, item2 });
This approach allows you to populate multiple columns and rows efficiently.
The above is the detailed content of How to Populate Multiple Columns in a C# ListView Control?. For more information, please follow other related articles on the PHP Chinese website!