user3613720
user3613720

Reputation: 47

How to put array values to specific column in listview in C#?

I created a two listview column 'Sample' and 'Quantity' in the design view mode. Now I want to add array data to mysample to 'Sample' column and myquantity to 'Quantity' column. But I am not how to specific which column the data the should go to. Please help. Here is my code -

str[] mysample = somedata;
str[] myquantity = somedata;

for (int i = 0,  i < mysample; i++)
    {
      ListViewItems item1 = new ListViewItem();
      item1.Subitems.Add(mysample[i].ToString());
      listview1.Items.add(item1);

      ListViewItems item2 = new ListViewItem();
      item1.Subitems.Add(myquantity[i].ToString());
      listview1.Items.add(item2);

     }

Upvotes: 0

Views: 4315

Answers (2)

Parsa Gachkar
Parsa Gachkar

Reputation: 21

First of all make sure the List View's View property is set to Details otherwise the columns wont show up.

You can either do it in the properties window or programmatically

listView1.View = View.Details;

Then you can add data to multiple columns by passing them to one of ListViewItem Class' Initializer Overloads as an Array (with desired sequence) and add it to Your ListView's Items

listView1.Items.Add(new ListViewItem(new[] {"column 1" , "column 2", ... }));

BTW your code will look like something Like This :

listView1.View = View.Details;
            String[] mySample =
            {
                "item 1",
                "item 2",
                "item 3"
            };
            String[] myQuantity =
            {
                "1",
                "2",
                "3"
            };
            for (var i = 0; i < mySample.Count(); i++)
            {
                listView1.Items.Add(new ListViewItem(new[] {mySample[i],myQuantity[i]}));
            }

also a piece of advise , Stop using WindowsForms and Learn WPF instead ;)

Upvotes: 1

Anton Kedrov
Anton Kedrov

Reputation: 1767

You need only one ListViewItem per row.

string[] mysample = { "Sample A", "Sample B", "Sample C"};
string[] myquantity = { "1", "2", "3"};

for (int i = 0; i < mysample.Length; i++)
{
    string[] subitems = new string[] { mysample[i], myquantity[i] };
    ListViewItem item = new ListViewItem(subitems);
    listView1.Items.Add(item);
}

Also note that to display columns, you should set the View to Details.

ListBox View property set to Details

Upvotes: 3

Related Questions