0

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

     }
1
  • Generally you add each subsequent (after the first) column of a ListView object (ListViewItem) as a subitem of the original ListViewItem. Commented May 29, 2015 at 20:06

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.