Cortana
Cortana

Reputation: 189

How to add items to ObjectListView in C#

I recently tried to add a ObjectListView to my project instead of the normal ListView. But i can not add the Items or the SubItems to the ObjectListView. The ObjectListView is always empty when i try to fill it with this code:

 while (dr.Read())
            {
                OLVListItem item = new OLVListItem(dr["tn"].ToString());
                item.SubItems.Add(dr["title"].ToString());
                item.SubItems.Add(tickettime.ToString());
                item.SubItems.Add(Convert.ToDateTime(dr["date"]).ToString("dd.MM.yyyy"));
                item.SubItems.Add(dr["schlange"].ToString());
                item.SubItems.Add(dr["vorname"].ToString() + " " + dr["nachname"].ToString());

                Objectlistview.AddObject(item);
            }

can you please help me or send me some useful commands to add subitems or items generally.

Upvotes: 1

Views: 3399

Answers (1)

user3784340
user3784340

Reputation: 74

I have had better luck with TreeListView.

It is best to have a list of objects. You make your changes to this list and then reflect these changes to the TreeListView using "SetObjects".

If each object in the list has a variable (for example name) those variables must be reflected on the TreeListView columns under "Aspect Name" in order for them to display.

Each Object in the main list should have a list of its own. Thats if you want to show sub items.

    public Form1()
    {
        InitializeComponent();
        // model is the currently queried object, we return true or false according to the amount of children we have in our Children List
        trLstVwResults.CanExpandGetter = model => ((MyClass)model).
                                                      Children.Count > 0;
        // We return the list of Children that shall be considered Children.

        trLstVwResults.ChildrenGetter = delegate(object model)
        {
            return ((MyClass)model).Children;
        }; 
    }

            private void btnAdd_Click(object sender, EventArgs e)
    {
        var MyClasses = new List<MyClass>();
        MyClasses.Add(new MyClass("Bob"));
        MyClasses.Add(new MyClass("John"));

        var mikeClass = new MyClass("Mike");

        var joeClass = new MyClass("Joe");

        mikeClass.addChildren(joeClass);

        MyClasses.Add(mikeClass);

        trLstVwResults.SetObjects(MyClasses);
    }

The Class would look as follows:

public class MyClass
{
    public string Name { get; set; }
    public List<MyClass> Children { get; set; }
    public MyClass(string name)
    {
        Name = name;
        Children = new List<MyClass>();
    }

    public void addChildren(MyClass tt)
    {
        Children.Add(tt);
    }
}

(Don't forget to set the aspect name in properties)

Upvotes: 0

Related Questions