2

I have a WinForms application with a dataGridView which has 26 columns and is filled with data from a database. How can I allow users to hide the columns they don't want to see and show them again later? I know how to do it programmatically, but the question is how should the user do it. Here are my bad ideas:

  1. A list of checkboxes with each column to be clicked there - this is bad because the list would be too long and won't fit inside the form.

  2. A checkbox over each header, but I don't know how to make these checkboxes "stick" and horizontally scroll with the headers.

  3. Clicking on a header - this works well for hiding, but there is no way to show this column again.

So what would be the solution here?

4
  • 1
    One more bad one is to create a ContextMenuStrip that includes ToolStripMenuItem for each column. Check to show, UnCheck to hide. Commented Jan 29, 2020 at 13:21
  • 1
    @JQSOFT: Agree with you, that's what e.g. Windows Explorer does on the right pane. And Windows users are familiar with that procedure. Commented Jan 29, 2020 at 13:31
  • 1
    @JQSOFT Why is that a bad one? Many applications that allow to show/hide columns use something similar, Explorer included. -- Besides the previous solution (which you can easily adopt), you can also show/hide a CheckedListBox, using an option Button, maybe in an ad hoc configuration panel, if you plan on providing more options to configure the DGV layout/appearance. Commented Jan 29, 2020 at 13:31
  • 1
    @JQSOFT that sounds like an elegant improvement on my #1 idea, I like it Commented Jan 29, 2020 at 13:36

1 Answer 1

1

The best solution is to hide the columns after double-clicking the header and adding hidden columns to a popup menu. The popup menu contains only the hidden columns, so it is not too long. Clicking on a popup menu item removes it from the menu and shows the column.

screen of the program

Code:

private void DataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                string column = dataGridView1.Columns[e.ColumnIndex].Name;
                dataGridView1.Columns[column].Visible = false;
                contextMenuStrip1.Items.Add(column);
            }
        }

private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            var menuText = e.ClickedItem.Text;
            dataGridView1.Columns[menuText].Visible = true;
            contextMenuStrip1.Items.Remove(e.ClickedItem);
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.