How to hide a column in a ListView control?

后端 未结 9 2331
慢半拍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.

提交回复
热议问题