开发者

Hide ID column in ListView control

I'm binding ListView control to DataTable. The DataTable have a column named ProductID. Is there any way to hide this column, because I'm gonna need it's value later开发者_Python百科?


I'll just address the UI angle. You can hide it by setting the column width to 0. For example, if the ID is bound to the 2nd column:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        listView1.Columns[1].Width = 0;
        listView1.ColumnWidthChanging += listView1_ColumnWidthChanging;
    }

    private void listView1_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e) {
        if (e.ColumnIndex == 1) {
            e.NewWidth = 0;
            e.Cancel = true;
        }
    }
}

It's not quite ideal, the user can get confuzzled by the 'splitter' cursor that shows up when she's a bit too far to the right of the column divider. That's very hard to fix.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜