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