LordTitiKaka
LordTitiKaka

Reputation: 2156

How to remove columns from ListView c#

I'm new with ListView and encountered a small problem :

I have a ListViewin WinForm which I fill it line after line with many columns (about 15) , later on I have an option to save ListView to CSV . what I want is a way to let the user delete unwanted columns from ListView .

My function to create the columns at first

    private void checkAddListBoxColumns(DomainLayer.ScriptLogic.session sessionToAdd)
    {
        if (IsResultLogListViewFirstRun)
        {
            IsResultLogListViewFirstRun = false;
            this.Invoke((MethodInvoker)delegate
            {
                ResultsLogTab_ListView.Columns.Clear();
            });

            foreach (var item in sessionToAdd.comments.Keys)
            {
                this.Invoke((MethodInvoker)delegate
                {
                    ResultsLogTab_ListView.Columns.Add(item);
                });
            }
            McsTableRow mcsTR = new McsTableRow();
            Type t = mcsTR.GetType();
            foreach (/*PropertyInfo*/FieldInfo info in t.GetFields())
            {
                this.Invoke((MethodInvoker)delegate
                {
                    ResultsLogTab_ListView.Columns.Add(info.Name+" 1");
                });
            }
            foreach (FieldInfo info in t.GetFields())
            {
                this.Invoke((MethodInvoker)delegate
                {
                    ResultsLogTab_ListView.Columns.Add(info.Name+" 2");
                });
            }
            this.Invoke((MethodInvoker)delegate
            {
                ResultsLogTab_ListView.Columns.Add("Effective PHY Rate");
            });
            //...more of the same
        }
        else
        {
            //?
        }
    }

later I add line like

            private OnSessionToAdd()
            {
            foreach (string key in sessionToAdd.comments.Keys)
            {
                item.SubItems.Add(sessionToAdd.comments[key]);
            }

            Type t = sessionToAdd.CurrentMCSCheck.firstMcsRow.GetType();

            foreach (FieldInfo info in t.GetFields())
            {
                string x = info.GetValue(sessionToAdd.CurrentMCSCheck.firstMcsRow) as string;
                item.SubItems.Add(x);
            }

            t = sessionToAdd.CurrentMCSCheck.secondMcsRow.GetType();

            foreach (FieldInfo info in t.GetFields())
            {
                string x = info.GetValue(sessionToAdd.CurrentMCSCheck.secondMcsRow) as string;
                item.SubItems.Add(x);
            }

            item.SubItems.Add(sessionToAdd.CurrentMCSCheck.EffectivePHYRate);

            this.Invoke((MethodInvoker)delegate
            {
             ResultsLogTab_ListView.Items.Add(item);
            });
            }

What i need is a way to get all names of columns and than delete columns by name or some kind of IndexOf(name)

please point me to the right direction

EDIT

just to clearfy I dont to hide columns (settings width = 0) I want to delete them to help you understand my point I've added the way I save the ListView the way I save to CSV :

public StringBuilder ListViewToCSV(ListView listView, string filePath, bool includeHidden)
{
    //make header string
    StringBuilder result = new StringBuilder();
    WriteCSVRow(result, listView.Columns.Count, i => includeHidden || listView.Columns[i].Width > 0, i => listView.Columns[i].Text);

    //export data rows
    foreach (ListViewItem listItem in listView.Items)
        WriteCSVRow(result, listView.Columns.Count, i => includeHidden || listView.Columns[i].Width > 0, i => listItem.SubItems[i].Text);

    return result;

}

private static void WriteCSVRow(StringBuilder result, int itemsCount, Func<int, bool> isColumnNeeded, Func<int, string> columnValue)
{
    bool isFirstTime = true;
    for (int i = 0; i < itemsCount; i++)
    {
        if (!isColumnNeeded(i))
            continue;

        if (!isFirstTime)
            result.Append(",");
        isFirstTime = false;

        result.Append(String.Format("\"{0}\"", columnValue(i)));
    }
    result.AppendLine();
}

than just save StringBuilder

Upvotes: 2

Views: 7441

Answers (1)

Alex Wiese
Alex Wiese

Reputation: 8370

You can reference the column by name.

var columnToRemove = ResultsLogTab_ListView.Columns["Name Of Column"];

and then remove it

ResultsLogTab_ListView.Columns.Remove(columnToRemove);

This is all documented on MSDN which is a great resource.

Update

With regards to saving/loading from CSV let's say you have a List<string> of column names (obtained from said CSV file) you want to keep then you can use LINQ to find the columns that do not match, and then iterate over the result to remove them.

using System.Linq;

...

var columnNames = new List<string> { "one", "two", "three" };

var columnsToDelete = ResultsLogTab_ListView.Columns.Where(c => !columnNames.Contains(c.Name));

foreach(var column in columnsToDelete)
{
     ResultsLogTab_ListView.Columns.Remove(column);
}

Upvotes: 6

Related Questions