How to hide a column in a ListView control?

后端 未结 9 2329
慢半拍i
慢半拍i 2021-02-14 03:01

How can I hide a column in a ListView control, without setting the column Width property to 0?

Also, can I lock the Width

相关标签:
9条回答
  • 2021-02-14 03:32

    How to hide/show listview columns

    C#, .NET framework 3.5.

    It is easy to hide and show listview columns, if you use the listview in “virtual mode”. In “virtual mode”, you are responsible for filling the listviewitems with data. This makes it possible to put the correct data in the correct column.

    Let me demonstrate: Create a form, and add a listview control and a button control. Add 3 columns to the listview control. Set the “view” property of the listview control to “Details”. Set the “VirtualMode” property of the listview control to “True”. Set the “VirtualListSize” property of the listview control to “100”. Add a bool to the form:

    private bool mblnShow = true;
    

    Add the event “RetrieveVirtualItem” for the listview control, and add the following code:

    ListViewItem objListViewItem = new ListViewItem();
    objListViewItem.Text = "Item index: " + e.ItemIndex.ToString();
    if (mblnShow) objListViewItem.SubItems.Add("second column: " +     DateTime.Now.Millisecond.ToString());
    objListViewItem.SubItems.Add("third column: " + DateTime.Now.Millisecond.ToString());
    e.Item = objListViewItem;
    

    Add the “Click” event for the button control, and add the following code:

    mblnShow = !mblnShow;
    if (mblnShow && !this.listView1.Columns.Contains(this.columnHeader2))   this.listView1.Columns.Insert(1, this.columnHeader2);
    else if (!mblnShow && this.listView1.Columns.Contains(this.columnHeader2))
        this.listView1.Columns.Remove(this.columnHeader2);
    

    Run the application, and press the button to show and hide the second column.

    Please note that running a listview in virtual mode will throw an error if you put data in the items collection. There is much more the know about virtual mode, so I suggest reading about it before using it.

    0 讨论(0)
  • 2021-02-14 03:33

    Simply just remove column at the index you wish:

    listView1.Columns.RemoveAt(3);
    

    when you want it back just insert it with its name:

    listView1.Columns.Insert(3, "Column Name");
    

    It will back with its values.

    0 讨论(0)
  • 2021-02-14 03:37

    I was looking for a way to do the same thing which bring me here.

    I'm not sure if there is a better way of doing it however I use following workaround.

    If you need to add a value to Listview Item but don't want to show it, you can use a subitem index greater than total column count. This way, even though the value exists it is not visible

    0 讨论(0)
提交回复
热议问题