Search code examples
c#winformsdatagridviewscrollbarvisible

How can make columns visible easly?


My project has a DataGridView with 52 columns and some of columns are not visible. But I want the user to make them visible easily. So I added a button as you see on the pic below. This makes five columns visible.

But the problem when scrolling, this Button stay static on form. I want this button anchored to a specific column header. Movable with column header.

So i tried to put the DataGridView and Button contols on same panel as children. That's worked but panel scroll is not functional as much as DataGridView's scroll. For example in panel scrolling freezed columns is not working.

Is there any solution for this. I want the user to make columns visible or not visible easily like Excel. it is not necessary to use a buttons. İf there any another options, I am interested.

button_on_datagridviewColumn_Header


Solution

  • I'll show an example of how you can use the context menu to show and hide DataGridView columns.

    Add menu to Form:

    ContextMenuStrip columnMenu;
    

    Create menu like this. Each column has one menu item with a checkbox.
    Of course, you can create and fill it in manually in the designer.

    private void Form1_Load(object sender, EventArgs e)
    {
        columnMenu = new ContextMenuStrip();
    
        foreach (DataGridViewColumn column in dataGridView.Columns)
        {
            var item = new ToolStripMenuItem();
            item.Text = column.Name;
            item.CheckOnClick = true;
            item.Checked = true;
            item.Click += Item_Click;
            columnMenu.Items.Add(item);
        }
    }
    

    When you select a menu item, show or hide the column.

    private void Item_Click(object sender, EventArgs e)
    {
        var item = (ToolStripMenuItem)sender;
        dataGridView.Columns[item.Text].Visible = item.Checked;
    }
    

    Subscribe the DataGridView on the event:

    dataGridView.ColumnHeaderMouseClick += DataGridView_ColumnHeaderMouseClick;
    

    In this event handler, show the menu.

    private void DataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        columnMenu.Show(MousePosition);
    }