foreach loop not producing variables correctly - listview columns

71 views Asked by At

I'm afraid I'm with a basic issue (probably too tired at the time)

I'm generating multiple objects with a foreach loop as it follows:

 List<string> columnnames = new List<string> {"column 1", "column 2", "column 3"};
            int i = 0;           
            foreach (string col in columnnames)
            {
                var col1 = new BrightIdeasSoftware.OLVColumn(col, col);
                col1.AspectGetter = x => (x as NodeN).Columns[i];
                this.treeListView1.Columns.Add(col1);
                i++;
            }

But the results are incorrect, and only work if I generate every column by itself such as:

var col1 = new BrightIdeasSoftware.OLVColumn("", "");
            col1.AspectGetter = x => (x as NodeN).Columns[0];
            this.treeListView1.Columns.Add(col1);

            var col2 = new BrightIdeasSoftware.OLVColumn("", "");
            col2.AspectGetter = x => (x as NodeN).Columns[1];
            this.treeListView1.Columns.Add(col2);

I did try setting col1 = null; at the end of foreach loop, but this unfortunately is not producing the same results. I also seem to have an index error unless I set i with maximum value of 2 on the 2nd line of the foreachloop.

Any hint what can be wrong?

0

There are 0 answers