开发者

How to fill a list view with the contents of List<string> in 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());
     listV开发者_开发百科iew1.Items[i].SubItems.Add(SampleList[i]);
   }

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

Thanks in advance


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;
}


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();


Unfortunately windows forms ListView doesn't support DataBinding. But if you update the list frequently, maybe you can use INotifyProperty interface.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜