Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a list view with the contents of List<string> in C#

Tags:

c#

I've a list

    List<String> SampleList=new List<String>();

I need to fill a listView with the contents of the list

For example the "SampleList" contains

 a
 b
 c
 d

The listView should be filled like

 S.No         Item

  1             a
  2             b
  3             c
  4             d

Now i'm using for loop for this method

like

for(int i=0;i<SampleList.Count;i++)
   {
     listView1.Items.Add((i+1).ToString());
     listView1.Items[i].SubItems.Add(SampleList[i]);
   }

is there any other way to do this like data binding ?

Thanks in advance

like image 619
Thorin Oakenshield Avatar asked Jun 22 '10 08:06

Thorin Oakenshield


2 Answers

Not quite like databinding, but you could use VirtualMode and RetrieveVirtualItem

listView1.VirtualMode = true;
listView1.RetreiveVirtualItem += new RetrieveVirtualItemEventHandler( this.RetrieveVirtualItem );
listView1.VirtualListSize = SampleList.Count;

private void RetreiveVirtualItem( object sender, RetrieveVirtualItemEventArgs e )
{
     ListViewItem lvItem = new ListViewItem((e.ItemIndex + 1).ToString());
     lvItem.SubItems.Add(SampleList[e.ItemIndex]);
     e.Item = lvItem;
}
like image 181
jmoreno Avatar answered Oct 17 '22 11:10

jmoreno


Does it have to be a ListView? ListBox is simple:

        using (Form form = new Form())
        {
            List<string> strings = new List<string> {"abc", "def", "ghi"};
            form.Controls.Add(new ListBox() {DataSource = strings});
            Application.Run(form);
        }

For a richer display, DataGridView would also do this, but you need an extra bit of indirection (since it supports multiple columns, it needs a wrapper object per row):

        using (Form form = new Form())
        {
            List<string> strings = new List<string> {"abc", "def", "ghi"};
            var indirect = (from s in strings
                            select new {Text = s}).ToList();

            form.Controls.Add(new DataGridView() { DataSource = indirect });
            Application.Run(form);
        }

This also gives you opportunity to add in extra data, for example the number:

            var indirect = strings.Select((s,i) =>
                new {Index = i + 1, Text = s}).ToList();
like image 5
Marc Gravell Avatar answered Oct 17 '22 11:10

Marc Gravell