1

New to c# and .net and I'm trying to throw together a listview that has three columns, Quantity, Item description and Price. I know how to fill the rows with data and I can even add the subitem below but what I can't figure out is how I can group them together as a primary item with "children" items tied to it...

Sorry for my most likely incorrect verbiage, but this is what I am shooting for:

Qty    Description        Price
1      Widget             2.95
       Widget add on       .25
       Widget insurance   1.25
1      Sprocket           4.95
       Sprocket add on     .50

I am trying to figure out how to group the subitems below the primary item to make it where when I select, for instance, "Widget insurance", it highlights "Widget add on" and "Wiget" as one entity. So for example if I need to go back and remove "Widget insurance" from the purchase of the "Widget" I can click on any item connected to "Widget", ex. "Widget", "Widget add on" or "Widget insurance" and it will pull up another form that allows me to deselect "Widget insurance", hit OK and it would update the list accordingly...

I've (poorly) thrown together code that visually gives me what I am looking for, but I think I am completely confusing the use of subitem and it's purpose:

    string[] newItem = new string[3];

    ListViewItem itm;
    newItem[0] = "1";
    newItem[1] = "Widget";
    newItem[2] = "2.95";
    itm = new ListViewItem(newItem);

    listView1.Items.Add(itm);

    string[] newSubItem = new string[3];

    ListViewItem sub;
    newSubItem[0] = "";
    newSubItem[1] = "Widget add on";
    newSubItem[2] = ".25";
    sub = new ListViewItem(newSubItem);

    listView1.Items.Add(sub);

Any help would be greatly appreciated.

Giovanni S
  • 2,050
  • 18
  • 33

1 Answers1

0

Here you are. "Qty" will be ListViewItem's text. "Description" and "Price" will be ListViewItem's SubItems.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        listView1.View = View.Details;
        listView1.Columns.Add("Qty", 100, HorizontalAlignment.Left);
        listView1.Columns.Add("Description", 100, HorizontalAlignment.Left);
        listView1.Columns.Add("Prie", 100, HorizontalAlignment.Left);

        var details = new[] {"Widget", "2.95"};
        var item = new ListViewItem("1");
        item.SubItems.AddRange(details);
        listView1.Items.Add(item);


        details = new[]{ "Widget add on",".25"};
        item = new ListViewItem("");
        item.SubItems.AddRange(details);
        listView1.Items.Add(item);
    }
}

enter image description here

Hope this help.

hungndv
  • 2,121
  • 2
  • 19
  • 20
  • But how can I use this in the sense that if I select Widget add on, widget also highlights? I need to be able to tie these "subitems" together with their parent items and I can't quite figure it out. – Giovanni S Jul 06 '15 at 21:31