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.
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!
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"}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With