Introduction
This article will discuss how to add listView items from another form in C#. ListView is a control that displays a collection of items in a list. It is a powerful control that can be used to display data in a variety of ways. In this article, we will discuss how to add items to a ListView from another form. We will also discuss how to access the items in the ListView from the other form. Finally, we will discuss how to update the ListView when the items in the other form change.
Solution
//Form1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.ShowDialog();
}
}
//Form2.cs
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Add items to listView
listView1.Items.Add(new ListViewItem(“Item1”));
listView1.Items.Add(new ListViewItem(“Item2”));
listView1.Items.Add(new ListViewItem(“Item3”));
}
}
The error is in the function
public void AddItem(object value)
{
listView1.Items.Add(value);
}
you pass an object to this function and try to add it to the ListViewItemCollection, but there is no overload of the Add method of the ListViewItemCollection that accepts an object
Change it to
public void AddItem(string value)
{
listView1.Items.Add(value);
}
This will solve the immediate compilation problem, but you will have hard time working with that static variable. If your plan were to pass values from form2 to form1 it is better that you keep the created instance of form1 and use it to pass values through the AddItem method otherwise you will end to add that values to other instances of the Form1 (the latter instance created will receive the new string)
1
solved c# Add listView items from another form [closed]
Adding items to a ListView from another form can be done in C# by using the AddRange
method. This method takes an array of ListViewItem objects and adds them to the ListView. To use this method, you first need to create an array of ListViewItem objects. This can be done by looping through the items in the other form and creating a ListViewItem object for each item. Once the array is created, you can then use the AddRange
method to add the items to the ListView.
The following example shows how to add items to a ListView from another form in C#:
// Create an array of ListViewItem objects
ListViewItem[] items = new ListViewItem[otherForm.Items.Count];
// Loop through the items in the other form
for (int i = 0; i < otherForm.Items.Count; i++)
{
// Create a ListViewItem object for each item
items[i] = new ListViewItem(otherForm.Items[i].Text);
}
// Add the items to the ListView
listView.Items.AddRange(items);
Once the items have been added to the ListView, they can be accessed and manipulated just like any other item in the ListView. This makes it easy to add items from another form to a ListView in C#.