Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I'd like to know how to address and change a specific item in a listview in c#. I already created a listview in my form and implemented 2 columns. I know how to add an item to the first column at runtime, but now I want to add an item to the second column, same row, at runtime and change it! Any ideas how to do that?

Thanks in advance.
Posted

The following example shows how you can set values for a list view by specifying row and column and a value to set.

The example will add a new line if required but will not add more columns than defined on the list view:

C#
private void UpdateListViewValue(ListView listView, int row, int column, string newValue)
{
    if (column >= listView.Columns.Count)
        throw new InvalidOperationException("cannot modify outside column bounds");
    ListViewItem item;
    if (row < listView.Items.Count)
        item = listView.Items[row];
    else
    {
        item = new ListViewItem();
        for (int i = 1; i < listView.Columns.Count; ++i)
            item.SubItems.Add(new ListViewItem.ListViewSubItem());
        listView.Items.Add(item);
    }
    item.SubItems[column].Text = newValue;
}


Hope this helps,
Fredrik
 
Share this answer
 
Each item of a list view is of ListViewItem type. A property of this type is SubItems, this is a collection of ListViewItems representing all the values for each column defined.

So in your case you want to change a specific column so give this a go:

CSS
// use the first item list item

ListViewItem myItem = listView1.Items[0];

myItem.SubItems[1].Text = "New Sub Item Value";



Ok in this case I have chosen a specific item, but you may want to use the SelectedItems property of ListView to retrieve your LstViewItem.

Hope this helps...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900