C# - Simple question. Regarding ListView with multicolumns

Hi,

This is C#, but the idea is of course the same for VB .NET or whatever language you use:

Code:
 listView1.Items.Add("Item 1").SubItems.Add("SubItem 1");

Will add "Item 1" to the first column, and "SubItem 1" to the second column. You can add .SubItems.Add.. etc etc for as many columns as you have :)
 
Thank you very much folks! :)

But what if I just want to add a item at column 2 instead of add values to columns 1 and 2?

Because I only have access to subitems properties after adding to the first item too...

Anyway, If I want to add items to 3 or more columns do I really need to do this?
Code:
for (int i = 0; i < 2000; i++)
{
        //Adds items to the first and second columns
	this.listView1.Items.Add("bla" + i).SubItems.Add("bla" + i);
       
        //This adds an item to the third column	
	this.listView1.Items[i].SubItems.Add("bla" + i); 
       
        //This adds an item to the forth column	
	this.listView1.Items[i].SubItems.Add("bla" + i); 
        // etc...
}
 
Last edited:
But what if I just want to add a item at column 2 instead of add values to columns 1 and 2?

Because I only have access to subitems properties after adding to the first item too...
If you just want to access for example the second column, you can do something like:
Code:
 listView1.Items[0].SubItems[1].Text = "Whatever";
or depending on your situation, you could use the Key, which you would add at the same time as adding the item. Then to access the second column you could do something like:
Code:
 listView1.Items["ItemKey"].SubItems[1].Text = "New Text";

I'm currently writing a UI for an online gaming service, and I'm showing the users ping next to their username in a listView. Whenever I add a user to the listview, I also add their username as the key, which makes it easy for me to update their ping (and other details) whenever I want, by doing listView.Items[string UserName].SubItems.blah...

Hope this makes sense :)
 
lol, I found it by the time I las posted.... But tks anyway...

Now am trying to select an item through code, but I just can't! Why there is no simple option like listView1.SelectIndex = 0???
 
EFileTahi-A said:
lol, I found it by the time I las posted.... But tks anyway...

Now am trying to select an item through code, but I just can't! Why there is no simple option like listView1.SelectIndex = 0???

Because multiple items can be selected ;) (Do check for this in your code!!)

pendragon got the solution to your question though.
 
Back
Top