Adding values calculated to another function to second row of listview

Viewed 46

I have a listview with two columns. The first column is filled with items imported from an external file. The second column is supposed to be filled with values that are calculated in another function of the software. How is this possible?

EDIT

   string[] arr = new string[4];
    ListViewItem itm;

    private void button3_Click(object sender, EventArgs e)
    {
 listView1.Columns.Add("ProductName", 100);
        listView1.Columns.Add("Price", 70);
        //Add items in the listview
        //Add first item
        arr[0] = "product_1";
        itm = new ListViewItem(arr);
        listView1.Items.Add(itm);

        //2
        arr[0] = "product_2";
        itm = new ListViewItem(arr);
        listView1.Items.Add(itm);
        listView1.CheckBoxes = true; 

The result is something like this : enter image description here

Now I have another function, a simple button. Let's say that I want to press the button and fill the second column of the listview with some values. In this case it is the price of each product.

I wrote the following :

 private void button4_Click(object sender, EventArgs e)
    {
             //1

        arr[1] = "20000";
       
        itm = new ListViewItem(arr);
        listView1.Items.Add(itm);
        //Add second item    
        arr[1] = "200";
   


        itm = new ListViewItem(arr);
        listView1.Items.Add(itm);
        
    }

The result is like this : enter image description here

The first column is changing as well. I only want to put the prices calculated at one function next to a list of products.

1 Answers

Looks like in your second button you are adding a new item when you actually want to update an existing item. Well add a child to an existing item.

Try this in your second button click.

listView1.Items[index].SubItems.Add("20,000");

Where index is the 0-based index of the item you want to modify. You may wish to use a foreach loop to update all the items. Which would look something like this.

foreach (ListViewItem item in listView1.Items)
{
    //Do your calculation or whatever it is you want to per item here...
    item.SubItems.Add("20,000");
}

Hopefully this helps. :)

Related