How to copy selected columns of a listview to another

I have two listviews.  One has 5 columns, the other has 2.  I want to copy cols 1 and 3 from the first listview to the second listview.

How do I do this?
rmmarshAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

MarkusLoiblCommented:
Are there any datarows displayed at the listviews? If yes, where do the data for the new destination columns come from?  
0
Meir RivkinFull stack Software EngineerCommented:
here's the code below.
to use it simply pass an array of indices (int []) and source listview and destination listview.
for example:
CopyColumns(new int[] { 2, 0, 3 }, listView1, listView2);

will copy 3rd column, then 1st column then 4 column from listview1 to listview2.
the columns will be added after the last column in the destination listview.
the function also take case of the data in those columns and copy them as well.
in case destination listview has fewer items (rows) than source listview, new items will be added with relevant subitems to fill the columns data.

 /// <summary>
        /// Copies the columns.
        /// </summary>
        /// <param name="indices">The indices.</param>
        /// <param name="listSrc">The list SRC.</param>
        /// <param name="listDest">The list dest.</param>
        private void CopyColumns(int[] indices, ListView listSrc, ListView listDest)
        {
            foreach (int colindex in indices)
            {
                ColumnHeader ch = listSrc.Columns[colindex];
                //clone the column from listview1 and add to listview2
                listDest.Columns.Add(ch.Clone() as ColumnHeader);

                //iterate items to fill data in new columns
                foreach (ListViewItem item in listSrc.Items)
                {
                    string val = item.SubItems[colindex].Text;

                    //listview1 has more items than listview2 we need first to add new item 
                    //and also add subitem for the new column
                    if (listDest.Items.Count < item.Index + 1)
                    {
                        listDest.Items.Add(new ListViewItem(listDest.Columns.Cast<ColumnHeader>().Select(n => string.Empty).ToArray()));
                        listDest.Items[item.Index].SubItems[listDest.Columns.Count - 1].Text = val;
                    }
                    else//just add the subitem for the new column
                    {
                        listDest.Items[item.Index].SubItems.Add(val);
                    }
                }
            }
        }

Open in new window

before.jpg
after.jpg
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Meir RivkinFull stack Software EngineerCommented:
one last thing, the function do not validate the indices so u need to make sure indices are not out of range.
0
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

rmmarshAuthor Commented:
Sorry it's taken me so long to get back to you... I am unable to compile your code.  Under C# .NET v2.0, I get the following error:

Error    2    'System.Windows.Forms.ListView.ColumnHeaderCollection' does not contain a definition for 'Cast' and no extension method 'Cast' accepting a first argument of type 'System.Windows.Forms.ListView.ColumnHeaderCollection' could be found (are you missing a using directive or an assembly reference?)  

How do i fix this?
0
Meir RivkinFull stack Software EngineerCommented:
let me fix it for you...
0
Meir RivkinFull stack Software EngineerCommented:
replace line 24 :
                       listDest.Items.Add(new ListViewItem(listDest.Columns.Cast<ColumnHeader>().Select(n => string.Empty).ToArray()));
 
with this one:

listDest.Items.Add(new ListViewItem(new string[listDest.Columns.Count]));
0
rmmarshAuthor Commented:
Hmmm... is there a way I can move from source to a string, then add to the destination?  I need to shorten the length of field 1, and format field 3.

I really appreciate your help... Listview's really confuse me! :D
0
Meir RivkinFull stack Software EngineerCommented:
if u want to manipulate listview source values before adding to destination lisview, add your code after line 18:

string val = item.SubItems[colindex].Text;
//add your code here

0
Meir RivkinFull stack Software EngineerCommented:
now, u can modify val as u wish, if u need to know which field are you in the loop, u can use
ColumnHeader ch variable from line 11:

ch.Text -> is the field name
0
rmmarshAuthor Commented:
Thank you so very much... I really appreciate your help and patience.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.