Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add to a specific column in Listview item?

I create a listview and the number of columns are determined at runtime. I have been reading texts on the web all over about listview( and I still am) but I wish to know how to add items to a specific column in listview I thought something like:

m_listview.Items.Add("1850").SubItems.Add("yes");

would work assuming the "1850" which is the text of the column would be the target column.

like image 559
Dark Star1 Avatar asked Aug 10 '09 15:08

Dark Star1


2 Answers

ListViewItems aren't aware of your ListView columns.

In order to directly reference the column, you first need to add all the columns to the ListViewItem.

So... lets say your ListView has three columns A, B and C; This next bit of code will only add data to column A:

ListViewItem item = new ListViewItem();
item.Text = "Column A";

m_listView.Items.Add(item);

To get it to add text to column C as well, we first need to tell it it has a column B...

ListViewItem item = new ListViewItem();
item.Text = "Column A";
item.SubItems.Add("");
item.SubItems.Add("Column C");

m_listView.Items.Add(item);

So now we'll have columns A, B and C in the ListViewItem, and text appearing in the A and C columns, but not the B.

Finally... now that we HAVE told it it has three columns, we can do whatever we like to those specific columns...

ListViewItem item = new ListViewItem();
item.Text = "Column A";
item.SubItems.Add("");
item.SubItems.Add("Column C");

m_listView.Items.Add(item);

m_listView.Items[0].SubItems[2].Text  = "change text of column C";
m_listView.Items[0].SubItems[1].Text  = "change text of column B";
m_listView.Items[0].SubItems[0].Text  = "change text of column A";

hope that helps!

like image 191
Sk93 Avatar answered Nov 09 '22 01:11

Sk93


I'm usially inherit ListViewItem as :

public class MyOwnListViewItem : ListViewItem 
{
    private UserData userData;

    public MyOwnListViewItem(UserData userData) 
    {
        this.userData = userData;
        Update();
    }

    public void Update() 
    { 
       this.SubItems.Clear(); 
       this.Text = userData.Name; //for first detailed column

       this.SubItems.Add(new ListViewSubItem(this, userData.Surname)); //for second can be more
    }
}

where

public class UserData 
{
   public string Name;
   public string Surname;
}

using

listView1.Items.Add(new MyOwnListViewItem(new UserData(){Name="Name", Surname = "Surname"}));
like image 31
Chernikov Avatar answered Nov 09 '22 02:11

Chernikov