I'm learning how to use the listView
in a windowsForm
and I have some problems that I hope to solve here. The first thing is when I'm creating the columns with the code below:
private void initListView()
{
// Add columns
lvRegAnimals.Columns.Add("Id", -3,HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -3, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -3, HorizontalAlignment.Left);
}
When I run the program, the name of the columns are not visible, they are all at the left corner, and I have to "drag" them to be able to read the text. What have I done wrong?
And finally I wonder how I add items to the columns. Do I first create a object like
ListViewItem item1 = new ListViewItem(???);
item1.SubItems.Add("text");
Is each listViewItem objects a column or a row? How do I add rows of info? Preciate some help! Thanks!
Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columns.aspx (look at the comments on the code example at the bottom)
private void initListView()
{
// Add columns
lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
}
You can also use the other overload, Add(string). E.g:
lvRegAnimals.Columns.Add("Id");
lvRegAnimals.Columns.Add("Name");
lvRegAnimals.Columns.Add("Age");
Reference for more overloads: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columnheadercollection.aspx
Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.
var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});
lvRegAnimals.Items.Add(item1);
lvRegAnimals.Items.Add(item2);
You can also store objects in the item's Tag property.
item2.Tag = person;
And then you can extract it
var person = item2.Tag as Person;
Let me know if you have any questions and I hope this helps!
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