Newuser
Newuser

Reputation: 399

How to add to specific listview column

Currently I'm just using listviewitem.SubItems.Add() to add items to my listview.

The problem is that it only adds to the first 2 columns (Goes column by column).

I want to be able to add to any column, for example: skip the yymm, total trans and yyww columns and add to the amount in doc column.

enter image description here

This is how I currently add to the listview:

int totItems = Seq3.Count - 1;

if (PercentPopTolerance1.Count - 1 > totItems)
    totItems = PercentPopTolerance1.Count - 1;

for (int i = 0; i <= totItems; i++)
{
    ListViewItem lvi = new ListViewItem();
    string item1 = "";
    string item2 = "";

    if (Seq3.Count - 1 >= i)
        item1 = Seq3[i].ToString();

    if (PercentPopTolerance1.Count - 1 >= i)
        item2 = PercentPopTolerance1[i].ToString();

    lvi.SubItems.Add(item1);
    lvi.SubItems.Add(item2);

    listView2.Items.Add(lvi);
}

Upvotes: 2

Views: 107

Answers (2)

Grant Winney
Grant Winney

Reputation: 66449

I'd create a class to represent a row in the grid:

public class MyClass
{
    string SeqNum { get; set; }
    string Percent { get; set; }
    string YYMM { get; set; }
    string TotalTrans { get; set; }
    string YYWW { get; set; }
    string AmountInDoc { get; set; }
}

Then modify your code to create a list of those objects, insert only the values you need, and then attach the list to the grid.

(Note: This is all untested and you'll need to play with it to get it work in your situation.)

var myList = new List<MyClass>();

for (int i = 0; i <= totItems; i++)
{
    var myClass = new MyClass();

    if (Seq3.Count - 1 >= i)
        myClass.SeqNum = Seq3[i].ToString();

    if (PercentPopTolerance1.Count - 1 >= i)
        myClass.Percent = PercentPopTolerance1[i].ToString();

    myList.Add(myClass);
}

myGrid.ItemsSource = myList;

Upvotes: 2

BartoszKP
BartoszKP

Reputation: 35891

Just add an empty string to bypass unneeded columns:

lvi.SubItems.Add(item1);

lvi.SubItems.Add(string.Empty); // skip Percent column

lvi.SubItems.Add(item2);

Upvotes: 3

Related Questions